feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #27.
This commit is contained in:
1 parent
188b2c2e55
commit
728ffa35cb
729 files changed
+26954
-1652
No files matched your search
@@ -367,7 +367,7 @@
|
||||
<DataTemplate DataType="{x:Type ar:TrashRowViewModel}">
|
||||
<DockPanel Height="48">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Archive.Trash.Restore}" Command="{Binding RestoreCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Archive.TrashRestore}" />
|
||||
ToolTip="{Binding RestoreToolTip}" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding DeletedText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Margin="12,0"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
<StackPanel VerticalAlignment="Center">
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -9,6 +10,7 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
@@ -22,9 +24,16 @@ public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
|
||||
/// <summary>"Photos", "Sequence": what the entry holds.</summary>
|
||||
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
|
||||
|
||||
/// <summary>"Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
|
||||
public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
|
||||
Formatting.LeftToRight(Entry.Folder));
|
||||
/// <summary>
|
||||
/// "Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language); a videos
|
||||
/// entry has no photos: "Videos · 1.2 GB · …".
|
||||
/// </summary>
|
||||
public string Detail => Entry.Kind == TrashKind.Videos
|
||||
? string.Join(Loc.Separator, KindText, Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder))
|
||||
: string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
|
||||
|
||||
/// <summary>What Restore brings back: the render into its sequence's renders, or the sequence or photos.</summary>
|
||||
public string RestoreToolTip => Entry.Kind == TrashKind.Videos ? Loc.L("Tooltips.Archive.TrashRestoreVideo") : Loc.L("Tooltips.Archive.TrashRestore");
|
||||
|
||||
/// <summary>"Deleted 02/10/2026 18:04".</summary>
|
||||
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
|
||||
@@ -175,6 +184,11 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
|
||||
try
|
||||
{
|
||||
if (entry.Kind == TrashKind.Videos)
|
||||
{
|
||||
await RestoreVideoAsync(entry);
|
||||
return;
|
||||
}
|
||||
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
|
||||
BusyText = null;
|
||||
@@ -205,6 +219,27 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A render deleted from Videos goes back among its sequence's renders after its hash is checked (the videos library
|
||||
/// refuses a file that changed in the trash, or a sequence that is gone, and says why).
|
||||
/// </summary>
|
||||
private async Task RestoreVideoAsync(TrashEntry entry)
|
||||
{
|
||||
try
|
||||
{
|
||||
var render = await Task.Run(() => _archives.Videos.RestoreAsync(entry.ArchiveId, entry.Name));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash (render {render.Id})");
|
||||
Rows = [.. _rows.Where(r => r.Entry != entry)];
|
||||
await _restored();
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
Log.Warning("archive", $"Restoring {entry.Title} failed: {ex.Code}", ex);
|
||||
var text = VideoText.Error(ex, entry.Title);
|
||||
ShowMessage(text, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash:
|
||||
/// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that
|
||||
|
||||
@@ -8,6 +8,7 @@ using Chronos.App.Jobs;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
@@ -74,6 +75,8 @@ public sealed class SampleData
|
||||
if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment.");
|
||||
var settings = services.Settings;
|
||||
var sample = new SampleData(services);
|
||||
// Not this PC's own Videos folder, so Settings › Archive reads the same on any machine; set before Settings reads it.
|
||||
settings.VideosFolder = @"D:\Videos\Chronos";
|
||||
services.Server.Dispose();
|
||||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(sample), new PlainTokenProtector());
|
||||
services.Encoders = new SampleEncoders();
|
||||
@@ -442,6 +445,143 @@ public sealed class SampleData
|
||||
/// <summary>The editor sample with a colour look (owner review 1, R6): Sepia at 60 %.</summary>
|
||||
public static ProjectSettings SepiaLook(ProjectSettings project) => ExposureTab.WithLook(project, "sepia", 0.6);
|
||||
|
||||
/// <summary>The editor sample played as a boomerang twice, fading in over 1 s and out over 1.5 s (settings format 3).</summary>
|
||||
public static ProjectSettings Boomerang(ProjectSettings project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return project with
|
||||
{
|
||||
Export = project.Export with { Playback = new PlaybackSettings { Direction = PlaybackDirection.Boomerang, Loops = 2, FadeIn = 1, FadeOut = 1.5 } },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Videos section's sample (owner review 1, R9), on sequences the server does not hold (so the sync table keeps its
|
||||
/// own sample): this PC's 4K video of Comet over the ridge, which the server holds too and which was copied to the videos
|
||||
/// folder, a still saved from it, a 1080p share and a PNG image sequence of Clouds over the Langhe, and last year's render
|
||||
/// of Fog lifting whose file is gone; two renders the sample server alone holds; and a GIF of a workspace project not sent
|
||||
/// yet. The files are small stand-ins (the still a real JPEG); sizes, durations and dates are the records', all from
|
||||
/// <see cref="Now"/>. The section reads the server's and the workspace's renders from here.
|
||||
/// </summary>
|
||||
public async Task FillVideosAsync(Sections.VideosViewModel videos)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(videos);
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
async Task<Sequence> LocalAsync(string text) => (await db.Sequences.ListAsync(new Data.Repositories.SequenceQuery { Text = text, Limit = 1 })).Items[0];
|
||||
var root = Path.Combine(_services.Environment.DataDirectory, "archive");
|
||||
var comet = await LocalAsync("Comet over the ridge");
|
||||
var clouds = await LocalAsync("Clouds over the Langhe");
|
||||
var fog = await LocalAsync("Fog lifting");
|
||||
string FolderOf(Sequence s) => Path.Combine(root, s.Folder.Replace('/', Path.DirectorySeparatorChar));
|
||||
string Output(Sequence s, string name) => Path.Combine(FolderOf(s), "exports", $"{s.FirstCapture:yyyy-MM-dd} {s.DisplayTitle} - {name}");
|
||||
|
||||
Render Make(Sequence s, string preset, string file, string codec, int width, int height, double fps, double seconds, long bytes, DateTimeOffset created,
|
||||
string? kind = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = s.Id,
|
||||
PresetName = preset,
|
||||
OutputPath = Output(s, file),
|
||||
Codec = codec,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Fps = fps,
|
||||
DurationSeconds = seconds,
|
||||
Bytes = bytes,
|
||||
Created = created,
|
||||
ProducedBy = "studio-pc",
|
||||
Kind = kind,
|
||||
};
|
||||
var cometVideo = Make(comet, "4K HEVC", "4K HEVC.mp4", "hevc", 3840, 2160, 24, 41.9, 1_380_000_000L, Now.AddDays(-2).AddHours(-3));
|
||||
var cometStill = Make(comet, "Frame 512", "Frame 512.jpg", "jpegsequence", 3840, 2160, 0, 0, 3_400_000L, Now.AddDays(-1).AddHours(-1), RenderKind.Still);
|
||||
var cloudsShare = Make(clouds, "1080p share", "1080p share.mp4", "h264", 1920, 1080, 30, 44, 186_000_000L, Now.AddDays(-20));
|
||||
var cloudsFrames = Make(clouds, "PNG frames", "PNG frames", "pngsequence", 3840, 2160, 24, 55, 6_240_000_000L, Now.AddDays(-21).AddHours(-2));
|
||||
var fogArchive = Make(fog, "4K archive", "4K archive.mp4", "hevc", 3840, 2160, 24, 40.8, 1_120_000_000L, new DateTimeOffset(2025, 12, 4, 19, 40, 0, TimeSpan.Zero));
|
||||
foreach (var render in new[] { cometVideo, cometStill, cloudsShare, cloudsFrames, fogArchive }) await db.Renders.InsertAsync(render);
|
||||
|
||||
foreach (var render in new[] { cometVideo, cloudsShare }) WriteStandIn(render.OutputPath);
|
||||
Directory.CreateDirectory(cloudsFrames.OutputPath);
|
||||
WriteStandIn(Path.Combine(cloudsFrames.OutputPath, "frame_000001.png"));
|
||||
// The still is one of the sequence's own photos, so its card and the player show a picture.
|
||||
File.Copy(Directory.EnumerateFiles(FolderOf(comet), "*.JPG").Order(StringComparer.Ordinal).First(), cometStill.OutputPath, overwrite: true);
|
||||
await db.RenderCopies.InsertAsync(new RenderCopy
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
RenderId = cometVideo.Id,
|
||||
Path = Path.Combine(@"D:\Videos\Chronos", Path.GetFileName(cometVideo.OutputPath)),
|
||||
Bytes = cometVideo.Bytes,
|
||||
CopiedAt = Now.AddDays(-1),
|
||||
CopiedBy = "studio-pc",
|
||||
});
|
||||
|
||||
VideoDto OnServer(Guid id, Guid sequence, string title, DateTime first, string preset, string codec, int width, int height, double fps, double seconds, long bytes,
|
||||
DateTimeOffset created, string? project = null) =>
|
||||
new(id, sequence, preset, codec, width, height, fps, seconds, bytes, created, "nas", null, null, null, RenderKind.Video, title, first, project, project is null ? null : 3,
|
||||
VideoStates.Ok, [], $"{first:yyyy-MM-dd} {title} - {preset}.mp4");
|
||||
IReadOnlyList<VideoDto> server =
|
||||
[
|
||||
OnServer(Guid.CreateVersion7(), _sunrise, "Sunrise over Superga", new DateTime(2026, 7, 2, 5, 12, 0), "4K HEVC", "hevc", 3840, 2160, 24, 120, 3_960_000_000L, Now.AddHours(-6)),
|
||||
OnServer(cometVideo.Id, comet.Id, comet.DisplayTitle, comet.FirstCapture!.Value, cometVideo.PresetName, "hevc", 3840, 2160, 24, 41.9, cometVideo.Bytes, cometVideo.Created),
|
||||
OnServer(Guid.CreateVersion7(), _lakeComo, "Lake Como storm", new DateTime(2026, 8, 21, 16, 30, 0), "Vertical 1080p", "h264", 1080, 1920, 30, 48.3, 248_000_000L,
|
||||
Now.AddDays(-30), project: "Vertical social"),
|
||||
];
|
||||
|
||||
var milan = await LocalAsync("Milan skyline dusk");
|
||||
var gif = Path.Combine(_services.Environment.DataDirectory, "workspace-sample", "exports", $"{milan.FirstCapture:yyyy-MM-dd} {milan.DisplayTitle} - GIF preview.gif");
|
||||
WriteStandIn(gif);
|
||||
IReadOnlyList<VideoEntry> workspace =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = milan.Id,
|
||||
Title = milan.DisplayTitle,
|
||||
PresetName = "GIF preview",
|
||||
Codec = "gif",
|
||||
Width = 960,
|
||||
Height = 540,
|
||||
Fps = 12,
|
||||
DurationSeconds = 8,
|
||||
Bytes = 24_600_000L,
|
||||
Created = Now.AddHours(-3),
|
||||
Kind = RenderKind.Video,
|
||||
FileName = Path.GetFileName(gif),
|
||||
LocalPath = gif,
|
||||
IsUnsent = true,
|
||||
WorkspaceProjectId = Guid.CreateVersion7(),
|
||||
ProjectName = "Social cut",
|
||||
},
|
||||
];
|
||||
|
||||
videos.ServerVideos = () => new VideoServer(VideoServerState.Available, () => new SampleRemoteVideos(server), CanEdit: true, CanDelete: true);
|
||||
videos.WorkspaceRenders = _ => Task.FromResult(workspace);
|
||||
|
||||
static void WriteStandIn(string path)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllBytes(path, new byte[4096]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sample server's videos library: one page, read only.</summary>
|
||||
private sealed class SampleRemoteVideos(IReadOnlyList<VideoDto> videos) : IRemoteVideos
|
||||
{
|
||||
public Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) => Task.FromResult(new VideoPageDto(videos, null, videos.Count));
|
||||
|
||||
public Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) =>
|
||||
throw new NotSupportedException("The sample server deletes no videos.");
|
||||
|
||||
public Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default) =>
|
||||
throw new NotSupportedException("The sample server deletes no videos.");
|
||||
|
||||
public Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) =>
|
||||
throw new NotSupportedException("The sample server copies no videos.");
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A deep analysis of <paramref name="sequenceId"/> half way through: the editor's busy state (settings wait, viewing stays live).</summary>
|
||||
public async Task MarkAnalysingAsync(Guid sequenceId)
|
||||
{
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Columns of the Export tab's preset grid: as many as fit at <see cref="MinCardWidth"/> (four at 1440 px, three at 1200 px).</summary>
|
||||
public sealed class CardColumns : IValueConverter
|
||||
{
|
||||
public const double MinCardWidth = 200;
|
||||
|
||||
public static CardColumns Instance { get; } = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
|
||||
value is double width && double.IsFinite(width) ? int.Max(1, (int)(width / MinCardWidth)) : 4;
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<!--
|
||||
The measuring tool of each step, below the filmstrip (BRIEF §12.3): the Analysis step's findings, luminance, flicker
|
||||
and waveform, camera path and sky charts, the frame table, the keyframe and time-remap curve editors with the plan
|
||||
chart, and the Export step's preset cards. Clicking a chart seeks the preview.
|
||||
chart, and the Export step's preset table. Clicking a chart seeks the preview.
|
||||
-->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Editor/EditorStyles.xaml" />
|
||||
@@ -272,44 +272,80 @@
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Export: preset cards at least 200 px wide (four per row in Export.html at 1440 px, three at 1200 px). -->
|
||||
<!--
|
||||
Export: the preset table (owner review 1, R3; decision 3). Column headers, then each preset group behind a header that
|
||||
opens or closes it, one 28 px row per preset: the batch tick, the name with the Recommended chip, size, codec, fps and
|
||||
the two estimates. Clicking a row selects the preset; the tick adds it to the batch.
|
||||
-->
|
||||
<DataTemplate DataType="{x:Type e:PresetRow}">
|
||||
<!-- Disabled while a job runs or the project cannot change: the row's tooltip says why. -->
|
||||
<Button Style="{StaticResource Button.PresetRow}" Command="{Binding SelectCommand}" CommandParameter="{Binding}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding Name}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Tick}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Size}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Codec}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Fps}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.EstimatedSize}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.EstimatedTime}" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<CheckBox IsChecked="{Binding IsInBatch}" Visibility="{Binding CanBatch, Converter={StaticResource BoolToVisibility}}" VerticalAlignment="Center"
|
||||
ToolTip="{Binding BatchToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.InBatch}" />
|
||||
<DockPanel Grid.Column="1" Margin="0,0,8,0">
|
||||
<Border DockPanel.Dock="Right" Style="{StaticResource Border.Recommended}" Visibility="{Binding IsRecommended, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Editor.Export.Recommended}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" />
|
||||
</Border>
|
||||
<TextBlock x:Name="Name" Text="{Binding Name}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
<TextBlock Grid.Column="2" Text="{Binding Size}" Style="{StaticResource Text.Cell}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="3" Text="{Binding Codec}" Style="{StaticResource Text.Cell}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="4" Text="{Binding Fps}" Style="{StaticResource Text.Cell}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="5" Text="{Binding EstimatedSize}" Style="{StaticResource Text.Cell}" FontSize="{StaticResource Size.Secondary}" />
|
||||
<TextBlock Grid.Column="6" Text="{Binding EstimatedTime}" Style="{StaticResource Text.Cell}" FontSize="{StaticResource Size.Secondary}" />
|
||||
</Grid>
|
||||
</Button>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsSelected}" Value="True">
|
||||
<Setter TargetName="Name" Property="FontWeight" Value="SemiBold" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:PresetGroup}">
|
||||
<StackPanel Margin="0,0,0,2">
|
||||
<ToggleButton Style="{StaticResource ToggleButton.Group}" IsChecked="{Binding IsExpanded}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Name}">
|
||||
<TextBlock Text="{Binding Header}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
|
||||
</ToggleButton>
|
||||
<ItemsControl ItemsSource="{Binding Rows}" Focusable="False" Visibility="{Binding IsExpanded, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:ExportTab}">
|
||||
<ScrollViewer Margin="0,10,0,0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<ItemsControl ItemsSource="{Binding Cards}" Focusable="False" IsEnabled="{Binding Editor.IsEditable}" Margin="-5,0,-5,0">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<UniformGrid Columns="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=ItemsControl}, Converter={x:Static e:CardColumns.Instance}}" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:PresetCard}">
|
||||
<!-- Disabled while a job runs or the project cannot change: the card's tooltip says why. -->
|
||||
<Button Style="{StaticResource Button.PresetCard}" Command="{Binding SelectCommand}" CommandParameter="{Binding}" ToolTip="{Binding ToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding Name}">
|
||||
<DockPanel>
|
||||
<!-- The chip moves under the name when both do not fit on one line. -->
|
||||
<WrapPanel DockPanel.Dock="Top">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Border Style="{StaticResource Border.Recommended}" Margin="0" Visibility="{Binding IsRecommended, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Editor.Export.Recommended}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" />
|
||||
</Border>
|
||||
</WrapPanel>
|
||||
<DockPanel DockPanel.Dock="Bottom">
|
||||
<CheckBox DockPanel.Dock="Right" IsChecked="{Binding IsInBatch}" Visibility="{Binding CanBatch, Converter={StaticResource BoolToVisibility}}"
|
||||
ToolTip="{Binding BatchToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.InBatch}" Margin="6,0,0,0" />
|
||||
<TextBlock Text="{Binding Estimate}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
</DockPanel>
|
||||
<StackPanel Margin="0,4,0,0">
|
||||
<TextBlock Text="{Binding Format}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Encoding}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis"
|
||||
Margin="0,4,0,0" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="10,6,10,6" Margin="0,10,0,0">
|
||||
<DockPanel>
|
||||
<Grid DockPanel.Dock="Top" Margin="6,0,6,2" MinHeight="24">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Tick}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Size}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Codec}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.Fps}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.EstimatedSize}" />
|
||||
<ColumnDefinition Width="{StaticResource Export.Column.EstimatedTime}" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.Name}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.Size}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.Codec}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.Fps}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.EstimatedSize}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Export.Column.EstimatedTime}" />
|
||||
</Grid>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<ItemsControl ItemsSource="{Binding PresetGroups}" Focusable="False" />
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -371,51 +371,80 @@
|
||||
</ContentControl>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Export: the Output panel (Export.html aside). -->
|
||||
<!--
|
||||
A collapsible group's header (owner review 1, R3; DESIGN §4): the name in Text.Body 600 and, while the group is collapsed,
|
||||
the muted one-line summary of its values. Open or closed is kept per group by the app, not in the project.
|
||||
-->
|
||||
<DataTemplate DataType="{x:Type e:SettingGroup}">
|
||||
<ToggleButton Style="{StaticResource ToggleButton.Group}" IsChecked="{Binding IsExpanded}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Header}"
|
||||
Margin="-2,4,0,4">
|
||||
<DockPanel>
|
||||
<TextBlock Text="{Binding Header}" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding Summary}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Secondary}" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis" Visibility="{Binding IsExpanded, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</DockPanel>
|
||||
</ToggleButton>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- A playback choice the export cannot take now (Boomerang with star trails): disabled, its reason in the tooltip. -->
|
||||
<Style x:Key="ComboBoxItem.Gated" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
|
||||
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
Export: the Output panel (Export.html aside; owner review 1, R3). The title, then four collapsible groups that scroll
|
||||
(Output, Encoding, Playback, File) with the notices, and a fixed footer: the result line, Render now, Add to queue,
|
||||
Batch (n), and the Videos (n), Reveal and Send again links.
|
||||
-->
|
||||
<DataTemplate DataType="{x:Type e:ExportTab}">
|
||||
<Border Style="{StaticResource Border.EditorPanel}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding Title}" Style="{StaticResource Text.Section}" Margin="0,0,0,12" TextTrimming="CharacterEllipsis" />
|
||||
<StackPanel DockPanel.Dock="Bottom" Margin="0,12,0,0">
|
||||
<Grid Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Content="{l:Loc Editor.Export.AddToQueue}" Command="{Binding AddToQueueCommand}" ToolTip="{Binding AddToQueueToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Grid.Column="1" Content="{l:Loc Editor.Export.Batch}" Margin="8,0,0,0" Command="{Binding BatchCommand}" ToolTip="{Binding BatchToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
<Button Style="{StaticResource Button.Primary}" Height="36" Content="{l:Loc Editor.Export.RenderNow}" Command="{Binding RenderNowCommand}"
|
||||
ToolTip="{Binding Editor.RenderToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<DockPanel Margin="0,8,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.HistoryLink}" Command="{Binding HistoryCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Render.SendAgain}" Command="{Binding SendAgainCommand}"
|
||||
ToolTip="{Binding SendAgainToolTip}" ToolTipService.ShowOnDisabled="True" Margin="6,0,0,0"
|
||||
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}"
|
||||
VerticalAlignment="Center" Margin="6,0,0,0" ToolTip="{Binding UnsentToolTip}"
|
||||
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
ToolTip="{Binding HistoryText}" />
|
||||
</DockPanel>
|
||||
<!-- A .chronos project file that opens this sequence with these settings (BRIEF §18). -->
|
||||
<Button Style="{StaticResource Button.Link}" HorizontalAlignment="Left" Margin="0,8,0,0" Content="{l:Loc Editor.ProjectFile.Save}"
|
||||
Command="{Binding SaveProjectCommand}" ToolTip="{Binding SaveProjectToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
|
||||
<v:SplitButton Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
|
||||
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True"
|
||||
DropDownToolTip="{l:Loc Tooltips.Editor.Export.RestoreChoice}" AutomationProperties.Name="{l:Loc Editor.Export.RestoreName}"
|
||||
Visibility="{Binding HasSavedCopies, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding Title}" Style="{StaticResource Text.Section}" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" />
|
||||
|
||||
<Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Margin="0,8,0,0" Padding="0,10,0,0">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding FooterSummary}" TextWrapping="Wrap" MaxHeight="36" TextTrimming="CharacterEllipsis" FontSize="{StaticResource Size.Secondary}"
|
||||
Foreground="{DynamicResource Brush.TextMuted}" Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Export.Footer.Summary}" />
|
||||
<Button Style="{StaticResource Button.Primary}" Height="36" Margin="0,8,0,0" Content="{l:Loc Editor.Export.RenderNow}" Command="{Binding RenderNowCommand}"
|
||||
ToolTip="{Binding Editor.RenderToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Content="{l:Loc Editor.Export.AddToQueue}" Command="{Binding AddToQueueCommand}" ToolTip="{Binding AddToQueueToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Grid.Column="1" Content="{Binding BatchText}" Margin="8,0,0,0" Command="{Binding BatchCommand}" ToolTip="{Binding BatchToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
<WrapPanel Margin="0,8,0,0">
|
||||
<Button Style="{StaticResource Button.Link}" Content="{Binding VideosText}" Command="{Binding VideosCommand}" ToolTip="{l:Loc Tooltips.Export.Footer.Videos}"
|
||||
ToolTipService.ShowOnDisabled="True" Margin="0,0,12,0" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="0,0,12,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Render.SendAgain}" Command="{Binding SendAgainCommand}"
|
||||
ToolTip="{Binding SendAgainToolTip}" ToolTipService.ShowOnDisabled="True" Margin="0,0,6,0"
|
||||
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" VerticalAlignment="Center"
|
||||
ToolTip="{Binding UnsentToolTip}" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" Margin="0,0,12,0" />
|
||||
<!-- A .chronos project file that opens this sequence with these settings (BRIEF §18); a workspace project has it in its project ▾ menu. -->
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Editor.ProjectFile.Save}" Command="{Binding SaveProjectCommand}"
|
||||
ToolTip="{Binding SaveProjectToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding Editor.HasProject, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<Grid>
|
||||
<StackPanel>
|
||||
<!-- ===== Output ===== -->
|
||||
<ContentControl Content="{Binding OutputGroup}" Focusable="False" />
|
||||
<Grid Margin="0,4,0,8" IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding OutputGroup.IsExpanded, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
@@ -428,10 +457,6 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Container}" ToolTip="{l:Loc Editor.Export.Container}" />
|
||||
<ComboBox Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Containers}" SelectedItem="{Binding SelectedContainer}" DisplayMemberPath="Label"
|
||||
@@ -441,8 +466,12 @@
|
||||
<ComboBox Grid.Row="1" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding CodecChoices}" SelectedItem="{Binding SelectedCodec}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.Codec}" AutomationProperties.Name="{l:Loc Editor.Export.Codec}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Resolution}" ToolTip="{l:Loc Editor.Export.Resolution}" />
|
||||
<Grid Grid.Row="2" Grid.Column="1" Margin="0,0,0,8">
|
||||
<!-- A standard size fitted to the chosen proportions (4K at 9:16 = 2160×3840), or Custom with Width × Height. -->
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Export.Resolution.Standard}" ToolTip="{l:Loc Export.Resolution.Standard}" />
|
||||
<ComboBox Grid.Row="2" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Resolutions}" SelectedItem="{Binding SelectedResolution}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Export.Resolution}" AutomationProperties.Name="{l:Loc Export.Resolution.Standard}" />
|
||||
|
||||
<Grid Grid.Row="3" Grid.Column="1" Margin="0,0,0,8" Visibility="{Binding IsCustomResolution, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="56" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@@ -458,12 +487,12 @@
|
||||
</Grid>
|
||||
|
||||
<!-- What is rendered: the chosen proportions fitted in the box above (owner review 1, R5), "(capped)" when the encoder shrinks it. -->
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.OutputSize}" ToolTip="{l:Loc Editor.Export.OutputSize}" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" Margin="0,0,0,8" MinHeight="24" Style="{StaticResource Text.Number}" Text="{Binding OutputSizeText}"
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.OutputSize}" ToolTip="{l:Loc Editor.Export.OutputSize}" />
|
||||
<TextBlock Grid.Row="4" Grid.Column="1" Margin="0,0,0,8" MinHeight="24" Style="{StaticResource Text.Number}" Text="{Binding OutputSizeText}"
|
||||
ToolTip="{Binding OutputSizeToolTip}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FrameRate}" ToolTip="{l:Loc Editor.Export.FrameRate}" />
|
||||
<Grid Grid.Row="4" Grid.Column="1" Margin="0,0,0,8">
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FrameRate}" ToolTip="{l:Loc Editor.Export.FrameRate}" />
|
||||
<Grid Grid.Row="5" Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@@ -479,23 +508,30 @@
|
||||
Visibility="{Binding IsFrameRateAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Quality}" ToolTip="{l:Loc Editor.Export.Quality}" />
|
||||
<Grid Grid.Row="5" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="64" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="1" Maximum="{Binding QualityMaximum}" SmallChange="1" LargeChange="5" IsSnapToTickEnabled="True" TickFrequency="1" Value="{Binding Quality}"
|
||||
IsEnabled="{Binding IsQualityApplicable}" ToolTip="{Binding QualityToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.Quality}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding QualityText}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}" ToolTip="{Binding QualityNotApplicable}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Colour}" ToolTip="{l:Loc Editor.Export.Colour}" />
|
||||
<ComboBox Grid.Row="6" Grid.Column="1" ItemsSource="{Binding Depths}" SelectedItem="{Binding SelectedDepth}" DisplayMemberPath="Label"
|
||||
IsEnabled="{Binding CanChooseDepth}" ToolTip="{l:Loc Tooltips.Editor.Export.Colour}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Export.Colour}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Encoder}" ToolTip="{l:Loc Editor.Export.Encoder}" />
|
||||
<Grid Grid.Row="6" Grid.Column="1" Margin="0,0,0,8">
|
||||
<!-- ===== Encoding (owner review 1, R8: rate control, keyframes, B-frames, profile over the existing overrides) ===== -->
|
||||
<ContentControl Content="{Binding EncodingGroup}" Focusable="False" />
|
||||
<Grid Margin="0,4,0,8" IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding EncodingGroup.IsExpanded, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Encoder}" ToolTip="{l:Loc Editor.Export.Encoder}" />
|
||||
<Grid Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@@ -516,18 +552,164 @@
|
||||
</TextBlock>
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Colour}" ToolTip="{l:Loc Editor.Export.Colour}" />
|
||||
<ComboBox Grid.Row="7" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Depths}" SelectedItem="{Binding SelectedDepth}" DisplayMemberPath="Label"
|
||||
IsEnabled="{Binding CanChooseDepth}" ToolTip="{l:Loc Tooltips.Editor.Export.Colour}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Export.Colour}" />
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Export.RateControl}" ToolTip="{l:Loc Export.RateControl}" />
|
||||
<Grid Grid.Row="1" Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox ItemsSource="{Binding RateControls}" SelectedItem="{Binding SelectedRateControl}" DisplayMemberPath="Label" IsEnabled="{Binding HasRateControl}"
|
||||
ToolTip="{Binding RateControlToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Export.RateControl}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}"
|
||||
Command="{Binding ResetRateControlCommand}" ToolTip="{l:Loc Tooltips.Export.ResetValue}" AutomationProperties.Name="{l:Loc Editor.ResetToAuto}"
|
||||
Visibility="{Binding IsRateControlSet, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="8" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FileName}" ToolTip="{l:Loc Editor.Export.FileName}" />
|
||||
<TextBox Grid.Row="8" Grid.Column="1" Margin="0,0,0,8" Text="{Binding NameTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
<!-- Bit rate (variable, constant) or quality 1–100 (quality rate control, JPEG, MJPEG, GIF); the label says which. -->
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{Binding QualityHeader}" ToolTip="{Binding QualityHeader}" />
|
||||
<Grid Grid.Row="2" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="64" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="1" Maximum="{Binding QualityMaximum}" SmallChange="1" LargeChange="5" IsSnapToTickEnabled="True" TickFrequency="1" Value="{Binding Quality}"
|
||||
IsEnabled="{Binding IsQualityApplicable}" ToolTip="{Binding QualityToolTip}" AutomationProperties.Name="{Binding QualityHeader}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding QualityText}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}" ToolTip="{Binding QualityNotApplicable}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="4,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}"
|
||||
Command="{Binding ResetQualityCommand}" ToolTip="{l:Loc Tooltips.Export.ResetValue}" AutomationProperties.Name="{l:Loc Editor.ResetToAuto}"
|
||||
Visibility="{Binding IsQualitySet, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Export.Keyframes}" ToolTip="{l:Loc Export.Keyframes}" />
|
||||
<ComboBox Grid.Row="3" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding KeyframeChoices}" SelectedItem="{Binding SelectedKeyframes}" DisplayMemberPath="Label"
|
||||
IsEnabled="{Binding HasRateControl}" ToolTip="{Binding KeyframesToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Export.Keyframes}" />
|
||||
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Export.BFrames}" ToolTip="{l:Loc Export.BFrames}" />
|
||||
<ComboBox Grid.Row="4" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding BFrameChoices}" SelectedItem="{Binding SelectedBFrames}" DisplayMemberPath="Label"
|
||||
IsEnabled="{Binding CanChooseBFrames}" ToolTip="{Binding BFramesToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Export.BFrames}" />
|
||||
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Export.Profile}" ToolTip="{l:Loc Export.Profile}" />
|
||||
<Grid Grid.Row="5" Grid.Column="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox ItemsSource="{Binding ProfileChoices}" SelectedItem="{Binding SelectedProfile}" DisplayMemberPath="Label" IsEnabled="{Binding CanChooseProfile}"
|
||||
ToolTip="{Binding ProfileToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Export.Profile}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}"
|
||||
Command="{Binding ResetProfileCommand}" ToolTip="{l:Loc Tooltips.Export.ResetValue}" AutomationProperties.Name="{l:Loc Editor.ResetToAuto}"
|
||||
Visibility="{Binding IsProfileSet, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- ===== Playback (owner review 1, R8; settings format 3 while it is not forward, once, without fades or hold) ===== -->
|
||||
<ContentControl Content="{Binding PlaybackGroup}" Focusable="False" />
|
||||
<Grid Margin="0,4,0,8" IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding PlaybackGroup.IsExpanded, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Export.Direction}" ToolTip="{l:Loc Export.Direction}" />
|
||||
<Grid Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox ItemsSource="{Binding Directions}" SelectedItem="{Binding SelectedDirection}" DisplayMemberPath="Label" ItemContainerStyle="{StaticResource ComboBoxItem.Gated}"
|
||||
ToolTip="{l:Loc Tooltips.Export.Direction}" AutomationProperties.Name="{l:Loc Export.Direction}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}"
|
||||
Command="{Binding ResetPlaybackCommand}" ToolTip="{l:Loc Tooltips.Export.PlaybackReset}" AutomationProperties.Name="{l:Loc Editor.ResetToAuto}"
|
||||
Visibility="{Binding IsPlaybackDefault, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Export.Loops}" ToolTip="{l:Loc Export.Loops}" />
|
||||
<Grid Grid.Row="1" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="52" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="1" Maximum="10" SmallChange="1" LargeChange="1" IsSnapToTickEnabled="True" TickFrequency="1" Value="{Binding Loops}"
|
||||
ToolTip="{l:Loc Tooltips.Export.Loops}" AutomationProperties.Name="{l:Loc Export.Loops}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding LoopsText}" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
|
||||
<!-- Fades and hold: a 0–10 s slider in steps of 0.5, and the exact seconds typed (fades up to 30 s, hold up to 60 s). -->
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Export.FadeIn}" ToolTip="{l:Loc Export.FadeIn}" />
|
||||
<Grid Grid.Row="2" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="52" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="0" Maximum="10" SmallChange="0.5" LargeChange="1" IsSnapToTickEnabled="True" TickFrequency="0.5" Value="{Binding FadeIn}"
|
||||
ToolTip="{l:Loc Tooltips.Export.FadeIn}" AutomationProperties.Name="{l:Loc Export.FadeIn}" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" Width="NaN" Margin="8,0,0,0"
|
||||
Text="{Binding FadeInField.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding FadeInField}"
|
||||
ToolTip="{Binding FadeInField.ToolTip}" AutomationProperties.Name="{l:Loc Export.FadeIn}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Export.FadeOut}" ToolTip="{l:Loc Export.FadeOut}" />
|
||||
<Grid Grid.Row="3" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="52" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="0" Maximum="10" SmallChange="0.5" LargeChange="1" IsSnapToTickEnabled="True" TickFrequency="0.5" Value="{Binding FadeOut}"
|
||||
ToolTip="{l:Loc Tooltips.Export.FadeOut}" AutomationProperties.Name="{l:Loc Export.FadeOut}" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" Width="NaN" Margin="8,0,0,0"
|
||||
Text="{Binding FadeOutField.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding FadeOutField}"
|
||||
ToolTip="{Binding FadeOutField.ToolTip}" AutomationProperties.Name="{l:Loc Export.FadeOut}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Export.HoldEnd}" ToolTip="{l:Loc Export.HoldEnd}" />
|
||||
<Grid Grid.Row="4" Grid.Column="1" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="52" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="0" Maximum="10" SmallChange="0.5" LargeChange="1" IsSnapToTickEnabled="True" TickFrequency="0.5" Value="{Binding HoldEnd}"
|
||||
ToolTip="{l:Loc Tooltips.Export.HoldEnd}" AutomationProperties.Name="{l:Loc Export.HoldEnd}" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" Width="NaN" Margin="8,0,0,0"
|
||||
Text="{Binding HoldEndField.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding HoldEndField}"
|
||||
ToolTip="{Binding HoldEndField.ToolTip}" AutomationProperties.Name="{l:Loc Export.HoldEnd}" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- ===== File ===== -->
|
||||
<ContentControl Content="{Binding FileGroup}" Focusable="False" />
|
||||
<Grid Margin="0,4,0,8" IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding FileGroup.IsExpanded, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FileName}" ToolTip="{l:Loc Editor.Export.FileName}" />
|
||||
<TextBox Grid.Column="1" Margin="0,0,0,8" Text="{Binding NameTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding NameTemplate}" ToolTip="{Binding NameTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.FileName}" />
|
||||
|
||||
<TextBlock Grid.Row="9" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.SaveTo}" ToolTip="{l:Loc Editor.Export.SaveTo}" />
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.SaveTo}" ToolTip="{l:Loc Editor.Export.SaveTo}" />
|
||||
<!-- The folder ends in an ellipsis (its full path is in the tooltip). -->
|
||||
<ComboBox Grid.Row="9" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
|
||||
<ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
|
||||
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:SaveChoice}">
|
||||
@@ -537,30 +719,18 @@
|
||||
</ComboBox>
|
||||
<!-- Export.html "Sync" (12 px): also send the render to the server the sequence is linked to. Under the folder rather than beside
|
||||
it, as in the mockup, so that neither is cut in the 194 px field column in longer languages. -->
|
||||
<CheckBox Grid.Row="10" Grid.Column="1" Margin="0,6,0,0" HorizontalAlignment="Left" FontSize="{StaticResource Size.Secondary}"
|
||||
<CheckBox Grid.Row="2" Grid.Column="1" Margin="0,6,0,0" HorizontalAlignment="Left" FontSize="{StaticResource Size.Secondary}"
|
||||
Content="{l:Loc Editor.Export.Sync}" IsChecked="{Binding SyncToServer}" IsEnabled="{Binding CanSync}" ToolTip="{Binding SyncToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
|
||||
<v:SplitButton Grid.Row="3" Grid.ColumnSpan="2" Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
|
||||
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True"
|
||||
DropDownToolTip="{l:Loc Tooltips.Editor.Export.RestoreChoice}" AutomationProperties.Name="{l:Loc Editor.Export.RestoreName}"
|
||||
Visibility="{Binding HasSavedCopies, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
|
||||
<Border Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10">
|
||||
<StackPanel>
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding EstimatedSize}" Style="{StaticResource Text.Number}" FontSize="{StaticResource Size.Secondary}" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Size}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
<DockPanel Margin="0,4,0,0">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding EstimatedTime}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" MaxWidth="180" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Time}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
<DockPanel Margin="0,4,0,0">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding ResultName}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" MaxWidth="180"
|
||||
ToolTip="{Binding ResultName}" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Result}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ItemsControl ItemsSource="{Binding Notices}" Margin="0,8,0,0" Focusable="False">
|
||||
<ItemsControl ItemsSource="{Binding Notices}" Margin="0,4,0,0" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid Margin="0,4,0,0">
|
||||
|
||||
@@ -2,6 +2,7 @@ using Chronos.Core.Advice;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Core.Video;
|
||||
@@ -263,6 +264,34 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
_ => [RenderRequest(export)],
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A source can save one frame as an image (owner review 1, R8, "Save frame"): a sequence of this PC or of a server, or a
|
||||
/// source that makes its own still jobs (<see cref="IProjectStills"/>, a workspace project). A source that renders
|
||||
/// elsewhere (<see cref="IProjectRenders"/>) without still jobs of its own saves none.
|
||||
/// </summary>
|
||||
public bool CanSaveFrames => Source is IProjectStills or not IProjectRenders;
|
||||
|
||||
/// <summary>
|
||||
/// The job that saves frame <paramref name="frameIndex"/> as one <paramref name="codec"/> image (one of
|
||||
/// <see cref="RenderRules.StillCodecs"/>) at the output size of <paramref name="export"/>, with every correction of the
|
||||
/// project as it is now and no playback (<see cref="ProcessingJobs.Still"/>): routed as <see cref="RenderRequests"/> is,
|
||||
/// on this PC's engine or on the server, as one job. The frame is named by its position and by its photo, whose hash
|
||||
/// wins when frames moved meanwhile. Null when the source saves no frames (<see cref="CanSaveFrames"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="frameIndex"/> is not a frame of the sequence, or <paramref name="codec"/> is no still format.</exception>
|
||||
public IReadOnlyList<ArchiveJobRequest>? StillRequests(ExportSettings export, VideoCodec codec, int frameIndex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)frameIndex, (uint)Content.Count, nameof(frameIndex));
|
||||
var photo = Content.Frames[frameIndex].Sha256;
|
||||
return Source switch
|
||||
{
|
||||
IProjectStills stills => stills.StillRequests(Content.Sequence, Project, export, codec, frameIndex, photo, Content.SourceWidth, Content.SourceHeight),
|
||||
IProjectRenders => null,
|
||||
_ => [ProcessingJobs.Still(Content.Sequence, export, codec, frameIndex, photo, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
|
||||
/// </summary>
|
||||
@@ -608,6 +637,17 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A source whose saved frames are made otherwise than from the project as the editor holds it (as <see cref="IProjectRenders"/>
|
||||
/// for renders): a workspace project would name the frame and its settings as its home reads them.
|
||||
/// </summary>
|
||||
public interface IProjectStills
|
||||
{
|
||||
/// <summary>The jobs that save frame <paramref name="frameIndex"/> (photo <paramref name="photoSha256"/>) of <paramref name="project"/> with <paramref name="export"/>.</summary>
|
||||
IReadOnlyList<ArchiveJobRequest> StillRequests(Sequence sequence, ProjectSettings project, ExportSettings export, VideoCodec codec, int frameIndex, string? photoSha256,
|
||||
int sourceWidth, int sourceHeight);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A "Save both" copy made the project (<see cref="EditorSession.RestoreAsync"/>). Its Undo brings back the project from
|
||||
/// before as a new step, and only while the restore is still the last change: after another edit, an undo or a merged
|
||||
|
||||
@@ -53,6 +53,53 @@ public sealed class AutoSetting<T>(
|
||||
public ProjectSettings Reset(ProjectSettings project) => set(project, get(project).Reset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which collapsible groups of the editor are open, by group key ("export.encoding", "preset.social"): a group nobody
|
||||
/// toggled opens as its default says. Until <see cref="Bind"/> attaches the app's settings the state lives for the run;
|
||||
/// bound, each toggle is written there and saved.
|
||||
/// </summary>
|
||||
public sealed class GroupStates
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private IDictionary<string, bool> _store = new Dictionary<string, bool>(StringComparer.Ordinal);
|
||||
private Action? _save;
|
||||
|
||||
/// <summary>Keeps the state in <paramref name="store"/> (the app's settings), calling <paramref name="save"/> after each toggle.</summary>
|
||||
public void Bind(IDictionary<string, bool> store, Action? save)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
lock (_lock)
|
||||
{
|
||||
// What was toggled before the settings were attached stays.
|
||||
foreach (var (key, open) in _store)
|
||||
{
|
||||
if (!store.ContainsKey(key)) store[key] = open;
|
||||
}
|
||||
(_store, _save) = (store, save);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether the group <paramref name="key"/> is open; <paramref name="fallback"/> when it was never toggled.</summary>
|
||||
public bool IsExpanded(string key, bool fallback)
|
||||
{
|
||||
lock (_lock) return _store.TryGetValue(key, out var open) ? open : fallback;
|
||||
}
|
||||
|
||||
/// <summary>Remembers that the group <paramref name="key"/> is open or closed.</summary>
|
||||
public void Set(string key, bool expanded)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
Action? save;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_store.TryGetValue(key, out var open) && open == expanded) return;
|
||||
_store[key] = expanded;
|
||||
save = _save;
|
||||
}
|
||||
save?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Auto settings of the editor's sections, in panel order.</summary>
|
||||
public static class EditorSettings
|
||||
{
|
||||
@@ -129,6 +176,12 @@ public static class EditorSettings
|
||||
public static bool IsSectionAuto(ProjectSettings project, AdvisorSection section) =>
|
||||
All.Where(s => s.Section == section).All(s => s.IsAuto(project));
|
||||
|
||||
/// <summary>
|
||||
/// The collapse state of the Export step's setting groups and preset groups (owner review 1, R3; DESIGN §4 collapsible
|
||||
/// group): this user's, kept by the app and not in the project.
|
||||
/// </summary>
|
||||
public static GroupStates Groups { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="setting"/> applies under the switches in force: the deflicker window, strength and regions
|
||||
/// with deflicker on, the transition length with holy grail on, the shutter angle with motion blur on, the flow quality
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
DynamicResource; sizes and the kit's styles StaticResource.
|
||||
-->
|
||||
|
||||
<!-- Preview height against the measuring area: the editor favours the picture; the Analysis findings and the Export preset cards take more room. -->
|
||||
<!-- Preview height against the measuring area: the editor favours the picture; the Analysis findings and the Export preset table take more room. -->
|
||||
<GridLength x:Key="Editor.Grid.Preview">17*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.Measure">10*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.ExportPreview">9*</GridLength>
|
||||
@@ -124,34 +124,35 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Preset card (Export.html): card fill, stroke, radius 8; accent border and glow when selected. -->
|
||||
<Style x:Key="Button.PresetCard" TargetType="Button">
|
||||
<!--
|
||||
A row of the Export step's preset table (owner review 1, R3): 28 px, transparent; card fill on hover, the accent wash and
|
||||
a 3 px accent bar at the start edge when it is the preset in use.
|
||||
-->
|
||||
<Style x:Key="Button.PresetRow" TargetType="Button">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Height" Value="118" />
|
||||
<Setter Property="Margin" Value="5,0,5,10" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="Height" Value="28" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Grid>
|
||||
<Border x:Name="Glow" Margin="-3" CornerRadius="11" BorderThickness="3" BorderBrush="{DynamicResource Brush.AccentSelected}" Visibility="Collapsed" />
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Card}" Padding="12,10" SnapsToDevicePixels="True">
|
||||
<ContentPresenter />
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True">
|
||||
<ContentPresenter Margin="6,0" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="False" />
|
||||
</Border>
|
||||
<Border x:Name="Bar" Width="3" HorizontalAlignment="Left" Margin="0,5" CornerRadius="1.5" Background="{DynamicResource Brush.Accent}" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.StrokeStrong}" />
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
<DataTrigger Binding="{Binding IsSelected}" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.AccentSubtle}" />
|
||||
<Setter TargetName="Bar" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
@@ -162,7 +163,53 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- "Recommended" chip on a card: accent border and text (DESIGN §4 chips). -->
|
||||
<!-- Columns of the preset table: the batch tick, then size, codec, fps and the two estimates after the name. -->
|
||||
<GridLength x:Key="Export.Column.Tick">28</GridLength>
|
||||
<GridLength x:Key="Export.Column.Size">92</GridLength>
|
||||
<GridLength x:Key="Export.Column.Codec">104</GridLength>
|
||||
<GridLength x:Key="Export.Column.Fps">44</GridLength>
|
||||
<GridLength x:Key="Export.Column.EstimatedSize">76</GridLength>
|
||||
<GridLength x:Key="Export.Column.EstimatedTime">96</GridLength>
|
||||
|
||||
<!--
|
||||
Collapsible group header (DESIGN §4, owner review 1 R3): a chevron (down when open, toward the reading direction when
|
||||
closed), then the content: the group's name in Text.Body 600 and, while collapsed, a muted one-line summary.
|
||||
-->
|
||||
<Style x:Key="ToggleButton.Group" TargetType="ToggleButton">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="MinHeight" Value="28" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" CornerRadius="{StaticResource Radius.Control}" Padding="2,0,6,0" SnapsToDevicePixels="True">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:Icon x:Name="Chevron" Glyph="{StaticResource Icon.ChevronRight}" Size="14" Margin="0,0,6,0" VerticalAlignment="Center"
|
||||
Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" RecognizesAccessKey="False" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="Chevron" Property="Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- "Recommended" chip on a preset row: accent border and text (DESIGN §4 chips). -->
|
||||
<Style x:Key="Border.Recommended" TargetType="Border">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
|
||||
@@ -49,6 +49,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
private readonly SequenceJobs _jobs;
|
||||
private readonly AsyncRelayCommand _analyse;
|
||||
private readonly AsyncRelayCommand _render;
|
||||
private readonly AsyncRelayCommand _renderBatch;
|
||||
private readonly AsyncRelayCommand _addToQueue;
|
||||
private readonly AsyncRelayCommand _saveFrame;
|
||||
private readonly AsyncRelayCommand _cancelServerJob;
|
||||
private PreviewRenderer _renderer;
|
||||
private int _currentIndex;
|
||||
@@ -117,10 +120,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
_player = new DispatcherTimer(DispatcherPriority.Background, _dispatcher);
|
||||
_player.Tick += (_, _) => Advance();
|
||||
|
||||
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
|
||||
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsLocked && !IsAnalysing);
|
||||
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsLocked);
|
||||
_render = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender);
|
||||
_renderBatch = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: true), () => CanRender && RenderMenu.BatchPresets(RenderExport).Count > 0);
|
||||
_addToQueue = new AsyncRelayCommand(() => RenderAsync(JobPriority.Normal, batch: false), () => CanRender);
|
||||
_saveFrame = new AsyncRelayCommand((p, _) => SaveFrameAsync(p), p => p is VideoCodec codec && RenderRules.StillCodecs.Contains(codec) && SaveFrameBlockedReason is null);
|
||||
SelectPresetCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is string id) SelectedRenderChoice = RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, id, StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
ShowVideosCommand = new RelayCommand(ShowVideos);
|
||||
_cancelServerJob = new AsyncRelayCommand(CancelServerJobAsync, () => ServerJob is not null);
|
||||
UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsLocked && Session.History.CanUndo);
|
||||
RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsLocked && Session.History.CanRedo);
|
||||
@@ -141,7 +153,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
Analysis = new AnalysisTab(this);
|
||||
Frames = new FramesTab(this);
|
||||
Exposure = new ExposureTab(this);
|
||||
Tabs = [Analysis, Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
|
||||
Export = new ExportTab(this);
|
||||
Tabs = [Analysis, Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), Export];
|
||||
for (var i = 0; i < Tabs.Count; i++)
|
||||
{
|
||||
Tabs[i].Number = i + 1;
|
||||
@@ -154,7 +167,6 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
_currentFrameId = FrameId(_currentIndex);
|
||||
// Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders.
|
||||
_syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut;
|
||||
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
|
||||
_shownOrientation = OrientationOf(session.Project.Camera);
|
||||
UpdateCropBox();
|
||||
|
||||
@@ -272,6 +284,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
|
||||
public ExposureTab Exposure { get; }
|
||||
|
||||
/// <summary>The last step; the project ▾ menu's "Save project file" is its command (owner review 1, R3).</summary>
|
||||
public ExportTab Export { get; }
|
||||
|
||||
/// <summary>The steps of the Edit path, in order (owner review 1, R7).</summary>
|
||||
public IReadOnlyList<EditorTab> Tabs { get; }
|
||||
|
||||
@@ -624,29 +639,105 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
? Session.ExportFor(id) with { Batch = Session.Project.Export.Batch }
|
||||
: Session.Project.Export;
|
||||
|
||||
/// <summary>"Render · 4K archive".</summary>
|
||||
public string RenderText => Loc.L("Editor.Render", Plan?.PresetName ?? string.Empty);
|
||||
/// <summary>"Render" whatever the preset (owner review 1, R3, decision 1): the header keeps its width; the tooltip and the menu's check say which.</summary>
|
||||
public string RenderText => Loc.L("Editor.RenderButton");
|
||||
|
||||
public string RenderToolTip => RenderBlockedReason ?? (IsRemote ? Loc.L("Tooltips.Editor.RenderServer", ServerName) : Loc.L("Tooltips.Editor.Render"));
|
||||
/// <summary>Why Render waits, then what it renders: preset, size, codec, frame rate, estimated size and time (<see cref="RenderMenu.RenderToolTip"/>).</summary>
|
||||
public string RenderToolTip => RenderMenu.RenderToolTip(Plan, RenderBlockedReason, IsRemote ? ServerName : null);
|
||||
|
||||
/// <summary>The ▾ part of Render: another preset for the project, or only for this render when the project cannot change.</summary>
|
||||
public string RenderChoiceToolTip => Loc.L(IsReadOnly ? "Tooltips.Editor.RenderChoiceReadOnly" : "Tooltips.Editor.RenderChoice");
|
||||
|
||||
/// <summary>
|
||||
/// The Render ▾ menu (<see cref="RenderMenu"/>): made again whenever it is read, so the menu, which reads it each time it
|
||||
/// opens, shows the presets, the batch, the history and the reasons as they are then.
|
||||
/// </summary>
|
||||
public IReadOnlyList<RenderMenuItem> RenderMenuItems
|
||||
{
|
||||
get
|
||||
{
|
||||
var export = RenderExport;
|
||||
var batch = RenderMenu.BatchPresets(export);
|
||||
var (camera, width, height) = (Session.Project.Camera, Session.Content.SourceWidth, Session.Content.SourceHeight);
|
||||
return RenderMenu.Build(new RenderMenuState
|
||||
{
|
||||
CurrentPresetId = RenderPresetId(basis: false),
|
||||
BasePresetId = RenderPresetId(basis: true),
|
||||
RecommendedPresetId = Session.Advice.Find(AdvisorParameters.ExportPreset)?.Value as string,
|
||||
Batch = batch,
|
||||
Recent = RenderMenu.RecentPresets(Session.Content.Renders),
|
||||
Details = preset => RenderMenu.PresetDetails(export, preset.Id, camera, width, height),
|
||||
SelectPreset = SelectPresetCommand,
|
||||
RenderBatch = _renderBatch,
|
||||
RenderBatchToolTip = RenderBlockedReason,
|
||||
AddToQueue = _addToQueue,
|
||||
AddToQueueToolTip = RenderBlockedReason,
|
||||
SaveFrame = _saveFrame,
|
||||
SaveFrameBlocked = SaveFrameBlockedReason,
|
||||
ShowVideos = ShowVideosCommand,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chooses the preset Render renders (<see cref="SelectedRenderChoice"/>); its parameter is the preset id.</summary>
|
||||
public ICommand SelectPresetCommand { get; }
|
||||
|
||||
/// <summary>Render batch (n): the export and each preset of its batch.</summary>
|
||||
public ICommand RenderBatchCommand => _renderBatch;
|
||||
|
||||
/// <summary>Add to queue: the render at a normal priority, the editing goes on.</summary>
|
||||
public ICommand AddToQueueCommand => _addToQueue;
|
||||
|
||||
/// <summary>Save frame › PNG, JPEG or TIFF 16-bit (decision 12); its parameter is the <see cref="VideoCodec"/>.</summary>
|
||||
public ICommand SaveFrameCommand => _saveFrame;
|
||||
|
||||
/// <summary>The videos of this sequence (decision 20); disabled until this Chronos has a Videos section.</summary>
|
||||
public ICommand ShowVideosCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Why the frame under the cursor cannot be saved now (<see cref="RenderMenu.SaveFrameBlockedReason"/>): out of date or
|
||||
/// read-only, no frame the render keeps under the cursor, a source that saves no frames, no right to render on the server or a
|
||||
/// server too old for still jobs (format 3), a wrong file name; null when it can.
|
||||
/// </summary>
|
||||
public string? SaveFrameBlockedReason
|
||||
{
|
||||
get
|
||||
{
|
||||
var hasFrame = FrameCount > 0 && !Session.Project.ExcludedFrames.Contains(CurrentIndex) && !Session.Content.NotRenderable().Contains(CurrentIndex);
|
||||
string? server = null;
|
||||
// A workspace project saving the frame on this PC from its originals (phase 5c) uses this PC's engine: the
|
||||
// server's format does not decide, as for its renders.
|
||||
if (IsRemote && Session.CanSaveFrames && Session.Source is not IProjectRenders { RendersLocally: true })
|
||||
{
|
||||
var sync = Shell.Services.Sync;
|
||||
server = !sync.CanRender ? Loc.L("Tooltips.Editor.Render.NoRight", ServerName)
|
||||
: ServerJobs.StillNeedsNewerServer(sync.SettingsFormat)
|
||||
?? ServerJobs.RenderNeedsNewerServer(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight, sync.SettingsFormat);
|
||||
}
|
||||
return RenderMenu.SaveFrameBlockedReason(IsOutdated, ServerName, IsReadOnly, hasFrame, Session.CanSaveFrames, server, Plan?.NameError);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanRender => RenderBlockedReason is null;
|
||||
|
||||
/// <summary>The settings format a render of <see cref="RenderExport"/> needs (<see cref="Chronos.Data.Processing.ProcessingJobs.RequiredFormat"/>).</summary>
|
||||
private int RenderFormat =>
|
||||
Chronos.Data.Processing.ProcessingJobs.RequiredFormat(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight);
|
||||
/// <summary>
|
||||
/// The preset Render renders (<paramref name="basis"/>: the one its values start from, a custom export's included), as
|
||||
/// chosen for this render in a read-only session, else as planned, else as the project names it.
|
||||
/// </summary>
|
||||
private string? RenderPresetId(bool basis) =>
|
||||
(IsReadOnly ? _renderPreset : null) ?? (basis ? Plan?.Export.BasePresetId : Plan?.Export.PresetId) ?? EditorSettings.ExportPreset.Effective(Session.Project, null);
|
||||
|
||||
/// <summary>Why the project's export cannot be rendered now, localised; null when it can.</summary>
|
||||
public string? RenderBlockedReason => Plan switch
|
||||
{
|
||||
_ when IsRemote && !Shell.Services.Sync.CanRender => Loc.L("Tooltips.Editor.Render.NoRight", ServerName),
|
||||
// Settings or proportions the server would render otherwise (owner review 1, phase 4: an older server, Send and render too).
|
||||
// A workspace project rendered on this PC from its originals (phase 5c) renders with this PC's engine: the server's
|
||||
// format does not decide (sending its version home is held by the workspace's own gate).
|
||||
// Settings or proportions the server would render otherwise (owner review 1, phase 4: an older server, Send and render too;
|
||||
// phase 5: playback needs format 3, read from the export rendered). A workspace project rendered on this PC from its
|
||||
// originals (phase 5c) renders with this PC's engine: the server's format does not decide (sending its version home is
|
||||
// held by the workspace's own gate).
|
||||
_ when IsRemote && Session.Source is not IProjectRenders { RendersLocally: true }
|
||||
&& ServerJobs.NeedsNewerServer(RenderFormat, Shell.Services.Sync.SettingsFormat) is { } newer => newer,
|
||||
&& ServerJobs.RenderNeedsNewerServer(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight,
|
||||
Shell.Services.Sync.SettingsFormat) is { } newer => newer,
|
||||
_ when IsOutdated => Loc.L("Tooltips.Editor.Outdated", ServerName),
|
||||
null when _planned => Loc.L("Tooltips.Editor.Render.NoSource"),
|
||||
null => Loc.L("Tooltips.Editor.Render.Planning"),
|
||||
@@ -732,11 +823,36 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Save frame ›" (owner review 1, R8, decision 12): queues the frame under the cursor as one <paramref name="parameter"/>
|
||||
/// image (a <see cref="VideoCodec"/> of <see cref="RenderRules.StillCodecs"/>) at the export's output size, with every
|
||||
/// correction and no playback; on this PC's engine, or as one server job for a server sequence. The frame is the one on
|
||||
/// screen wherever frames read again before the job put it.
|
||||
/// </summary>
|
||||
public async Task SaveFrameAsync(object? parameter)
|
||||
{
|
||||
if (parameter is not VideoCodec codec || !RenderRules.StillCodecs.Contains(codec) || SaveFrameBlockedReason is not null) return;
|
||||
var frame = _currentFrameId;
|
||||
await Session.EnsureFramesAsync();
|
||||
if (IsOutdated || IndexOfFrame(frame) is not { } index) return;
|
||||
if (Session.StillRequests(RenderExport with { Batch = [] }, codec, index) is not [_, ..] requests) return;
|
||||
foreach (var request in requests) await Session.SubmitAsync(request);
|
||||
var label = requests[0].Label + Loc.Separator + EditorText.Position(index, FrameCount);
|
||||
if (IsRemote && Session.Source is not IProjectRenders { RendersLocally: true }) Shell.Notify(Loc.L("Editor.Still.Queued"), label);
|
||||
else Shell.Notify(Loc.L("Editor.Still.Queued"), label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
/// <summary>The videos of this sequence (Render ▾ › Videos): the Videos section filtered on it.</summary>
|
||||
private void ShowVideos() => Shell.OpenVideos(Session.Content.Sequence.Id, Title);
|
||||
|
||||
/// <summary>Re-reads the enabled state of every command (the async ones keep their own event).</summary>
|
||||
public void RefreshCommands()
|
||||
{
|
||||
_analyse.RaiseCanExecuteChanged();
|
||||
_render.RaiseCanExecuteChanged();
|
||||
_renderBatch.RaiseCanExecuteChanged();
|
||||
_addToQueue.RaiseCanExecuteChanged();
|
||||
_saveFrame.RaiseCanExecuteChanged();
|
||||
_cancelServerJob.RaiseCanExecuteChanged();
|
||||
foreach (var tab in Tabs) tab.RefreshCommands();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
@@ -1523,6 +1639,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
OnPropertyChanged(nameof(RenderToolTip));
|
||||
OnPropertyChanged(nameof(RenderBlockedReason));
|
||||
OnPropertyChanged(nameof(CanRender));
|
||||
OnPropertyChanged(nameof(SaveFrameBlockedReason));
|
||||
OnPropertyChanged(nameof(RenderMenuItems));
|
||||
}
|
||||
|
||||
/// <summary>A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread).</summary>
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A collapsible group of the Export step's Output panel (owner review 1, R3; DESIGN §4): its name with a chevron and,
|
||||
/// while collapsed, a muted one-line summary of its values. Open or closed is this user's choice, kept by the app
|
||||
/// (<see cref="EditorSettings.Groups"/>), not in the project.
|
||||
/// </summary>
|
||||
public sealed class SettingGroup : ObservableObject
|
||||
{
|
||||
private readonly string _nameKey;
|
||||
private readonly string _toolTipKey;
|
||||
private readonly bool _expandedByDefault;
|
||||
private string? _summary;
|
||||
|
||||
/// <param name="key">The group's key in <see cref="EditorSettings.Groups"/> ("export.encoding").</param>
|
||||
public SettingGroup(string key, string nameKey, string toolTipKey, bool expandedByDefault)
|
||||
{
|
||||
Key = key;
|
||||
(_nameKey, _toolTipKey, _expandedByDefault) = (nameKey, toolTipKey, expandedByDefault);
|
||||
ToggleCommand = new RelayCommand(() => IsExpanded = !IsExpanded);
|
||||
}
|
||||
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>"Encoding".</summary>
|
||||
public string Header => Loc.L(_nameKey);
|
||||
|
||||
/// <summary>What opening the group shows.</summary>
|
||||
public string ToolTip => Loc.L(_toolTipKey);
|
||||
|
||||
public bool IsExpanded
|
||||
{
|
||||
get => EditorSettings.Groups.IsExpanded(Key, _expandedByDefault);
|
||||
set
|
||||
{
|
||||
if (value == IsExpanded) return;
|
||||
EditorSettings.Groups.Set(Key, value);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Variable · 40 Mb/s · GOP 1 s · B 2 · High": the values, shown while the group is collapsed.</summary>
|
||||
public string? Summary { get => _summary; set => Set(ref _summary, value); }
|
||||
|
||||
public ICommand ToggleCommand { get; }
|
||||
|
||||
/// <summary>The UI language changed, or another editor toggled the group: everything is read again.</summary>
|
||||
public void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the Export step's advanced encoding rows offer for a codec and colour depth (owner review 1, R8; decision 6), and
|
||||
/// the keyframe interval in seconds as the project stores it in frames. Every value is an <see cref="ExportOverrides"/>
|
||||
/// member nodes of phase 4 already read, so none of them raises the settings format.
|
||||
/// </summary>
|
||||
public static class ExportRules
|
||||
{
|
||||
/// <summary>Keyframe intervals offered, in seconds (0.5 to 10, step 0.5).</summary>
|
||||
public static IReadOnlyList<double> KeyframeSeconds { get; } = [.. Enumerable.Range(1, 20).Select(i => i * 0.5)];
|
||||
|
||||
/// <summary>B-frame counts offered besides Auto.</summary>
|
||||
public static IReadOnlyList<int> BFrameCounts { get; } = [0, 1, 2, 3, 4];
|
||||
|
||||
/// <summary>
|
||||
/// The standard resolutions of the Resolution choice (decision 7): the landscape box written into
|
||||
/// <see cref="ExportOverrides.Width"/>/<see cref="ExportOverrides.Height"/>, which the chosen proportions are fitted in.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<(string Key, string LabelKey, int Width, int Height)> StandardResolutions { get; } =
|
||||
[.. ExportPresets.Resolutions.Select(r => (r.Key, "Export.Resolution." + ResolutionLabel(r.Key), r.Width, r.Height))];
|
||||
|
||||
/// <summary>Only the hardware codecs have a rate control, a keyframe interval and B-frames to choose.</summary>
|
||||
public static bool HasRateControl(VideoCodec codec) => !VideoCodecInfo.IsManaged(codec);
|
||||
|
||||
/// <summary>Why <paramref name="codec"/> has no rate control to choose; null when it has.</summary>
|
||||
public static string? RateControlBlocked(VideoCodec codec) =>
|
||||
HasRateControl(codec) ? null : Loc.L("Tooltips.Export.RateControlNA", Loc.L("Export.Codec." + codec));
|
||||
|
||||
/// <summary>Why <paramref name="codec"/> has no keyframe interval to choose (as it has no rate control); null when it has.</summary>
|
||||
public static string? KeyframesBlocked(VideoCodec codec) =>
|
||||
HasRateControl(codec) ? null : Loc.L("Tooltips.Export.KeyframesNA", Loc.L("Export.Codec." + codec));
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="codec"/> with <paramref name="profile"/> takes no B-frames (Baseline, MJPEG, GIF, APNG and the
|
||||
/// image sequences); null when it does.
|
||||
/// </summary>
|
||||
public static string? BFramesBlocked(VideoCodec codec, CodecProfile profile) => codec switch
|
||||
{
|
||||
VideoCodec.H264 when profile == CodecProfile.H264Baseline => Loc.L("Tooltips.Export.BFramesNA", ProfileLabel(profile)),
|
||||
_ when VideoCodecInfo.IsManaged(codec) => Loc.L("Tooltips.Export.BFramesNA", Loc.L("Export.Codec." + codec)),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The profiles <paramref name="codec"/> offers at <paramref name="bitDepth"/>: H.264 Baseline, Main and High; HEVC Main
|
||||
/// at 8 bits or Main 10 above; AV1 Main; none for the managed codecs.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<CodecProfile> Profiles(VideoCodec codec, int bitDepth) => codec switch
|
||||
{
|
||||
VideoCodec.H264 => [CodecProfile.H264Baseline, CodecProfile.H264Main, CodecProfile.H264High],
|
||||
VideoCodec.Hevc => [bitDepth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain],
|
||||
VideoCodec.Av1 => [CodecProfile.Av1Main],
|
||||
_ => [],
|
||||
};
|
||||
|
||||
/// <summary>Why the profile cannot be chosen (the codec has one, or none); null when it can.</summary>
|
||||
public static string? ProfileBlocked(VideoCodec codec, int bitDepth) =>
|
||||
Profiles(codec, bitDepth).Count > 1 ? null : Loc.L("Tooltips.Export.ProfileNA", Loc.L("Export.Codec." + codec));
|
||||
|
||||
/// <summary>"Baseline", "Main", "High", "Main 10".</summary>
|
||||
public static string ProfileLabel(CodecProfile profile) => Loc.L(profile switch
|
||||
{
|
||||
CodecProfile.H264Baseline => "Export.Profile.Baseline",
|
||||
CodecProfile.H264High => "Export.Profile.High",
|
||||
CodecProfile.HevcMain10 => "Export.Profile.Main10",
|
||||
_ => "Export.Profile.Main",
|
||||
});
|
||||
|
||||
/// <summary>The interval of <paramref name="seconds"/> as stored: whole frames at <paramref name="frameRate"/>, at least one.</summary>
|
||||
public static int GopFrames(double seconds, Rational frameRate) => int.Max(1, (int)double.Round(seconds * frameRate.Value));
|
||||
|
||||
/// <summary>The interval of <paramref name="gopFrames"/> at <paramref name="frameRate"/>, in seconds.</summary>
|
||||
public static double GopSeconds(int gopFrames, Rational frameRate) => frameRate.Value > 0 ? gopFrames / frameRate.Value : 0;
|
||||
|
||||
/// <summary>The offered interval nearest <paramref name="gopFrames"/> at <paramref name="frameRate"/> (what the choice shows).</summary>
|
||||
public static double NearestKeyframeSeconds(int gopFrames, Rational frameRate) =>
|
||||
double.Clamp(double.Round(GopSeconds(gopFrames, frameRate) * 2) / 2, KeyframeSeconds[0], KeyframeSeconds[^1]);
|
||||
|
||||
/// <summary>
|
||||
/// A keyframe interval chosen by hand keeps its seconds when the frame rate changes: <paramref name="gopFrames"/> at
|
||||
/// <paramref name="from"/> as frames at <paramref name="to"/>.
|
||||
/// </summary>
|
||||
public static int RescaleGop(int gopFrames, Rational from, Rational to) => GopFrames(GopSeconds(gopFrames, from), to);
|
||||
|
||||
/// <summary>"1.5 s".</summary>
|
||||
public static string Seconds(double seconds) => Loc.L("Export.Seconds", seconds.ToString("0.##", Loc.Culture));
|
||||
|
||||
private static string ResolutionLabel(string key) => key switch
|
||||
{
|
||||
"4k" => "Uhd4k",
|
||||
"dci4k" => "Dci4k",
|
||||
_ => key,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The one-line summaries of the Export step (owner review 1, R3): a collapsed group's values and the footer's line.</summary>
|
||||
public static class ExportSummaries
|
||||
{
|
||||
private static string Separator => Loc.Separator;
|
||||
|
||||
/// <summary>
|
||||
/// "Variable · 40 Mb/s · GOP 1 s · B 2 · High" for a video codec; the quality ("Quality 95") or n/a for the managed
|
||||
/// codecs, which have no rate control.
|
||||
/// </summary>
|
||||
public static string Encoding(ResolvedExport export, long bitRate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
if (!ExportRules.HasRateControl(export.Codec))
|
||||
{
|
||||
var managed = EditorText.Encoding(export, 0, null);
|
||||
return managed.Length > 0 ? managed : Loc.L("Common.NotApplicable");
|
||||
}
|
||||
var parts = new List<string> { RateControlLabel(export.RateControl) };
|
||||
parts.Add(export.RateControl == RateControl.Quality ? Loc.L("Editor.Export.QualityValue", export.Quality) : EditorText.BitRate(bitRate));
|
||||
parts.Add(Loc.L("Export.Summary.Keyframes", ExportRules.Seconds(ExportRules.GopSeconds(export.GopFrames, export.FrameRate))));
|
||||
if (ExportRules.BFramesBlocked(export.Codec, export.Profile) is null) parts.Add(Loc.L("Export.Summary.BFrames", export.BFrames));
|
||||
if (export.Profile != CodecProfile.Auto) parts.Add(ExportRules.ProfileLabel(export.Profile));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"Forward · no fades", "Boomerang · ×2 · fades 1 s / 1.5 s · hold 2 s".</summary>
|
||||
public static string Playback(PlaybackSettings? playback)
|
||||
{
|
||||
playback ??= new PlaybackSettings();
|
||||
var parts = new List<string> { DirectionLabel(playback.EffectiveDirection) };
|
||||
if (playback.EffectiveLoops > 1) parts.Add(Loc.L("Export.Summary.Loops", playback.EffectiveLoops));
|
||||
parts.Add(playback.EffectiveFadeIn > 0 || playback.EffectiveFadeOut > 0
|
||||
? Loc.L("Export.Summary.Fades", ExportRules.Seconds(playback.EffectiveFadeIn), ExportRules.Seconds(playback.EffectiveFadeOut))
|
||||
: Loc.L("Export.Summary.NoFades"));
|
||||
if (playback.EffectiveHoldEnd > 0) parts.Add(Loc.L("Export.Summary.Hold", ExportRules.Seconds(playback.EffectiveHoldEnd)));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"2026-09-28 Harbour sunset - 4K archive.mp4 · Sync": the result's name, then Sync when it is on.</summary>
|
||||
public static string File(string? resultName, string folder, bool sync)
|
||||
{
|
||||
var parts = new List<string> { resultName is { Length: > 0 } name ? name : folder };
|
||||
if (sync) parts.Add(Loc.L("Editor.Export.Sync"));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The footer's line (decision 5): "2026-09-28 Harbour sunset - 4K….mp4 · 1.2 GB · about 4 min · 42 s · 1,260 frames"; the
|
||||
/// size and time are left out when there is no estimate (no encoder here).
|
||||
/// </summary>
|
||||
public static string Footer(string resultName, ExportEstimate? estimate, double durationSeconds, int frames)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(resultName);
|
||||
var duration = Formatting.Duration(TimeSpan.FromSeconds(double.Max(0, durationSeconds)));
|
||||
var count = Loc.Plural("Export.Footer.Frames", frames);
|
||||
return estimate is null
|
||||
? string.Join(Separator, resultName, duration, count)
|
||||
: Loc.L("Export.Footer.Summary", resultName, Formatting.Bytes(estimate.Bytes), Loc.L("Editor.Export.About", Formatting.Duration(estimate.Time)), duration, count);
|
||||
}
|
||||
|
||||
/// <summary>"Variable", "Constant", "Quality".</summary>
|
||||
public static string RateControlLabel(RateControl rateControl) => Loc.L("Export.RateControl." + rateControl);
|
||||
|
||||
/// <summary>"Forward", "Reverse", "Boomerang" (<see cref="PlaybackDirection"/>).</summary>
|
||||
public static string DirectionLabel(string direction) =>
|
||||
Loc.L("Export.Direction." + CultureInfo.InvariantCulture.TextInfo.ToTitleCase(PlaybackDirection.IsKnown(direction) ? direction.ToLowerInvariant() : PlaybackDirection.Forward));
|
||||
}
|
||||
@@ -34,6 +34,18 @@ public sealed record ExportPlan(ResolvedExport Export, RenderSetup Setup, Export
|
||||
|
||||
/// <summary>The encoder shrank the output (by more than the rounding to even sizes every encoder makes).</summary>
|
||||
public bool IsCapped => EncodedSize.Width < OutputSize.Width - 1 || EncodedSize.Height < OutputSize.Height - 1;
|
||||
|
||||
/// <summary>
|
||||
/// The frames as the encoder receives them (owner review 1, R8): the plan played as the export's playback says
|
||||
/// (direction, loops, fades, hold), which gives the video's duration and frame count.
|
||||
/// </summary>
|
||||
public OutputProgram? Program { get; init; }
|
||||
|
||||
/// <summary>The video's duration in seconds, holds and loops included.</summary>
|
||||
public double DurationSeconds => Program?.DurationSeconds ?? Setup.Plan.DurationSeconds;
|
||||
|
||||
/// <summary>The pictures the encoder receives (and the render renders), every loop included.</summary>
|
||||
public int FrameCount => Program?.Count ?? Setup.Plan.Frames.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -88,7 +100,8 @@ public sealed class ExportPlanner(SequenceContent content, IReadOnlyList<IVideoE
|
||||
var (name, error) = FileName(export.NameTemplate, resolved, setup);
|
||||
// The estimates follow the setup, which renders the adapted size the encoder may cap (RenderSetup.Create).
|
||||
var size = RenderSize.Of(input.Project.Camera, resolved, content.SourceWidth, content.SourceHeight, RenderOptions.Default.MaxWorkingLongEdge);
|
||||
return new ExportPlan(resolved, setup, setup.Estimate(model), name, error) { OutputSize = size };
|
||||
// The program the render will play (RenderSetup.Program): playback applied, a boomerang over star trails played forward.
|
||||
return new ExportPlan(resolved, setup, setup.Estimate(model), name, error) { OutputSize = size, Program = setup.Program };
|
||||
}
|
||||
|
||||
/// <summary>The first problem of a name template, localised; null when it is valid.</summary>
|
||||
|
||||
+485
-163
@@ -19,77 +19,6 @@ using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>A preset card of the Export tab (Export.html): what it renders and what it will cost on this machine.</summary>
|
||||
public sealed class PresetCard(ExportTab owner, ExportChoice choice) : ObservableObject
|
||||
{
|
||||
private string? _format;
|
||||
private string? _encoding;
|
||||
private string? _estimate;
|
||||
private bool _isSelected;
|
||||
|
||||
public ExportChoice Choice { get; } = choice;
|
||||
|
||||
public string Name => Choice.Name;
|
||||
|
||||
public bool IsRecommended => Choice.IsRecommended;
|
||||
|
||||
/// <summary>Sequence presets apply full settings; export presets only choose the output.</summary>
|
||||
public bool IsSequencePreset => Choice.Sequence is not null;
|
||||
|
||||
/// <summary>What choosing the card does, or why it cannot be chosen now (a job runs, the project cannot change).</summary>
|
||||
public string ToolTip => owner.Editor.LockedToolTip ?? (Choice.Reason is { } reason
|
||||
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
|
||||
: Loc.L("Tooltips.Editor.Export.Preset", Name));
|
||||
|
||||
public string BatchToolTip => owner.Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.InBatch");
|
||||
|
||||
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
|
||||
public string? Format { get => _format; private set => Set(ref _format, value); }
|
||||
|
||||
/// <summary>"120 Mb/s · 0.07 bpp · NVENC".</summary>
|
||||
public string? Encoding { get => _encoding; private set => Set(ref _encoding, value); }
|
||||
|
||||
/// <summary>"2.2 GB · about 5 min".</summary>
|
||||
public string? Estimate { get => _estimate; private set => Set(ref _estimate, value); }
|
||||
|
||||
public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); }
|
||||
|
||||
/// <summary>Ticked for "Batch…" (export presets only).</summary>
|
||||
public bool IsInBatch
|
||||
{
|
||||
get => owner.IsInBatch(Choice.ExportPresetId);
|
||||
set => owner.SetInBatch(Choice.ExportPresetId, value);
|
||||
}
|
||||
|
||||
public bool CanBatch => !IsSequencePreset;
|
||||
|
||||
public ICommand SelectCommand => owner.SelectCommand;
|
||||
|
||||
/// <remarks>A server sequence renders on the server: this PC's encoders neither name nor rule out the encoding.</remarks>
|
||||
public void Update(ExportPlan? plan)
|
||||
{
|
||||
if (plan is null)
|
||||
{
|
||||
Format = Encoding = Estimate = null;
|
||||
return;
|
||||
}
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
var remote = owner.Editor.IsRemote;
|
||||
Format = EditorText.Format(plan.Export, settings.Width, settings.Height);
|
||||
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, remote ? null : plan.Setup.Encoder.Capability?.Name);
|
||||
Estimate = remote || plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
|
||||
}
|
||||
|
||||
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
|
||||
|
||||
/// <summary>A job of the sequence started or ended, or the project became read-only: the tooltips say why the card waits.</summary>
|
||||
public void RefreshLocked()
|
||||
{
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A codec choice of the Output panel with the profile and depth it implies.</summary>
|
||||
public sealed record CodecChoice(VideoCodec Codec, CodecProfile Profile, int BitDepth)
|
||||
{
|
||||
@@ -104,10 +33,15 @@ public sealed record SaveChoice(string? Folder, bool Browse = false)
|
||||
public string Label => Browse ? Loc.L("Editor.Export.Browse") : Folder is null ? Loc.L("Editor.Export.SequenceFolder") : Path.GetFileName(Folder.TrimEnd('\\', '/'));
|
||||
}
|
||||
|
||||
/// <summary>A choice that may not apply now (Boomerang with star trails): disabled in the list, its reason in the tooltip.</summary>
|
||||
public sealed record GatedChoice(object Value, string Label, bool IsAvailable, string ToolTip);
|
||||
|
||||
/// <summary>
|
||||
/// Export (Export.html, BRIEF §11.4–11.5): preset cards with size and time estimates, the Output panel (container,
|
||||
/// codec, size, frame rate, quality, encoder, colour depth, name template, folder) with the estimate and the encoder's
|
||||
/// notices, and the render actions (now, queue, batch). Editing a value makes the preset "Custom" (§11.4).
|
||||
/// Export (Export.html, BRIEF §11.4–11.5, owner review 1 R3/R8): the preset table with size and time estimates, the Output
|
||||
/// panel in four collapsible groups (Output: container, codec, resolution, frame rate, colour depth; Encoding: encoder,
|
||||
/// rate control, bit rate or quality, keyframes, B-frames, profile; Playback: direction, loops, fades, hold; File: name
|
||||
/// template, folder, sync, restore), the encoder's notices, and a fixed footer with the result line and the render
|
||||
/// actions (now, queue, batch). Editing a value makes the preset "Custom" (§11.4).
|
||||
/// </summary>
|
||||
public sealed class ExportTab : EditorTab
|
||||
{
|
||||
@@ -119,79 +53,138 @@ public sealed class ExportTab : EditorTab
|
||||
new(VideoCodec.Tiff16Sequence, CodecProfile.Auto, 16), new(VideoCodec.LinearDngSequence, CodecProfile.Auto, 16),
|
||||
];
|
||||
|
||||
/// <summary>The Resolution choice's value for the preset's own box (no override).</summary>
|
||||
public const string PresetResolution = "preset";
|
||||
|
||||
/// <summary>The Resolution choice's value for the source size (a box of 0 × 0).</summary>
|
||||
public const string SourceResolution = "source";
|
||||
|
||||
/// <summary>The Resolution choice's value that shows the Width × Height fields.</summary>
|
||||
public const string CustomResolution = "custom";
|
||||
|
||||
/// <summary>The longest fade or hold the sliders reach (seconds); the fields take up to the playback's own limits.</summary>
|
||||
public const double SliderSeconds = 10;
|
||||
|
||||
private readonly LatestRunner _estimates = new(TimeSpan.FromMilliseconds(250));
|
||||
private readonly AsyncRelayCommand _renderNow;
|
||||
private readonly AsyncRelayCommand _addToQueue;
|
||||
private readonly AsyncRelayCommand _batch;
|
||||
private readonly AsyncRelayCommand _restore;
|
||||
private SavedCopy? _selectedCopy;
|
||||
private IReadOnlyList<PresetCard> _cards = [];
|
||||
private IReadOnlyList<PresetRow> _presets = [];
|
||||
private IReadOnlyList<PresetGroup> _presetGroups = [];
|
||||
private IReadOnlyList<CodecChoice> _codecChoices = [];
|
||||
private IReadOnlyList<Choice> _encoders = [];
|
||||
private IReadOnlyList<SaveChoice> _saveChoices = [];
|
||||
private IReadOnlyList<Choice> _depths = [];
|
||||
private IReadOnlyList<Choice> _keyframeChoices = [];
|
||||
private IReadOnlyList<Choice> _bFrameChoices = [];
|
||||
private IReadOnlyList<Choice> _profileChoices = [];
|
||||
private IReadOnlyList<GatedChoice> _directions = [];
|
||||
private IReadOnlyList<string> _notices = [];
|
||||
private bool _refreshing;
|
||||
private bool _customResolution;
|
||||
|
||||
public ExportTab(EditorViewModel editor)
|
||||
: base(editor, "Export", AdvisorSection.Export)
|
||||
{
|
||||
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.IsLocked);
|
||||
SelectCommand = new RelayCommand(p => Select(p as PresetRow), _ => !Editor.IsLocked);
|
||||
_renderNow = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: false), () => Editor.CanRender);
|
||||
_addToQueue = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.Normal, batch: false), () => Editor.CanRender);
|
||||
_batch = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: true), () => Editor.CanRender && Batch.Count > 0);
|
||||
HistoryCommand = new RelayCommand(OpenHistory);
|
||||
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
|
||||
VideosCommand = new RelayCommand(OpenVideos, () => CanOpenVideos);
|
||||
_restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null);
|
||||
SaveProjectCommand = new AsyncRelayCommand(() => new ProjectFiles(Editor.Shell).SaveAsync(Editor.Session), () => !Editor.IsRemote);
|
||||
ResetFrameRateCommand = new RelayCommand(() => EditOverrides(o => o with { FrameRate = null }));
|
||||
ResetFrameRateCommand = new RelayCommand(() => SetFrameRate(null));
|
||||
ResetRateControlCommand = new RelayCommand(() => EditOverrides(o => o with { RateControl = null }));
|
||||
ResetQualityCommand = new RelayCommand(() => EditOverrides(o => o with { BitRate = null, Quality = null }));
|
||||
ResetProfileCommand = new RelayCommand(() => EditOverrides(o => o with { Profile = null, BFrames = IsBaseline(o.Profile) ? null : o.BFrames }));
|
||||
ResetPlaybackCommand = new RelayCommand(() => EditExport(e => e with { Playback = null }), () => !IsPlaybackDefault);
|
||||
Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width"));
|
||||
Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height"));
|
||||
NameTemplate = new EditableField(string.Empty, ValidateTemplate, v => EditExport(e => e with { NameTemplate = v }), () => Loc.L("Tooltips.Editor.Export.Name"));
|
||||
FadeInField = SecondsField(PlaybackSettings.MaxFadeSeconds, (p, v) => p with { FadeIn = v }, "Tooltips.Export.FadeIn");
|
||||
FadeOutField = SecondsField(PlaybackSettings.MaxFadeSeconds, (p, v) => p with { FadeOut = v }, "Tooltips.Export.FadeOut");
|
||||
HoldEndField = SecondsField(PlaybackSettings.MaxHoldSeconds, (p, v) => p with { HoldEnd = v }, "Tooltips.Export.HoldEnd");
|
||||
OutputGroup = new SettingGroup("export.output", "Export.Group.Output", "Tooltips.Export.Group.Output", expandedByDefault: true);
|
||||
EncodingGroup = new SettingGroup("export.encoding", "Export.Group.Encoding", "Tooltips.Export.Group.Encoding", expandedByDefault: false);
|
||||
PlaybackGroup = new SettingGroup("export.playback", "Export.Group.Playback", "Tooltips.Export.Group.Playback", expandedByDefault: false);
|
||||
FileGroup = new SettingGroup("export.file", "Export.Group.File", "Tooltips.Export.Group.File", expandedByDefault: true);
|
||||
_selectedCopy = SavedCopies.FirstOrDefault();
|
||||
LoadCards();
|
||||
LoadTable();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public IReadOnlyList<PresetCard> Cards { get => _cards; private set => Set(ref _cards, value); }
|
||||
// ---- Preset table (measure area) ----
|
||||
|
||||
/// <summary>Every preset, in table order.</summary>
|
||||
public IReadOnlyList<PresetRow> Presets { get => _presets; private set => Set(ref _presets, value); }
|
||||
|
||||
/// <summary>The presets by group (Video, Social, Intermediate, Image sequence, Web), each one opened or closed.</summary>
|
||||
public IReadOnlyList<PresetGroup> PresetGroups { get => _presetGroups; private set => Set(ref _presetGroups, value); }
|
||||
|
||||
public ICommand SelectCommand { get; }
|
||||
|
||||
// ---- The groups of the Output panel ----
|
||||
|
||||
public SettingGroup OutputGroup { get; }
|
||||
|
||||
public SettingGroup EncodingGroup { get; }
|
||||
|
||||
public SettingGroup PlaybackGroup { get; }
|
||||
|
||||
public SettingGroup FileGroup { get; }
|
||||
|
||||
// ---- Footer ----
|
||||
|
||||
public ICommand RenderNowCommand => _renderNow;
|
||||
|
||||
public ICommand AddToQueueCommand => _addToQueue;
|
||||
|
||||
public ICommand BatchCommand => _batch;
|
||||
|
||||
/// <summary>Jobs, filtered on this sequence (its renders and analyses).</summary>
|
||||
public ICommand HistoryCommand { get; }
|
||||
|
||||
/// <summary>"Reveal in Explorer" for the newest render (BRIEF §11.5 follow-up).</summary>
|
||||
public ICommand RevealLastCommand { get; }
|
||||
|
||||
public string AddToQueueToolTip => Editor.RenderBlockedReason ?? Loc.L("Tooltips.Editor.Export.AddToQueue");
|
||||
|
||||
/// <summary>"Batch (2)": the ticked presets.</summary>
|
||||
public string BatchText => Loc.L("Export.Footer.Batch", Batch.Count.ToString("N0", Loc.Culture));
|
||||
|
||||
public string BatchToolTip => Editor.RenderBlockedReason ?? (Batch.Count == 0 ? Loc.L("Tooltips.Editor.Export.BatchEmpty")
|
||||
: Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.BatchServer", Editor.ServerName)
|
||||
: Loc.L("Tooltips.Editor.Export.Batch"));
|
||||
|
||||
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
|
||||
|
||||
/// <summary>The "history" link opens this PC's Jobs screen, which does not list a server's jobs.</summary>
|
||||
public bool CanOpenHistory => !Editor.IsRemote;
|
||||
: Loc.L("Tooltips.Export.Footer.Batch"));
|
||||
|
||||
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
|
||||
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
|
||||
|
||||
/// <summary>"Videos (3)": the renders of this sequence.</summary>
|
||||
public string VideosText => Loc.L("Export.Footer.Videos", Editor.Session.Content.Renders.Count.ToString("N0", Loc.Culture));
|
||||
|
||||
/// <summary>Opens the Videos section filtered on this sequence (owner review 1, R9).</summary>
|
||||
public ICommand VideosCommand { get; }
|
||||
|
||||
/// <summary>The app has a Videos section to open.</summary>
|
||||
public bool CanOpenVideos => VideosLink.Find(Editor.Shell.AllSections) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// "2026-09-28 Harbour sunset - 4K archive.mp4 · 1.2 GB · about 4 min · 42 s · 1,260 frames": the result, its estimates,
|
||||
/// and the video's duration and frames as the playback plays them; null before the plan.
|
||||
/// </summary>
|
||||
public string? FooterSummary => Editor.Plan is { } plan
|
||||
? ExportSummaries.Footer(plan.FileName, Estimated?.Estimate, plan.DurationSeconds, plan.FrameCount)
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// Saves a <c>.chronos</c> project file of this sequence and its settings (BRIEF §18); a server sequence has no
|
||||
/// archive on this PC for the file to name.
|
||||
/// archive on this PC for the file to name. Offered in the project ▾ menu.
|
||||
/// </summary>
|
||||
public ICommand SaveProjectCommand { get; }
|
||||
|
||||
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
|
||||
|
||||
// ---- Export "Sync" (Export.html, next to Save to) ----
|
||||
// ---- File: Sync ----
|
||||
|
||||
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
|
||||
public bool SyncToServer
|
||||
@@ -218,7 +211,7 @@ public sealed class ExportTab : EditorTab
|
||||
/// <summary>A server sequence renders into its exports folder on the server.</summary>
|
||||
public bool CanChooseFolder => !Editor.IsRemote;
|
||||
|
||||
// ---- "Save both" copies of this PC's settings ----
|
||||
// ---- File: "Save both" copies of this PC's settings ----
|
||||
|
||||
public IReadOnlyList<SavedCopy> SavedCopies => Editor.Session.Content.SavedCopies;
|
||||
|
||||
@@ -244,7 +237,7 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public ICommand RestoreCommand => _restore;
|
||||
|
||||
public ICommand ResetFrameRateCommand { get; }
|
||||
// ---- Output ----
|
||||
|
||||
/// <summary>"Output · 4K archive".</summary>
|
||||
public string Title => Loc.L("Editor.Export.Output", Editor.Plan?.PresetName ?? ProcessingJobs.PresetName(ExportResolver.Resolve(Export)));
|
||||
@@ -276,6 +269,46 @@ public sealed class ExportTab : EditorTab
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Preset, Source, the standard sizes (720p … 8K) and Custom (decision 7).</summary>
|
||||
public IReadOnlyList<Choice> Resolutions { get; } =
|
||||
[
|
||||
new(PresetResolution, "Export.Resolution.Preset"), new(SourceResolution, "Export.Resolution.Source"),
|
||||
.. ExportRules.StandardResolutions.Select(r => new Choice(r.Key, r.LabelKey)),
|
||||
new(CustomResolution, "Export.Resolution.Custom"),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The size the export asks for: the preset's box, the source, a standard box (written into the overrides as landscape,
|
||||
/// so the chosen proportions are fitted in it: 4K at 9:16 renders 2160 × 3840), or Custom with Width × Height.
|
||||
/// </summary>
|
||||
public Choice? SelectedResolution
|
||||
{
|
||||
get => Resolutions.FirstOrDefault(c => Equals(c.Value, ResolutionKey(Export.Overrides, _customResolution)));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not string key) return;
|
||||
_customResolution = key == CustomResolution;
|
||||
if (_customResolution)
|
||||
{
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(IsCustomResolution));
|
||||
return;
|
||||
}
|
||||
var (width, height) = key switch
|
||||
{
|
||||
PresetResolution => ((int?)null, (int?)null),
|
||||
SourceResolution => (0, 0),
|
||||
_ => ExportRules.StandardResolutions.Where(r => r.Key == key).Select(r => ((int?)r.Width, (int?)r.Height)).First(),
|
||||
};
|
||||
Width.Revert();
|
||||
Height.Revert();
|
||||
EditOverrides(o => o with { Width = width, Height = height });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Custom is chosen: the Width × Height fields show.</summary>
|
||||
public bool IsCustomResolution => Equals(SelectedResolution?.Value, CustomResolution);
|
||||
|
||||
public EditableField Width { get; }
|
||||
|
||||
public EditableField Height { get; }
|
||||
@@ -311,7 +344,7 @@ public sealed class ExportTab : EditorTab
|
||||
get => FrameRates.FirstOrDefault(c => FrameRateText.TryParse((string)c.Value, out var r) && FrameRateText.AreEqual(r, Resolved.FrameRate));
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value?.Value is string rate) EditOverrides(o => o with { FrameRate = rate });
|
||||
if (!_refreshing && value?.Value is string rate) SetFrameRate(rate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,29 +353,27 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public string FrameRateAutoToolTip => Loc.L("Tooltips.Editor.Export.FrameRateAuto", EditorText.FrameRate(ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() }).FrameRate));
|
||||
|
||||
/// <summary>Bit rate in Mb/s (video) or quality 1–100 (JPEG, MJPEG, GIF).</summary>
|
||||
public double Quality
|
||||
public ICommand ResetFrameRateCommand { get; }
|
||||
|
||||
public IReadOnlyList<Choice> Depths { get => _depths; private set => Set(ref _depths, value); }
|
||||
|
||||
public Choice? SelectedDepth
|
||||
{
|
||||
get => IsBitRate ? (Editor.Plan?.Setup.Encoder.Settings.BitRate ?? Resolved.BitRate) / 1e6 : Resolved.Quality;
|
||||
get => Depths.FirstOrDefault(d => (int)d.Value == Resolved.BitDepth) ?? Depths[0];
|
||||
set
|
||||
{
|
||||
if (_refreshing) return;
|
||||
if (IsBitRate) EditOverrides(o => o with { BitRate = (long)(double.Round(value) * 1e6) }, "Export.Quality");
|
||||
else EditOverrides(o => o with { Quality = (int)double.Round(value) }, "Export.Quality");
|
||||
if (_refreshing || value?.Value is not int depth || depth == Resolved.BitDepth) return;
|
||||
EditOverrides(o => o with
|
||||
{
|
||||
BitDepth = depth,
|
||||
Profile = Resolved.Codec == VideoCodec.Hevc ? (depth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain).ToString() : o.Profile,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBitRate => !VideoCodecInfo.IsManaged(Resolved.Codec);
|
||||
public bool CanChooseDepth => Depths.Count > 1;
|
||||
|
||||
public double QualityMaximum => IsBitRate ? 400 : 100;
|
||||
|
||||
public bool IsQualityApplicable => IsBitRate || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif;
|
||||
|
||||
public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless");
|
||||
|
||||
public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture);
|
||||
|
||||
public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Editor.Export.BitRate" : "Tooltips.Editor.Export.Quality");
|
||||
// ---- Encoding ----
|
||||
|
||||
public IReadOnlyList<Choice> Encoders { get => _encoders; private set => Set(ref _encoders, value); }
|
||||
|
||||
@@ -367,23 +398,193 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public bool IsHardware => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability?.Hardware == true;
|
||||
|
||||
public IReadOnlyList<Choice> Depths { get => _depths; private set => Set(ref _depths, value); }
|
||||
/// <summary>Variable, constant, quality (H.264, HEVC and AV1 only).</summary>
|
||||
public IReadOnlyList<Choice> RateControls { get; } =
|
||||
[.. Enum.GetValues<RateControl>().Select(r => new Choice(r, "Export.RateControl." + r))];
|
||||
|
||||
public Choice? SelectedDepth
|
||||
public Choice? SelectedRateControl
|
||||
{
|
||||
get => Depths.FirstOrDefault(d => (int)d.Value == Resolved.BitDepth) ?? Depths[0];
|
||||
get => RateControls.FirstOrDefault(c => Equals(c.Value, Resolved.RateControl));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not int depth || depth == Resolved.BitDepth) return;
|
||||
if (_refreshing || value?.Value is not RateControl rateControl || rateControl == Resolved.RateControl) return;
|
||||
// The preset's own rate control (every preset is variable) is no override.
|
||||
EditOverrides(o => o with { RateControl = rateControl == PresetValues.RateControl ? null : rateControl.ToString().ToLowerInvariant() });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The codec has a rate control (and a keyframe interval) to choose.</summary>
|
||||
public bool HasRateControl => ExportRules.HasRateControl(Resolved.Codec);
|
||||
|
||||
public string RateControlToolTip => ExportRules.RateControlBlocked(Resolved.Codec) ?? Loc.L("Tooltips.Export.RateControl");
|
||||
|
||||
public bool IsRateControlSet => HasRateControl && Export.Overrides.RateControl is not null;
|
||||
|
||||
public ICommand ResetRateControlCommand { get; }
|
||||
|
||||
/// <summary>Bit rate in Mb/s (variable and constant rate) or quality 1–100 (quality rate control, JPEG, MJPEG, GIF).</summary>
|
||||
public double Quality
|
||||
{
|
||||
get => IsBitRate ? (Editor.Plan?.Setup.Encoder.Settings.BitRate ?? Resolved.BitRate) / 1e6 : Resolved.Quality;
|
||||
set
|
||||
{
|
||||
if (_refreshing) return;
|
||||
if (IsBitRate) EditOverrides(o => o with { BitRate = (long)(double.Round(value) * 1e6) }, "Export.Quality");
|
||||
else EditOverrides(o => o with { Quality = (int)double.Round(value) }, "Export.Quality");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The slider sets the bit rate: a video codec at variable or constant rate.</summary>
|
||||
public bool IsBitRate => HasRateControl && Resolved.RateControl != RateControl.Quality;
|
||||
|
||||
public double QualityMaximum => IsBitRate ? 400 : 100;
|
||||
|
||||
public bool IsQualityApplicable => HasRateControl || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif;
|
||||
|
||||
public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless");
|
||||
|
||||
/// <summary>"Bit rate" or "Quality": the row's label follows what the slider sets.</summary>
|
||||
public string QualityHeader => Loc.L(IsBitRate ? "Export.BitRate" : "Editor.Export.Quality");
|
||||
|
||||
public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture);
|
||||
|
||||
public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Export.BitRate" : "Tooltips.Export.Quality");
|
||||
|
||||
public bool IsQualitySet => IsQualityApplicable && (IsBitRate ? Export.Overrides.BitRate : Export.Overrides.Quality) is not null;
|
||||
|
||||
public ICommand ResetQualityCommand { get; }
|
||||
|
||||
/// <summary>Auto (the preset's), then 0.5 to 10 s.</summary>
|
||||
public IReadOnlyList<Choice> KeyframeChoices { get => _keyframeChoices; private set => Set(ref _keyframeChoices, value); }
|
||||
|
||||
/// <summary>
|
||||
/// The keyframe interval in seconds (decision 6), stored as whole frames at the export's rate
|
||||
/// (<see cref="ExportOverrides.GopFrames"/>); 0 is Auto (the preset's).
|
||||
/// </summary>
|
||||
public Choice? SelectedKeyframes
|
||||
{
|
||||
get
|
||||
{
|
||||
var seconds = Export.Overrides.GopFrames is { } gop ? ExportRules.NearestKeyframeSeconds(gop, Resolved.FrameRate) : 0.0;
|
||||
return KeyframeChoices.FirstOrDefault(c => (double)c.Value == seconds);
|
||||
}
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not double seconds) return;
|
||||
var rate = Resolved.FrameRate;
|
||||
EditOverrides(o => o with { GopFrames = seconds <= 0 ? null : ExportRules.GopFrames(seconds, rate) });
|
||||
}
|
||||
}
|
||||
|
||||
public string KeyframesToolTip => ExportRules.KeyframesBlocked(Resolved.Codec) ?? Loc.L("Tooltips.Export.Keyframes");
|
||||
|
||||
/// <summary>Auto (the preset's), then 0 to 4.</summary>
|
||||
public IReadOnlyList<Choice> BFrameChoices { get => _bFrameChoices; private set => Set(ref _bFrameChoices, value); }
|
||||
|
||||
/// <summary>B-frames, −1 for Auto (the preset's).</summary>
|
||||
public Choice? SelectedBFrames
|
||||
{
|
||||
get => BFrameChoices.FirstOrDefault(c => (int)c.Value == (Export.Overrides.BFrames ?? -1));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not int count) return;
|
||||
EditOverrides(o => o with { BFrames = count < 0 ? null : count });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Baseline, MJPEG, GIF, APNG and the image sequences take no B-frames.</summary>
|
||||
public bool CanChooseBFrames => ExportRules.BFramesBlocked(Resolved.Codec, Resolved.Profile) is null;
|
||||
|
||||
public string BFramesToolTip => ExportRules.BFramesBlocked(Resolved.Codec, Resolved.Profile) ?? Loc.L("Tooltips.Export.BFrames");
|
||||
|
||||
/// <summary>The profiles of the codec at the chosen depth.</summary>
|
||||
public IReadOnlyList<Choice> ProfileChoices { get => _profileChoices; private set => Set(ref _profileChoices, value); }
|
||||
|
||||
public Choice? SelectedProfile
|
||||
{
|
||||
get => ProfileChoices.FirstOrDefault(c => Equals(c.Value, Resolved.Profile)) ?? ProfileChoices.FirstOrDefault();
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not CodecProfile profile || profile == Resolved.Profile) return;
|
||||
// Baseline takes no B-frames: none are asked for while it is chosen, the preset's again once it is not.
|
||||
EditOverrides(o => o with
|
||||
{
|
||||
BitDepth = depth,
|
||||
Profile = Resolved.Codec == VideoCodec.Hevc ? (depth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain).ToString() : o.Profile,
|
||||
Profile = profile.ToString(),
|
||||
BFrames = profile == CodecProfile.H264Baseline ? 0 : IsBaseline(o.Profile) ? null : o.BFrames,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanChooseDepth => Depths.Count > 1;
|
||||
public bool CanChooseProfile => ProfileChoices.Count > 1;
|
||||
|
||||
public string ProfileToolTip => ExportRules.ProfileBlocked(Resolved.Codec, Resolved.BitDepth) ?? Loc.L("Tooltips.Export.Profile");
|
||||
|
||||
public bool IsProfileSet => CanChooseProfile && Export.Overrides.Profile is not null;
|
||||
|
||||
public ICommand ResetProfileCommand { get; }
|
||||
|
||||
// ---- Playback (settings format 3) ----
|
||||
|
||||
/// <summary>Forward, Reverse, Boomerang; Boomerang is not offered with star trails (decision 11).</summary>
|
||||
public IReadOnlyList<GatedChoice> Directions { get => _directions; private set => Set(ref _directions, value); }
|
||||
|
||||
public GatedChoice? SelectedDirection
|
||||
{
|
||||
get => Directions.FirstOrDefault(d => Equals(d.Value, Playback.EffectiveDirection));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value is not { IsAvailable: true, Value: string direction } || direction == Playback.EffectiveDirection) return;
|
||||
EditPlayback(p => p with { Direction = direction });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Passes of the whole video, 1 to 10.</summary>
|
||||
public double Loops
|
||||
{
|
||||
get => Playback.EffectiveLoops;
|
||||
set
|
||||
{
|
||||
var loops = int.Clamp((int)double.Round(value), 1, PlaybackSettings.MaxLoops);
|
||||
if (_refreshing || loops == Playback.EffectiveLoops) return;
|
||||
EditPlayback(p => p with { Loops = loops }, "Export.Loops");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"×2".</summary>
|
||||
public string LoopsText => Loc.L("Export.Summary.Loops", Playback.EffectiveLoops);
|
||||
|
||||
/// <summary>Seconds of fade from black (slider 0–10, step 0.5; the field takes up to 30).</summary>
|
||||
public double FadeIn
|
||||
{
|
||||
get => double.Min(Playback.EffectiveFadeIn, SliderSeconds);
|
||||
set => SetSeconds(value, Playback.EffectiveFadeIn, (p, v) => p with { FadeIn = v }, "Export.FadeIn");
|
||||
}
|
||||
|
||||
public double FadeOut
|
||||
{
|
||||
get => double.Min(Playback.EffectiveFadeOut, SliderSeconds);
|
||||
set => SetSeconds(value, Playback.EffectiveFadeOut, (p, v) => p with { FadeOut = v }, "Export.FadeOut");
|
||||
}
|
||||
|
||||
/// <summary>Seconds the last frame stays (slider 0–10, step 0.5; the field takes up to 60).</summary>
|
||||
public double HoldEnd
|
||||
{
|
||||
get => double.Min(Playback.EffectiveHoldEnd, SliderSeconds);
|
||||
set => SetSeconds(value, Playback.EffectiveHoldEnd, (p, v) => p with { HoldEnd = v }, "Export.HoldEnd");
|
||||
}
|
||||
|
||||
public EditableField FadeInField { get; }
|
||||
|
||||
public EditableField FadeOutField { get; }
|
||||
|
||||
public EditableField HoldEndField { get; }
|
||||
|
||||
/// <summary>Forward, once, without fades or hold: the project writes no playback (and keeps its settings format).</summary>
|
||||
public bool IsPlaybackDefault => Export.Playback is null or { IsDefault: true };
|
||||
|
||||
public ICommand ResetPlaybackCommand { get; }
|
||||
|
||||
// ---- File ----
|
||||
|
||||
public EditableField NameTemplate { get; }
|
||||
|
||||
@@ -411,6 +612,8 @@ public sealed class ExportTab : EditorTab
|
||||
? Loc.L("Tooltips.Editor.Export.FolderServer")
|
||||
: Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty);
|
||||
|
||||
// ---- Estimate and notices ----
|
||||
|
||||
public string? EstimatedSize => Estimated is { } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null;
|
||||
|
||||
/// <summary>"about 5 min · NVENC"; without this PC's encoder for a server sequence.</summary>
|
||||
@@ -420,14 +623,9 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public string? ResultName => Editor.Plan?.FileName;
|
||||
|
||||
/// <summary>What the encoder changed or cannot do (localised notices and render remarks).</summary>
|
||||
/// <summary>What the encoder changed or cannot do, and what the playback could not do (localised notices and render remarks).</summary>
|
||||
public IReadOnlyList<string> Notices { get => _notices; private set => Set(ref _notices, value); }
|
||||
|
||||
/// <summary>"Previous renders of this sequence: 2 · last 2026-09-21".</summary>
|
||||
public string HistoryText => Editor.Session.Content.Renders is { Count: > 0 } renders
|
||||
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
|
||||
: Loc.L("Editor.Export.NoHistory");
|
||||
|
||||
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
|
||||
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
|
||||
|
||||
@@ -466,12 +664,18 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public IReadOnlyList<string> Batch => Export.Batch;
|
||||
|
||||
/// <summary>Completes when the card estimates in flight are done.</summary>
|
||||
/// <summary>Completes when the preset estimates in flight are done.</summary>
|
||||
public Task EstimatesIdle => _estimates.Idle;
|
||||
|
||||
private ExportSettings Export => Editor.Session.Project.Export;
|
||||
|
||||
private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export);
|
||||
private PlaybackSettings Playback => Export.Playback ?? new PlaybackSettings();
|
||||
|
||||
/// <summary>The project's export as the plan resolves it, read at once (the plan follows an edit later).</summary>
|
||||
private ResolvedExport Resolved => ExportResolver.Resolve(Export);
|
||||
|
||||
/// <summary>The export's preset without overrides: what Auto and Reset go back to.</summary>
|
||||
private ResolvedExport PresetValues => ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() });
|
||||
|
||||
/// <summary>The plan when its estimates mean something: this PC can encode it, or the server renders it.</summary>
|
||||
private ExportPlan? Estimated => Editor.Plan is { } plan && (Editor.IsRemote || plan.Setup.Encoder.IsReady) ? plan : null;
|
||||
@@ -484,9 +688,26 @@ public sealed class ExportTab : EditorTab
|
||||
EditExport(e => e with { Batch = value ? [.. e.Batch, presetId] : [.. e.Batch.Where(b => !b.Equals(presetId, StringComparison.OrdinalIgnoreCase))] });
|
||||
}
|
||||
|
||||
/// <summary>The preset cards take more of the height than the preview (Export.html).</summary>
|
||||
/// <summary>The preset table takes more of the height than the preview (Export.html).</summary>
|
||||
public override bool PrefersTallMeasure => true;
|
||||
|
||||
/// <summary>
|
||||
/// The Resolution choice of <paramref name="overrides"/>: Preset without a box of its own, Source for 0 × 0, a standard
|
||||
/// size for its box, else Custom (also while <paramref name="custom"/>, chosen to type a size).
|
||||
/// </summary>
|
||||
public static string ResolutionKey(ExportOverrides overrides, bool custom = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(overrides);
|
||||
if (custom) return CustomResolution;
|
||||
return (overrides.Width, overrides.Height) switch
|
||||
{
|
||||
(null, null) => PresetResolution,
|
||||
(0, 0) => SourceResolution,
|
||||
({ } w, { } h) when ExportRules.StandardResolutions.FirstOrDefault(r => r.Width == w && r.Height == h) is { Key: { } key } => key,
|
||||
_ => CustomResolution,
|
||||
};
|
||||
}
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
@@ -494,20 +715,21 @@ public sealed class ExportTab : EditorTab
|
||||
try
|
||||
{
|
||||
UpdateLists();
|
||||
LoadBox();
|
||||
LoadFields();
|
||||
SaveChoices = !CanChooseFolder ? [new SaveChoice(null)]
|
||||
: Export.Folder is { } folder ? [new SaveChoice(null), new SaveChoice(folder), new SaveChoice(null, Browse: true)]
|
||||
: [new SaveChoice(null), new SaveChoice(null, Browse: true)];
|
||||
if (!NameTemplate.IsDirty) NameTemplate.Load(Export.NameTemplate);
|
||||
UpdateSummaries();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
SelectCards();
|
||||
foreach (var card in Cards) card.RefreshBatch();
|
||||
_ = EstimateCardsAsync();
|
||||
SelectRows();
|
||||
foreach (var row in Presets) row.RefreshBatch();
|
||||
_ = EstimateRowsAsync();
|
||||
}
|
||||
|
||||
public override void OnPlanChanged()
|
||||
@@ -515,9 +737,10 @@ public sealed class ExportTab : EditorTab
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
LoadBox();
|
||||
LoadFields();
|
||||
UpdateLists();
|
||||
Notices = Editor.Plan is { } plan ? PlanNotices(plan) : [];
|
||||
UpdateSummaries();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
@@ -525,13 +748,13 @@ public sealed class ExportTab : EditorTab
|
||||
_refreshing = false;
|
||||
}
|
||||
// The plan follows the preset a read-only session chose to render.
|
||||
SelectCards();
|
||||
SelectRows();
|
||||
}
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
foreach (var card in Cards) card.RefreshLocked();
|
||||
foreach (var row in Presets) row.RefreshLocked();
|
||||
}
|
||||
|
||||
public override void OnContentChanged()
|
||||
@@ -539,8 +762,12 @@ public sealed class ExportTab : EditorTab
|
||||
// The ledger was read again: Send again goes by what it holds now.
|
||||
_sendQueued = false;
|
||||
_sendAgain?.RaiseCanExecuteChanged();
|
||||
LoadCards();
|
||||
LoadTable();
|
||||
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
|
||||
// The rows and groups keep texts in objects (a language switch comes this way too).
|
||||
_keyframeChoices = _bFrameChoices = _profileChoices = [];
|
||||
_directions = [];
|
||||
foreach (var group in new[] { OutputGroup, EncodingGroup, PlaybackGroup, FileGroup }) group.Refresh();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
@@ -559,6 +786,7 @@ public sealed class ExportTab : EditorTab
|
||||
{
|
||||
OnPropertyChanged(nameof(CanSync));
|
||||
OnPropertyChanged(nameof(SyncToolTip));
|
||||
FileGroup.Summary = FileSummary();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
@@ -569,15 +797,33 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
/// <summary>
|
||||
/// Width and Height edit the preset's box, which the chosen proportions are fitted in (owner review 1, R5): they show the
|
||||
/// resolved box (empty for a side the preset leaves to the source), not the size rendered (Output size).
|
||||
/// resolved box (empty for a side the preset leaves to the source), not the size rendered (Output size). The playback
|
||||
/// fields show the seconds in force.
|
||||
/// </summary>
|
||||
private void LoadBox()
|
||||
private void LoadFields()
|
||||
{
|
||||
var resolved = Resolved;
|
||||
if (!Width.IsDirty) Width.Load(resolved.Width > 0 ? resolved.Width.ToString(CultureInfo.InvariantCulture) : string.Empty);
|
||||
if (!Height.IsDirty) Height.Load(resolved.Height > 0 ? resolved.Height.ToString(CultureInfo.InvariantCulture) : string.Empty);
|
||||
var playback = Playback;
|
||||
if (!FadeInField.IsDirty) FadeInField.Load(SecondsText(playback.EffectiveFadeIn));
|
||||
if (!FadeOutField.IsDirty) FadeOutField.Load(SecondsText(playback.EffectiveFadeOut));
|
||||
if (!HoldEndField.IsDirty) HoldEndField.Load(SecondsText(playback.EffectiveHoldEnd));
|
||||
}
|
||||
|
||||
/// <summary>The one-line summaries the groups show while collapsed.</summary>
|
||||
private void UpdateSummaries()
|
||||
{
|
||||
var resolved = Resolved;
|
||||
var settings = Editor.Plan?.Setup.Encoder.Settings;
|
||||
OutputGroup.Summary = EditorText.Format(resolved, settings?.Width ?? resolved.Width, settings?.Height ?? resolved.Height);
|
||||
EncodingGroup.Summary = ExportSummaries.Encoding(resolved, settings?.BitRate ?? resolved.BitRate);
|
||||
PlaybackGroup.Summary = ExportSummaries.Playback(Export.Playback);
|
||||
FileGroup.Summary = FileSummary();
|
||||
}
|
||||
|
||||
private string FileSummary() => ExportSummaries.File(ResultName, SelectedSave?.Label ?? Loc.L("Editor.Export.SequenceFolder"), SyncToServer && CanSync);
|
||||
|
||||
/// <summary>"2160 × 3840".</summary>
|
||||
private static string SizeText((int Width, int Height) size) =>
|
||||
size.Width.ToString(Loc.Culture) + " × " + size.Height.ToString(Loc.Culture);
|
||||
@@ -596,7 +842,7 @@ public sealed class ExportTab : EditorTab
|
||||
return width > maxWidth || height > maxHeight ? (maxWidth, maxHeight) : plan.EncodedSize;
|
||||
}
|
||||
|
||||
/// <summary>The choices that depend on the resolved codec (new lists only when they change, so selections stay bound).</summary>
|
||||
/// <summary>The choices that depend on the resolved codec and the project (new lists only when they change, so selections stay bound).</summary>
|
||||
private void UpdateLists()
|
||||
{
|
||||
var resolved = Resolved;
|
||||
@@ -610,43 +856,77 @@ public sealed class ExportTab : EditorTab
|
||||
_ => [resolved.BitDepth],
|
||||
};
|
||||
if (!depths.SequenceEqual(Depths.Select(d => (int)d.Value))) Depths = [.. depths.Select(d => new Choice(d, "Editor.Export.Depth", d))];
|
||||
|
||||
// Auto names the preset's own value (its keyframe interval is in seconds, whatever the frame rate).
|
||||
var preset = PresetValues;
|
||||
var autoKeyframes = Auto(ExportRules.Seconds(ExportRules.GopSeconds(preset.GopFrames, preset.FrameRate)));
|
||||
if (KeyframeChoices.FirstOrDefault()?.Label != autoKeyframes)
|
||||
KeyframeChoices = [new Choice(0.0, "Editor.Value.Text", autoKeyframes), .. ExportRules.KeyframeSeconds.Select(s => new Choice(s, "Editor.Value.Text", ExportRules.Seconds(s)))];
|
||||
var autoBFrames = Auto(preset.BFrames.ToString(Loc.Culture));
|
||||
if (BFrameChoices.FirstOrDefault()?.Label != autoBFrames)
|
||||
BFrameChoices = [new Choice(-1, "Editor.Value.Text", autoBFrames), .. ExportRules.BFrameCounts.Select(n => new Choice(n, "Editor.Value.Number", n))];
|
||||
var profiles = ExportRules.Profiles(resolved.Codec, resolved.BitDepth);
|
||||
if (!profiles.Cast<object>().SequenceEqual(ProfileChoices.Select(c => c.Value)))
|
||||
ProfileChoices = [.. profiles.Select(p => new Choice(p, "Editor.Value.Text", ExportRules.ProfileLabel(p)))];
|
||||
|
||||
var starTrails = Editor.Session.Project.Stack.Mode == StackSetting.StarTrails;
|
||||
if (Directions.Count == 0 || Directions.Any(d => (string)d.Value == PlaybackDirection.Boomerang && d.IsAvailable == starTrails))
|
||||
{
|
||||
Directions =
|
||||
[
|
||||
.. PlaybackDirection.All.Select(d =>
|
||||
{
|
||||
var blocked = starTrails && d == PlaybackDirection.Boomerang;
|
||||
return new GatedChoice(d, ExportSummaries.DirectionLabel(d), !blocked, Loc.L(blocked ? "Tooltips.Export.BoomerangStack" : "Tooltips.Export.Direction"));
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))];
|
||||
/// <summary>"Auto · 1 s".</summary>
|
||||
private static string Auto(string value) => Loc.L("Export.Auto") + Loc.Separator + value;
|
||||
|
||||
/// <summary>The card of the export preset the plan renders.</summary>
|
||||
private void SelectCards()
|
||||
private void LoadTable()
|
||||
{
|
||||
foreach (var card in Cards)
|
||||
card.IsSelected = card.Choice.Sequence is null && string.Equals(card.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||||
Presets = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetRow(this, c))];
|
||||
PresetGroups = PresetTable.Build(Presets, Resolved.PresetId);
|
||||
}
|
||||
|
||||
/// <summary>The row of the export preset the plan renders.</summary>
|
||||
private void SelectRows()
|
||||
{
|
||||
foreach (var row in Presets)
|
||||
row.IsSelected = row.Choice.Sequence is null && string.Equals(row.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the plan changed or cannot do, localised; for a server sequence without this PC's encoder notices (the server
|
||||
/// or its render node picks the encoder).
|
||||
/// or its render node picks the encoder). The output program's remarks (fades shortened, a direction not known) follow.
|
||||
/// </summary>
|
||||
private IReadOnlyList<string> PlanNotices(ExportPlan plan)
|
||||
{
|
||||
var encoder = Editor.IsRemote ? plan.Setup.Encoder.Notices.Select(n => n.Key).ToHashSet(StringComparer.Ordinal) : [];
|
||||
return [.. plan.Setup.Warnings.Where(w => !encoder.Contains(w.Key)).Select(w => Loc.L(w.Key, [.. w.Args]))
|
||||
.Concat(plan.Export.Warnings.Select(k => Loc.L(k))).Distinct()];
|
||||
.Concat(plan.Export.Warnings.Select(k => Loc.L(k)))
|
||||
.Concat(plan.Program?.Warnings.Select(w => Loc.L(w.Key, [.. w.Args])) ?? []).Distinct()];
|
||||
}
|
||||
|
||||
/// <summary>Estimates every card off the UI thread for the project as it is now (latest request wins).</summary>
|
||||
private async Task EstimateCardsAsync()
|
||||
/// <summary>Estimates every preset off the UI thread for the project as it is now (latest request wins).</summary>
|
||||
private async Task EstimateRowsAsync()
|
||||
{
|
||||
var project = Editor.Session.Project;
|
||||
var cards = Cards;
|
||||
var plans = new ExportPlan?[cards.Count];
|
||||
var rows = Presets;
|
||||
var plans = new ExportPlan?[rows.Count];
|
||||
var done = false;
|
||||
try
|
||||
{
|
||||
await _estimates.Schedule(token =>
|
||||
{
|
||||
for (var i = 0; i < cards.Count; i++)
|
||||
for (var i = 0; i < rows.Count; i++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var export = project.Export with { Preset = project.Export.Preset.WithManual(cards[i].Choice.ExportPresetId), Overrides = new ExportOverrides(), Batch = [] };
|
||||
// The playback stays: a preset renders with the loops and holds of the export (batch presets inherit it).
|
||||
var export = project.Export with { Preset = project.Export.Preset.WithManual(rows[i].Choice.ExportPresetId), Overrides = new ExportOverrides(), Batch = [] };
|
||||
plans[i] = Editor.Planner.Plan(project, export);
|
||||
}
|
||||
done = true;
|
||||
@@ -655,12 +935,12 @@ public sealed class ExportTab : EditorTab
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("editor", "Preset estimates failed", ex);
|
||||
Log.Warning("editor", "Preset estimates failed", ex);
|
||||
return;
|
||||
}
|
||||
// A superseded request stops part way (or never starts); undo can bring back the same project instance.
|
||||
if (!done || !ReferenceEquals(cards, Cards) || !ReferenceEquals(project, Editor.Session.Project)) return;
|
||||
for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]);
|
||||
if (!done || !ReferenceEquals(rows, Presets) || !ReferenceEquals(project, Editor.Session.Project)) return;
|
||||
for (var i = 0; i < rows.Count; i++) rows[i].Update(plans[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -697,18 +977,14 @@ public sealed class ExportTab : EditorTab
|
||||
});
|
||||
}
|
||||
|
||||
private void OpenHistory()
|
||||
{
|
||||
Editor.Shell.Jobs.Filter = Jobs.JobFilter.All;
|
||||
Editor.Shell.Jobs.SearchText = Editor.Title;
|
||||
Editor.Shell.Navigate(Shell.SectionKey.Jobs);
|
||||
}
|
||||
private void OpenVideos() => Editor.Shell.OpenVideos(Editor.Session.Content.Sequence.Id, Editor.Title);
|
||||
|
||||
private void Select(PresetCard? card)
|
||||
private void Select(PresetRow? row)
|
||||
{
|
||||
if (card is null) return;
|
||||
if (card.Choice.Sequence is { } preset) Editor.Session.ApplyPreset(preset);
|
||||
else EditExport(e => e with { Preset = e.Preset.WithManual(card.Choice.ExportPresetId), Overrides = new ExportOverrides() });
|
||||
if (row is null) return;
|
||||
_customResolution = false;
|
||||
if (row.Choice.Sequence is { } preset) Editor.Session.ApplyPreset(preset);
|
||||
else EditExport(e => e with { Preset = e.Preset.WithManual(row.Choice.ExportPresetId), Overrides = new ExportOverrides() });
|
||||
}
|
||||
|
||||
private void SelectCodec(CodecChoice choice) => EditOverrides(o => o with
|
||||
@@ -720,6 +996,17 @@ public sealed class ExportTab : EditorTab
|
||||
Encoder = null,
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Sets the frame rate (null: the preset's). A keyframe interval chosen by hand is kept in seconds (decision 6), so
|
||||
/// its frames follow the new rate.
|
||||
/// </summary>
|
||||
private void SetFrameRate(string? rate)
|
||||
{
|
||||
var from = Resolved.FrameRate;
|
||||
var to = rate is not null && FrameRateText.TryParse(rate, out var parsed) ? parsed : PresetValues.FrameRate;
|
||||
EditOverrides(o => o with { FrameRate = rate, GopFrames = o.GopFrames is { } gop ? ExportRules.RescaleGop(gop, from, to) : null });
|
||||
}
|
||||
|
||||
private IReadOnlyList<Choice> EncoderChoices(VideoCodec codec)
|
||||
{
|
||||
var names = Editor.Planner.Encoders.SelectMany(p => p.Capabilities).Where(c => c.Codec == codec).Select(c => c.Name).Distinct();
|
||||
@@ -732,6 +1019,41 @@ public sealed class ExportTab : EditorTab
|
||||
private void EditOverrides(Func<ExportOverrides, ExportOverrides> change, string? mergeKey = null) =>
|
||||
EditExport(e => e with { Overrides = change(e.Overrides) }, mergeKey);
|
||||
|
||||
/// <summary>
|
||||
/// Changes the playback; at its default (forward, once, no fades or hold) the export holds none, so an ordinary project
|
||||
/// keeps its settings format (decision 8).
|
||||
/// </summary>
|
||||
private void EditPlayback(Func<PlaybackSettings, PlaybackSettings> change, string? mergeKey = null) =>
|
||||
EditExport(e => e with { Playback = change(e.Playback ?? new PlaybackSettings()) is var p && p.IsDefault ? null : p.Normalized() }, mergeKey);
|
||||
|
||||
/// <summary>A slider of seconds: snapped to 0.5 s; a value the field set above the slider's end stays until the slider moves.</summary>
|
||||
private void SetSeconds(double value, double current, Func<PlaybackSettings, double?, PlaybackSettings> set, string mergeKey)
|
||||
{
|
||||
var seconds = double.Round(double.Clamp(value, 0, SliderSeconds) * 2) / 2;
|
||||
if (_refreshing || seconds == double.Min(current, SliderSeconds)) return;
|
||||
EditPlayback(p => set(p, seconds), mergeKey);
|
||||
}
|
||||
|
||||
private EditableField SecondsField(double maximum, Func<PlaybackSettings, double?, PlaybackSettings> set, string toolTipKey) =>
|
||||
new(SecondsText(0), text => ParseSeconds(text, maximum) is null ? Loc.L("Errors.Number.DecimalRange", 0.ToString("0.##", Loc.Culture), maximum.ToString("0.##", Loc.Culture)) : null,
|
||||
text => EditPlayback(p => set(p, ParseSeconds(text, maximum))), () => Loc.L(toolTipKey));
|
||||
|
||||
/// <summary>"1.5" in the UI language.</summary>
|
||||
private static string SecondsText(double seconds) => seconds.ToString("0.##", Loc.Culture);
|
||||
|
||||
/// <summary>Seconds 0..<paramref name="maximum"/> in the UI language (or with a point); null when the text is not one.</summary>
|
||||
private static double? ParseSeconds(string text, double maximum)
|
||||
{
|
||||
var trimmed = text.Trim();
|
||||
if (trimmed.Length == 0) return 0;
|
||||
return (double.TryParse(trimmed, NumberStyles.Float, Loc.Culture, out var v) || double.TryParse(trimmed, NumberStyles.Float, CultureInfo.InvariantCulture, out v))
|
||||
&& double.IsFinite(v) && v >= 0 && v <= maximum
|
||||
? v
|
||||
: null;
|
||||
}
|
||||
|
||||
private static bool IsBaseline(string? profile) => string.Equals(profile, nameof(CodecProfile.H264Baseline), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string? ValidateSize(string text) =>
|
||||
text.Length == 0 || (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) && v is >= 16 and <= 16384)
|
||||
? null
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A 28 px row of the Export step's preset table (owner review 1, R3; decision 3): the batch tick, the name with the
|
||||
/// Recommended chip, and the details as columns (size, codec, fps, estimated size and time). Clicking the row selects the
|
||||
/// preset; the tick adds it to the batch.
|
||||
/// </summary>
|
||||
public sealed class PresetRow : ObservableObject
|
||||
{
|
||||
private readonly ExportTab _owner;
|
||||
private string _size;
|
||||
private string _codec;
|
||||
private string _fps;
|
||||
private string? _estimatedSize;
|
||||
private string? _estimatedTime;
|
||||
private bool _isSelected;
|
||||
|
||||
public PresetRow(ExportTab owner, ExportChoice choice)
|
||||
{
|
||||
_owner = owner;
|
||||
Choice = choice;
|
||||
var preset = ExportPresets.Find(choice.ExportPresetId);
|
||||
_size = preset is { Width: > 0, Height: > 0 } ? EditorText.Size(preset.Width, preset.Height) : Loc.L("Export.Resolution.Source");
|
||||
_codec = preset is null ? string.Empty : EditorText.CodecName(preset.Codec, preset.Profile, preset.BitDepth);
|
||||
_fps = preset is null ? string.Empty : EditorText.FrameRate(preset.FrameRate);
|
||||
}
|
||||
|
||||
public ExportChoice Choice { get; }
|
||||
|
||||
public string Name => Choice.Name;
|
||||
|
||||
public bool IsRecommended => Choice.IsRecommended;
|
||||
|
||||
/// <summary>Sequence presets apply full settings; export presets only choose the output.</summary>
|
||||
public bool IsSequencePreset => Choice.Sequence is not null;
|
||||
|
||||
/// <summary>The preset group of the table (<see cref="ExportPreset.Group"/>): a sequence preset's is its export preset's.</summary>
|
||||
public string Group => ExportPresets.Find(Choice.ExportPresetId)?.Group ?? PresetTable.DefaultGroup;
|
||||
|
||||
/// <summary>What choosing the row does, or why it cannot be chosen now (a job runs, the project cannot change).</summary>
|
||||
public string ToolTip => _owner.Editor.LockedToolTip ?? (Choice.Reason is { } reason
|
||||
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
|
||||
: Loc.L("Tooltips.Export.PresetRow", Name));
|
||||
|
||||
public string BatchToolTip => _owner.Editor.LockedToolTip ?? Loc.L("Tooltips.Export.PresetBatch", Name);
|
||||
|
||||
/// <summary>"3840×2160" as rendered (the chosen proportions fitted in the preset's box), "Source" for image sequences.</summary>
|
||||
public string Size { get => _size; private set => Set(ref _size, value); }
|
||||
|
||||
/// <summary>"HEVC Main10".</summary>
|
||||
public string Codec { get => _codec; private set => Set(ref _codec, value); }
|
||||
|
||||
/// <summary>"24".</summary>
|
||||
public string Fps { get => _fps; private set => Set(ref _fps, value); }
|
||||
|
||||
/// <summary>"2.2 GB", or "No encoder here"; null until estimated.</summary>
|
||||
public string? EstimatedSize { get => _estimatedSize; private set => Set(ref _estimatedSize, value); }
|
||||
|
||||
/// <summary>"about 5 min"; null until estimated or without an encoder here.</summary>
|
||||
public string? EstimatedTime { get => _estimatedTime; private set => Set(ref _estimatedTime, value); }
|
||||
|
||||
public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); }
|
||||
|
||||
/// <summary>Ticked for the batch (export presets only).</summary>
|
||||
public bool IsInBatch
|
||||
{
|
||||
get => _owner.IsInBatch(Choice.ExportPresetId);
|
||||
set => _owner.SetInBatch(Choice.ExportPresetId, value);
|
||||
}
|
||||
|
||||
public bool CanBatch => !IsSequencePreset;
|
||||
|
||||
public ICommand SelectCommand => _owner.SelectCommand;
|
||||
|
||||
/// <remarks>A server sequence renders on the server: this PC's encoders do not rule out the estimate.</remarks>
|
||||
public void Update(ExportPlan? plan)
|
||||
{
|
||||
if (plan is null)
|
||||
{
|
||||
EstimatedSize = EstimatedTime = null;
|
||||
return;
|
||||
}
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
if (settings.Width > 0 && settings.Height > 0) Size = EditorText.Size(settings.Width, settings.Height);
|
||||
Codec = EditorText.CodecName(plan.Export.Codec, plan.Export.Profile, plan.Export.BitDepth);
|
||||
Fps = EditorText.FrameRate(plan.Export.FrameRate);
|
||||
if (_owner.Editor.IsRemote || plan.Setup.Encoder.IsReady)
|
||||
{
|
||||
EstimatedSize = Formatting.Bytes(plan.Estimate.Bytes);
|
||||
EstimatedTime = Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time));
|
||||
}
|
||||
else
|
||||
{
|
||||
EstimatedSize = Loc.L("Editor.Export.Unavailable");
|
||||
EstimatedTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
|
||||
|
||||
/// <summary>A job of the sequence started or ended, or the project became read-only: the tooltips say why the row waits.</summary>
|
||||
public void RefreshLocked()
|
||||
{
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A group of the preset table ("Social (3)"): a header that opens or closes it, then its rows.</summary>
|
||||
public sealed class PresetGroup : ObservableObject
|
||||
{
|
||||
private readonly bool _expandedByDefault;
|
||||
|
||||
public PresetGroup(string key, IReadOnlyList<PresetRow> rows, bool expandedByDefault)
|
||||
{
|
||||
Key = key;
|
||||
Rows = rows;
|
||||
_expandedByDefault = expandedByDefault;
|
||||
ToggleCommand = new RelayCommand(() => IsExpanded = !IsExpanded);
|
||||
}
|
||||
|
||||
/// <summary>The <see cref="ExportPreset.Group"/> ("social").</summary>
|
||||
public string Key { get; }
|
||||
|
||||
public IReadOnlyList<PresetRow> Rows { get; }
|
||||
|
||||
/// <summary>"Social".</summary>
|
||||
public string Name => PresetTable.GroupName(Key);
|
||||
|
||||
/// <summary>"Social (3)".</summary>
|
||||
public string Header => Loc.L("Export.Preset.GroupCount", Name, Rows.Count.ToString("N0", Loc.Culture));
|
||||
|
||||
public string ToolTip => Loc.L("Tooltips.Export.PresetGroup", Name);
|
||||
|
||||
/// <summary>Kept per group by the app (<see cref="EditorSettings.Groups"/>); by default open when it holds the preset in use or the recommended one.</summary>
|
||||
public bool IsExpanded
|
||||
{
|
||||
get => EditorSettings.Groups.IsExpanded(PresetTable.StateKey(Key), _expandedByDefault);
|
||||
set
|
||||
{
|
||||
if (value == IsExpanded) return;
|
||||
EditorSettings.Groups.Set(PresetTable.StateKey(Key), value);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand ToggleCommand { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Export step's preset table (owner review 1, R3; decision 3): the presets grouped by <see cref="ExportPreset.Group"/>
|
||||
/// (Video, Social, Intermediate, Image sequence, Web) in the order the built-in list first names each group, a sequence
|
||||
/// preset first in the group of its export preset.
|
||||
/// </summary>
|
||||
public static class PresetTable
|
||||
{
|
||||
/// <summary>The group of a preset that names none.</summary>
|
||||
public const string DefaultGroup = "video";
|
||||
|
||||
/// <summary>The key of a group's open state in <see cref="EditorSettings.Groups"/>.</summary>
|
||||
public static string StateKey(string group) => "preset." + group;
|
||||
|
||||
/// <summary>"Image sequence" for "sequence".</summary>
|
||||
public static string GroupName(string group) => Loc.L("Export.Preset.Group." + group switch
|
||||
{
|
||||
"social" => "Social",
|
||||
"intermediate" => "Intermediate",
|
||||
"sequence" => "Sequence",
|
||||
"web" => "Web",
|
||||
_ => "Video",
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The groups of <paramref name="rows"/>, in the order of <see cref="ExportPresets.BuiltIn"/> (a group it does not name
|
||||
/// comes last), each row in the order given. A group with the preset in use (<paramref name="selectedPresetId"/>) or the
|
||||
/// recommended preset opens by default, the first group when none has either.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<PresetGroup> Build(IReadOnlyList<PresetRow> rows, string? selectedPresetId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var order = ExportPresets.BuiltIn.Select(p => p.Group).Distinct(StringComparer.Ordinal).ToList();
|
||||
var groups = rows.GroupBy(r => r.Group, StringComparer.Ordinal)
|
||||
.OrderBy(g => order.IndexOf(g.Key) is var i and >= 0 ? i : int.MaxValue)
|
||||
.Select(g => (g.Key, Rows: g.ToList()))
|
||||
.ToList();
|
||||
var open = groups.Select(g => g.Rows.Any(r => r.IsRecommended
|
||||
|| (!r.IsSequencePreset && string.Equals(r.Choice.ExportPresetId, selectedPresetId, StringComparison.OrdinalIgnoreCase)))).ToList();
|
||||
if (open.Count > 0 && !open.Contains(true)) open[0] = true;
|
||||
return [.. groups.Select((g, i) => new PresetGroup(g.Key, g.Rows, open[i]))];
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,8 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
Bytes = r.Bytes,
|
||||
Created = r.Created,
|
||||
ProducedBy = r.ProducedBy,
|
||||
Sha256 = r.Sha256,
|
||||
Kind = r.Kind,
|
||||
}).ToList();
|
||||
var (deep, otherFrames) = Report(report, frames.Count);
|
||||
return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// What the editor's Render ▾ menu is made from (owner review 1, R3, decision 2): the presets to put first, the commands
|
||||
/// of its lower part and why Save frame waits, when it does.
|
||||
/// </summary>
|
||||
public sealed record RenderMenuState
|
||||
{
|
||||
/// <summary>The preset the export renders (checked); null for values that match no preset ("Custom").</summary>
|
||||
public string? CurrentPresetId { get; init; }
|
||||
|
||||
/// <summary>The preset the export starts from (Custom included): listed at the top when no section below lists it.</summary>
|
||||
public string? BasePresetId { get; init; }
|
||||
|
||||
/// <summary>The advisor's pick for this sequence; null when it has none.</summary>
|
||||
public string? RecommendedPresetId { get; init; }
|
||||
|
||||
/// <summary>The export's batch presets besides its own (<see cref="RenderMenu.BatchPresets"/>).</summary>
|
||||
public IReadOnlyList<string> Batch { get; init; } = [];
|
||||
|
||||
/// <summary>Presets the sequence was rendered with, newest first (<see cref="RenderMenu.RecentPresets"/>).</summary>
|
||||
public IReadOnlyList<string> Recent { get; init; } = [];
|
||||
|
||||
/// <summary>The details line of a preset: "3840×2160 · HEVC Main10 · 24 fps" (<see cref="RenderMenu.PresetDetails"/>).</summary>
|
||||
public Func<ExportPreset, string> Details { get; init; } = _ => string.Empty;
|
||||
|
||||
/// <summary>Chooses a preset; its parameter is the preset id.</summary>
|
||||
public ICommand? SelectPreset { get; init; }
|
||||
|
||||
public ICommand? RenderBatch { get; init; }
|
||||
|
||||
/// <summary>Why Render batch waits; null shows what it does.</summary>
|
||||
public string? RenderBatchToolTip { get; init; }
|
||||
|
||||
public ICommand? AddToQueue { get; init; }
|
||||
|
||||
/// <summary>Why Add to queue waits; null shows what it does.</summary>
|
||||
public string? AddToQueueToolTip { get; init; }
|
||||
|
||||
/// <summary>Saves the frame under the cursor; its parameter is one of <see cref="RenderRules.StillCodecs"/>.</summary>
|
||||
public ICommand? SaveFrame { get; init; }
|
||||
|
||||
/// <summary>Why no frame can be saved now (<see cref="RenderMenu.SaveFrameBlockedReason"/>); null when one can.</summary>
|
||||
public string? SaveFrameBlocked { get; init; }
|
||||
|
||||
/// <summary>Opens the videos of this sequence.</summary>
|
||||
public ICommand? ShowVideos { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The editor's Render ▾ menu (owner review 1, R3, decisions 1 and 2): short and structured instead of every preset in a
|
||||
/// row. In order: the current preset when no section lists it, the advisor's pick, the batch presets, up to three presets
|
||||
/// this sequence was rendered with, "Other presets ›" grouped as the Export step groups them; then Render batch (n), Add to
|
||||
/// queue, Save frame › (PNG, JPEG, TIFF 16-bit) and the videos of the sequence. Each preset reads as two lines, its name
|
||||
/// and a muted "size · codec · fps"; estimates stay out of the menu (they cost a plan per preset) and live in the Render
|
||||
/// button's tooltip (<see cref="RenderToolTip"/>). Every entry has a tooltip; a disabled one says why.
|
||||
/// </summary>
|
||||
public static class RenderMenu
|
||||
{
|
||||
/// <summary>The presets of the render history the menu puts first, at most.</summary>
|
||||
public const int RecentCount = 3;
|
||||
|
||||
/// <summary>The preset groups in the order the menu and the Export step list them; another group follows them.</summary>
|
||||
public static IReadOnlyList<string> GroupOrder { get; } = ["video", "social", "intermediate", "sequence", "web"];
|
||||
|
||||
/// <summary>The menu for <paramref name="state"/>.</summary>
|
||||
public static IReadOnlyList<RenderMenuItem> Build(RenderMenuState state)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
var shown = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var recommended = Find(state.RecommendedPresetId);
|
||||
var batch = state.Batch.Select(Find).OfType<ExportPreset>().Where(p => !Same(p, recommended)).DistinctBy(p => p.Id).ToList();
|
||||
var recent = state.Recent.Select(Find).OfType<ExportPreset>().Where(p => !Same(p, recommended) && !batch.Contains(p)).DistinctBy(p => p.Id)
|
||||
.Take(RecentCount).ToList();
|
||||
var items = new List<RenderMenuItem>();
|
||||
|
||||
if (Find(state.BasePresetId) is { } current && !Same(current, recommended) && !batch.Contains(current) && !recent.Contains(current))
|
||||
items.Add(Preset(current, null));
|
||||
if (recommended is not null)
|
||||
{
|
||||
items.Add(RenderMenuItem.Header(Loc.L("Editor.RenderMenu.Recommended")));
|
||||
items.Add(Preset(recommended, Loc.L("Tooltips.Editor.RenderMenu.Recommended")));
|
||||
}
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
// The count is the batch's (as Render batch says), a preset listed above among them.
|
||||
items.Add(RenderMenuItem.Header(Loc.L("Export.Footer.Batch", state.Batch.Count)));
|
||||
items.AddRange(batch.Select(p => Preset(p, null)));
|
||||
}
|
||||
if (recent.Count > 0)
|
||||
{
|
||||
items.Add(RenderMenuItem.Header(Loc.L("Editor.RenderMenu.Recent")));
|
||||
items.AddRange(recent.Select(p => Preset(p, Loc.L("Tooltips.Editor.RenderMenu.Recent"))));
|
||||
}
|
||||
|
||||
var others = new List<RenderMenuItem>();
|
||||
foreach (var group in ExportPresets.BuiltIn.Where(p => !shown.Contains(p.Id)).GroupBy(p => p.Group, StringComparer.OrdinalIgnoreCase).OrderBy(g => GroupRank(g.Key)))
|
||||
{
|
||||
others.Add(RenderMenuItem.Header(GroupLabel(group.Key)));
|
||||
others.AddRange(group.Select(p => Preset(p, null)));
|
||||
}
|
||||
if (others.Count > 0)
|
||||
{
|
||||
items.Add(new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Submenu,
|
||||
Id = "other",
|
||||
Label = Loc.L("Editor.RenderMenu.Other"),
|
||||
ToolTip = Loc.L("Tooltips.Editor.RenderMenu.Other"),
|
||||
Children = others,
|
||||
});
|
||||
}
|
||||
|
||||
items.Add(RenderMenuItem.Separator);
|
||||
items.Add(new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Command,
|
||||
Id = "batch",
|
||||
Label = Loc.L("Editor.RenderMenu.Batch", state.Batch.Count),
|
||||
Command = state.RenderBatch,
|
||||
ToolTip = state.RenderBatchToolTip ?? Loc.L(state.Batch.Count == 0 ? "Tooltips.Editor.RenderMenu.BatchEmpty" : "Tooltips.Editor.RenderMenu.Batch"),
|
||||
});
|
||||
items.Add(new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Command,
|
||||
Id = "queue",
|
||||
Label = Loc.L("Editor.Export.AddToQueue"),
|
||||
Command = state.AddToQueue,
|
||||
ToolTip = state.AddToQueueToolTip ?? Loc.L("Tooltips.Editor.RenderMenu.AddToQueue"),
|
||||
});
|
||||
items.Add(new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Submenu,
|
||||
Id = "frame",
|
||||
Label = Loc.L("Editor.RenderMenu.SaveFrame"),
|
||||
IsEnabled = state.SaveFrameBlocked is null,
|
||||
ToolTip = state.SaveFrameBlocked ?? Loc.L("Tooltips.Editor.RenderMenu.SaveFrame"),
|
||||
Children = [.. RenderRules.StillCodecs.Select(codec => new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Command,
|
||||
Id = "frame:" + Data.Processing.ProcessingJobs.CodecName(codec),
|
||||
Label = StillFormatName(codec),
|
||||
Command = state.SaveFrame,
|
||||
CommandParameter = codec,
|
||||
IsEnabled = state.SaveFrameBlocked is null,
|
||||
ToolTip = state.SaveFrameBlocked ?? Loc.L("Tooltips.Editor.RenderMenu.SaveFormat", StillFormatName(codec)),
|
||||
})],
|
||||
});
|
||||
items.Add(new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Command,
|
||||
Id = "videos",
|
||||
Label = Loc.L("Editor.RenderMenu.Videos"),
|
||||
Command = state.ShowVideos,
|
||||
ToolTip = Loc.L("Tooltips.Editor.RenderMenu.Videos"),
|
||||
});
|
||||
return items;
|
||||
|
||||
RenderMenuItem Preset(ExportPreset preset, string? why)
|
||||
{
|
||||
shown.Add(preset.Id);
|
||||
var name = Loc.L(preset.NameKey);
|
||||
var details = state.Details(preset);
|
||||
var tip = Loc.L("Tooltips.Editor.RenderMenu.Preset", name, details);
|
||||
return new RenderMenuItem
|
||||
{
|
||||
Kind = RenderMenuItemKind.Preset,
|
||||
Id = "preset:" + preset.Id,
|
||||
Label = name,
|
||||
Details = details.Length > 0 ? details : null,
|
||||
IsChecked = string.Equals(preset.Id, state.CurrentPresetId, StringComparison.OrdinalIgnoreCase),
|
||||
Command = state.SelectPreset,
|
||||
CommandParameter = preset.Id,
|
||||
ToolTip = why is null ? tip : tip + Loc.Separator + why,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Video", "Social"…: the name of a preset group.</summary>
|
||||
public static string GroupLabel(string group)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(group);
|
||||
return Loc.L("Export.Preset.Group." + char.ToUpperInvariant(group[0]) + group[1..].ToLowerInvariant());
|
||||
}
|
||||
|
||||
/// <summary>"PNG", "JPEG", "TIFF 16-bit": a Save frame format.</summary>
|
||||
public static string StillFormatName(VideoCodec codec) => Loc.L("Export.Codec." + codec);
|
||||
|
||||
/// <summary>
|
||||
/// "3840×2160 · HEVC Main10 · 24 fps": the size <paramref name="presetId"/> renders this sequence at (the preset's box
|
||||
/// fitted to the chosen proportions, as the render does), its codec and its frame rate, with the export's own values
|
||||
/// for the rest (as choosing it in the menu makes it); the preset's own size without a source size.
|
||||
/// </summary>
|
||||
public static string PresetDetails(ExportSettings export, string presetId, CameraSettings camera, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
ArgumentNullException.ThrowIfNull(camera);
|
||||
var resolved = ExportResolver.Resolve(export with { Preset = export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] });
|
||||
var (width, height) = sourceWidth > 0 && sourceHeight > 0 ? RenderSize.Of(camera, resolved, sourceWidth, sourceHeight) : (resolved.Width, resolved.Height);
|
||||
var size = width > 0 && height > 0 ? EditorText.Size(width, height) : Loc.L("Export.Resolution.Source");
|
||||
return Loc.L("Editor.RenderMenu.Details", size, EditorText.CodecName(resolved.Codec, resolved.Profile, resolved.BitDepth),
|
||||
Loc.L("Editor.Value.Fps", EditorText.FrameRate(resolved.FrameRate)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Render button's tooltip (decision 1): why it waits, when it does, then what it renders, "Render 4K HEVC ·
|
||||
/// 3840×2160 · HEVC Main10 · 24 fps · ~1.2 GB · ~4 min · Ctrl+R" (the size the encoder makes); for a server sequence,
|
||||
/// where it renders.
|
||||
/// </summary>
|
||||
public static string RenderToolTip(ExportPlan? plan, string? blocked, string? server)
|
||||
{
|
||||
var lines = new List<string>(3);
|
||||
if (blocked is { Length: > 0 }) lines.Add(blocked);
|
||||
if (plan is not null)
|
||||
{
|
||||
var (width, height) = plan.EncodedSize;
|
||||
lines.Add(Loc.L("Tooltips.Editor.RenderDetails", plan.PresetName, width > 0 && height > 0 ? EditorText.Size(width, height) : Loc.L("Export.Resolution.Source"),
|
||||
EditorText.CodecName(plan.Export.Codec, plan.Export.Profile, plan.Export.BitDepth), Loc.L("Editor.Value.Fps", EditorText.FrameRate(plan.Setup.Plan.FrameRate)),
|
||||
Formatting.Bytes(plan.Estimate.Bytes), Formatting.Duration(plan.Estimate.Time)));
|
||||
}
|
||||
if (blocked is null && server is not null) lines.Add(Loc.L("Tooltips.Editor.RenderServer", server));
|
||||
if (lines.Count == 0) lines.Add(Loc.L("Tooltips.Editor.Render"));
|
||||
return string.Join(Environment.NewLine, lines);
|
||||
}
|
||||
|
||||
/// <summary>The batch presets of an export besides its own, each once, in the order ticked (blank entries skipped).</summary>
|
||||
public static IReadOnlyList<string> BatchPresets(ExportSettings export)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
var own = ExportResolver.Resolve(export).BasePresetId;
|
||||
return [.. export.Batch.Where(id => !string.IsNullOrWhiteSpace(id) && !id.Equals(own, StringComparison.OrdinalIgnoreCase)).Distinct(StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The presets <paramref name="renders"/> (newest first, as <see cref="SequenceContent.Renders"/>) were made with, newest
|
||||
/// first and each once, at most <paramref name="count"/>; saved frames do not count.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> RecentPresets(IReadOnlyList<Render> renders, int count = RecentCount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renders);
|
||||
return [.. renders.Where(r => RenderKind.Of(r) != RenderKind.Still).Select(PresetOf).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase).Take(count)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The built-in preset a render was made with: from the settings it recorded, else from its preset name in the language
|
||||
/// of the moment; null when neither tells (a custom export, settings no longer readable).
|
||||
/// </summary>
|
||||
public static string? PresetOf(Render render)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(render);
|
||||
if (render.SettingsJson is { Length: > 0 } json)
|
||||
{
|
||||
try
|
||||
{
|
||||
var resolved = ExportResolver.Resolve(ProjectSettings.FromJson(json, allowNewer: true).Export);
|
||||
if (!resolved.IsCustom && Find(resolved.BasePresetId) is { } preset) return preset.Id;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException or ArgumentException)
|
||||
{
|
||||
// Settings no longer readable say nothing: the name may still tell.
|
||||
}
|
||||
}
|
||||
return ExportPresets.BuiltIn.FirstOrDefault(p => string.Equals(Loc.L(p.NameKey), render.PresetName, StringComparison.OrdinalIgnoreCase))?.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why Save frame waits (decision 12), in this order: the frames changed on the server, the project is shown read-only,
|
||||
/// there is no frame to save under the cursor (none, or one the render leaves out), the source cannot save frames, the
|
||||
/// server cannot (<paramref name="serverReason"/>: no right, or an older Chronos), the file name is wrong; null when a
|
||||
/// frame can be saved.
|
||||
/// </summary>
|
||||
public static string? SaveFrameBlockedReason(bool outdated, string? server, bool readOnly, bool hasFrame, bool sourceSavesFrames, string? serverReason,
|
||||
string? nameError)
|
||||
{
|
||||
if (outdated) return Loc.L("Tooltips.Editor.Outdated", server);
|
||||
if (readOnly) return Loc.L("Tooltips.Export.StillReadOnly");
|
||||
if (!hasFrame) return Loc.L("Tooltips.Export.StillNeedsFrame");
|
||||
if (!sourceSavesFrames) return Loc.L("Tooltips.Export.StillWorkspace");
|
||||
if (serverReason is not null) return serverReason;
|
||||
return nameError is null ? null : Loc.L("Tooltips.Editor.Render.NameError", nameError);
|
||||
}
|
||||
|
||||
private static ExportPreset? Find(string? id) => id is { Length: > 0 } ? ExportPresets.Find(id) : null;
|
||||
|
||||
private static bool Same(ExportPreset preset, ExportPreset? other) => other is not null && preset.Id.Equals(other.Id, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static int GroupRank(string group)
|
||||
{
|
||||
for (var i = 0; i < GroupOrder.Count; i++)
|
||||
{
|
||||
if (GroupOrder[i].Equals(group, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
}
|
||||
return GroupOrder.Count;
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@ using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
@@ -63,6 +66,24 @@ internal sealed class ServerJobs : IAsyncDisposable
|
||||
/// </summary>
|
||||
public static string? NeedsNewerServer(int required, int serverFormat) => required > serverFormat ? Loc.L("Tooltips.Server.NeedsNewerServer") : null;
|
||||
|
||||
/// <summary>
|
||||
/// Why a render of <paramref name="export"/> with <paramref name="settings"/> cannot go to a server that reads
|
||||
/// <paramref name="serverFormat"/> (owner review 1, phase 5: playback needs format 3); null when it can. The format is the
|
||||
/// one of the job's own export, its playback included, never the project's export alone (<see cref="ProcessingJobs.RequiredFormat"/>).
|
||||
/// </summary>
|
||||
public static string? RenderNeedsNewerServer(ProjectSettings settings, ExportSettings export, int sourceWidth, int sourceHeight, int serverFormat)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
return NeedsNewerServer(ProcessingJobs.RequiredFormat(settings with { Export = export }, export, sourceWidth, sourceHeight), serverFormat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why "Save frame" cannot go to a server that reads <paramref name="serverFormat"/>: a still job needs
|
||||
/// <see cref="RenderRules.StillFormat"/>, which an older server's nodes would render as a whole video; null when it can.
|
||||
/// </summary>
|
||||
public static string? StillNeedsNewerServer(int serverFormat) => NeedsNewerServer(RenderRules.StillFormat, serverFormat);
|
||||
|
||||
/// <summary>Queues <paramref name="request"/> on the server (its priority set after, when it is not the user's); returns the job id.</summary>
|
||||
/// <exception cref="EditorException">The sequence is gone from the server.</exception>
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using Chronos.App.Shell;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A rail section that lists the videos (owner review 1, R9: the Videos section) and can show only those of one
|
||||
/// sequence: the Export footer's "Videos (n)" and the Render menu open it filtered on the sequence in Edit.
|
||||
/// </summary>
|
||||
public interface IVideosSection
|
||||
{
|
||||
/// <summary>Lists the videos of <paramref name="sequenceId"/> only; null lists every video again.</summary>
|
||||
void ShowSequence(Guid? sequenceId);
|
||||
}
|
||||
|
||||
/// <summary>Opens the Videos section on one sequence's videos, wherever the shell keeps it.</summary>
|
||||
public static class VideosLink
|
||||
{
|
||||
/// <summary>The section of <paramref name="sections"/> that lists the videos; null while the app has none.</summary>
|
||||
public static SectionViewModel? Find(IEnumerable<SectionViewModel> sections)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sections);
|
||||
return sections.FirstOrDefault(s => s is IVideosSection);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters the Videos section on <paramref name="sequenceId"/> and shows it through <paramref name="navigate"/>; false
|
||||
/// (nothing happens) when the app has no Videos section.
|
||||
/// </summary>
|
||||
public static bool Open(IEnumerable<SectionViewModel> sections, Action<SectionKey> navigate, Guid sequenceId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(navigate);
|
||||
if (Find(sections) is not { } section) return false;
|
||||
((IVideosSection)section).ShowSequence(sequenceId);
|
||||
navigate(section.Key);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
@@ -74,7 +75,7 @@ public sealed class WorkspaceServerHome(Func<IRemoteSequenceApi?> connect, Func<
|
||||
/// are read from the server when it can be reached (else the copy the workspace took), and "Update media" is offered when
|
||||
/// the server's frames moved, or it has the proxy of a frame a thumbnail stands in for.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders, IProjectStills
|
||||
{
|
||||
private const int JobsListed = 200;
|
||||
|
||||
@@ -292,6 +293,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
Bytes = r.Bytes,
|
||||
Created = r.Created,
|
||||
ProducedBy = r.ProducedBy,
|
||||
Sha256 = r.Sha256,
|
||||
Kind = r.Kind,
|
||||
}).ToList() ?? [];
|
||||
renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
|
||||
var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count);
|
||||
@@ -618,6 +621,35 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Save frame" of a workspace project (owner review 1, R8, decision 12), routed as its renders are: media holding the
|
||||
/// originals save the frame on this PC into the project's <c>exports/</c> (a <see cref="JobKind.WorkspaceRender"/> still,
|
||||
/// recorded in its ledger and sent home after, naming the head version when it holds these settings); media of proxies
|
||||
/// have the home save it from its originals (this PC's archive, or the server). Either way the job carries the project's
|
||||
/// portable settings (positions parked by photo, placed on the frames that render) and the project, the frame by its
|
||||
/// position in the media and by its photo, whose hash wins at a home whose frames are in another order.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> StillRequests(Sequence sequence, ProjectSettings project, ExportSettings export, VideoCodec codec, int frameIndex,
|
||||
string? photoSha256, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
|
||||
var request = ProcessingJobs.Still(sequence, export, codec, frameIndex, photoSha256, sourceWidth, sourceHeight, project with { Export = export });
|
||||
var parameters = JsonSerializer.Deserialize(request.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!
|
||||
with
|
||||
{ SettingsJson = portable, ProjectId = ProjectId, ProjectVersionId = null };
|
||||
if (RendersLocally && Workspace is { } workspace)
|
||||
{
|
||||
var head = HeadVersion(portable);
|
||||
var json = JsonSerializer.Serialize(parameters with { ProjectVersionId = head }, ProtocolJson.Default.RenderJobParameters);
|
||||
var home = workspace.Home;
|
||||
return [WorkspaceJobs.Render(home.SequenceId, request.Label ?? sequence.DisplayTitle, _sync.Store.Root, ProjectId, head, json, home.IsArchive ? null : home.Server)];
|
||||
}
|
||||
return [request with { ParametersJson = JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters) }];
|
||||
}
|
||||
|
||||
/// <summary>The id of the newest version the workspace holds when it holds <paramref name="portable"/> (any line ends); null otherwise.</summary>
|
||||
private Guid? HeadVersion(string portable)
|
||||
{
|
||||
@@ -657,6 +689,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
ProducedBy = Environment.MachineName,
|
||||
ProjectId = e.ProjectId,
|
||||
ProjectVersionId = e.ProjectVersionId,
|
||||
Sha256 = e.Sha256,
|
||||
Kind = e.Kind,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Settings = settings;
|
||||
SaveSettingsAction = saveSettings;
|
||||
Dialogs = dialogs;
|
||||
// The editor's open and closed groups survive a restart (owner review 1, R3).
|
||||
Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings);
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
@@ -495,6 +497,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
},
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
// The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5).
|
||||
Archives.Videos.ProtectedFolders = () => [Workspace.Root];
|
||||
Archives.Videos.Servers = Sync;
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
Sync.Open(database, Archives, archive);
|
||||
var handlers = CreateJobHandlers(this);
|
||||
|
||||
@@ -85,6 +85,12 @@ public sealed class AppSettings
|
||||
public AppTheme Theme { get; set; } = AppTheme.Dark;
|
||||
public bool RailCollapsed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The editor's collapsible groups this user opened or closed, by group key ("export.encoding" → false; owner review 1,
|
||||
/// R3): kept like the rail's state, never in a project (<see cref="Chronos.App.Editor.EditorSettings.Groups"/>).
|
||||
/// </summary>
|
||||
public Dictionary<string, bool> EditorGroups { get; set; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The sequence opened in Edit last; the picker selects it first (owner review 1, R7).</summary>
|
||||
public Guid? LastEditedSequence { get; set; }
|
||||
|
||||
@@ -110,6 +116,12 @@ public sealed class AppSettings
|
||||
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
|
||||
public string FileTemplate { get; set; } = TemplateDefaults.File;
|
||||
|
||||
/// <summary>
|
||||
/// Where Videos › Copy to folder puts copies of renders (owner review 1, R9): Videos\Chronos by default, null or empty
|
||||
/// when unset (Copy then says why it cannot run). Never inside the archive or the workspace.
|
||||
/// </summary>
|
||||
public string? VideosFolder { get; set; } = Videos.VideosFolders.Default();
|
||||
|
||||
/// <summary>Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.</summary>
|
||||
public int ProxyLongEdge { get; set; } = 1920;
|
||||
|
||||
@@ -152,6 +164,9 @@ public sealed class AppSettings
|
||||
public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
|
||||
public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
|
||||
|
||||
/// <summary>The Videos section as cards (<see cref="LibraryLayout.Grid"/>) or as a list (<see cref="LibraryLayout.List"/>).</summary>
|
||||
public LibraryLayout VideosLayout { get; set; } = LibraryLayout.Grid;
|
||||
|
||||
// ---- Rendering ----
|
||||
public QualityProfile Quality { get; set; } = QualityProfile.Balanced;
|
||||
|
||||
@@ -361,6 +376,7 @@ public sealed class AppSettings
|
||||
RecentServers = RecentServers,
|
||||
Window = Window,
|
||||
RailCollapsed = RailCollapsed,
|
||||
EditorGroups = EditorGroups,
|
||||
LastEditedSequence = LastEditedSequence,
|
||||
FirstRunCompleted = FirstRunCompleted,
|
||||
JobsClearedAt = JobsClearedAt,
|
||||
@@ -396,6 +412,7 @@ public sealed class AppSettings
|
||||
imported.ServerUrl = ServerUrl;
|
||||
imported.Window = Window;
|
||||
imported.RailCollapsed = RailCollapsed;
|
||||
imported.EditorGroups = EditorGroups;
|
||||
imported.LastEditedSequence = LastEditedSequence;
|
||||
imported.FirstRunCompleted = FirstRunCompleted;
|
||||
imported.WorkspaceFolder = WorkspaceFolder;
|
||||
|
||||
@@ -41,7 +41,7 @@ public static class JobNotices
|
||||
private static bool Announces(JobKind kind) =>
|
||||
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
|
||||
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
|
||||
or JobKind.WorkspaceMove;
|
||||
or JobKind.WorkspaceMove or JobKind.VideoCopy;
|
||||
|
||||
/// <summary>
|
||||
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
|
||||
|
||||
@@ -121,6 +121,9 @@
|
||||
ToolTip="{Binding Project.SaveVersionToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Sync}" Command="{Binding Project.SyncCommand}" ToolTip="{Binding Project.SyncToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.History}" Command="{Binding Project.HistoryCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.History}" />
|
||||
<!-- Owner review 1, R3: moved here from the Export step's footer. -->
|
||||
<MenuItem Header="{l:Loc Editor.ProjectFile.Save}" Command="{Binding Export.SaveProjectCommand}" ToolTip="{Binding Export.SaveProjectToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<Separator />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
|
||||
@@ -162,8 +165,10 @@
|
||||
<Button Content="{l:Loc Editor.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{Binding AnalyseToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Content="{l:Loc Editor.OptimiseAll}" Command="{Binding OptimiseAllCommand}" ToolTip="{Binding OptimiseAllToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" Margin="12,0,0,0" />
|
||||
<!-- Owner review 1, R3: "Render ▾" whatever the preset, so the header keeps its width; the tooltip gives the details and the
|
||||
menu, made again at every opening, checks the current preset (Recommended, batch, recent, Other presets ›, Save frame ›). -->
|
||||
<v:SplitButton x:Name="RenderButton" IsPrimary="True" Margin="12,0,0,0" Content="{Binding RenderText}" Command="{Binding RenderCommand}"
|
||||
ItemsSource="{Binding RenderChoices}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedRenderChoice}" ToolTip="{Binding RenderToolTip}"
|
||||
ItemsSource="{Binding RenderMenuItems, Mode=OneWay}" ToolTip="{Binding RenderToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" DropDownToolTip="{Binding RenderChoiceToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Editor.RenderButton}" />
|
||||
</StackPanel>
|
||||
|
||||
@@ -192,6 +192,22 @@
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ThumbnailSizes}" SelectedItem="{Binding SelectedThumbnailSize}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ThumbnailSize}" AutomationProperties.Name="{l:Loc Settings.Archive.Thumbnails}" />
|
||||
</HeaderedContentControl>
|
||||
<!-- Where Videos › Copy to folder puts copies of renders (owner review 1, R9). -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.VideosFolder}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Style="{StaticResource TextBox.Path}" Text="{Binding VideosFolder.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding VideosFolder}" ToolTip="{Binding VideosFolder.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Archive.VideosFolder}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.Icon}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding BrowseVideosCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.VideosBrowse}" AutomationProperties.Name="{l:Loc Settings.Archive.VideosBrowse}" />
|
||||
<Button Grid.Column="2" Margin="10,0,0,0" Content="{l:Loc Settings.Archive.VideosOpen}" Command="{Binding OpenVideosFolderCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.VideosOpen}" ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Import: defaults of new cards and folders ================= -->
|
||||
|
||||
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
@@ -79,7 +80,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
|
||||
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
|
||||
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
|
||||
"Settings.Archive.Thumbnails"]),
|
||||
"Settings.Archive.Thumbnails", "Settings.Archive.VideosFolder"]),
|
||||
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
|
||||
"Import.Label.After", "Import.After.Eject"]),
|
||||
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
|
||||
@@ -121,6 +122,12 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
Save();
|
||||
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }), ReorganizeParts.Files);
|
||||
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
|
||||
// Where Videos › Copy to folder puts copies (owner review 1, R9): empty leaves it unset; never inside the archive or the workspace.
|
||||
VideosFolder = new EditableField(_s.VideosFolder ?? string.Empty, ValidateVideosFolder, v =>
|
||||
{
|
||||
_s.VideosFolder = v.Trim().Length == 0 ? null : Path.GetFullPath(v.Trim());
|
||||
Save();
|
||||
}, () => Loc.L("Tooltips.Settings.VideosFolder"));
|
||||
FolderTemplate.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
|
||||
@@ -216,6 +223,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
});
|
||||
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
|
||||
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
|
||||
BrowseVideosCommand = new RelayCommand(() => Browse(VideosFolder, "Settings.Archive.VideosPickTitle"));
|
||||
OpenVideosFolderCommand = new RelayCommand(OpenVideosFolder, () => !string.IsNullOrWhiteSpace(_s.VideosFolder));
|
||||
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
|
||||
ResetParallelismCommand = new RelayCommand(() =>
|
||||
{
|
||||
@@ -400,6 +409,11 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
public EditableField FileTemplate { get; }
|
||||
public ICommand BrowseArchiveCommand { get; }
|
||||
|
||||
/// <summary>Archive › Videos folder: where Videos › Copy to folder puts copies of renders.</summary>
|
||||
public EditableField VideosFolder { get; }
|
||||
public ICommand BrowseVideosCommand { get; }
|
||||
public ICommand OpenVideosFolderCommand { get; }
|
||||
|
||||
/// <summary>"1.8 TB free".</summary>
|
||||
public string? ArchiveFreeText
|
||||
{
|
||||
@@ -1236,7 +1250,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
|
||||
JobKind.WorkspaceMove,
|
||||
JobKind.WorkspaceMove, JobKind.VideoCopy,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
@@ -1259,6 +1273,28 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
? null
|
||||
: Loc.L("Errors.Number.DecimalRange", min.ToString("0.##", Loc.Culture), max.ToString("0.##", Loc.Culture));
|
||||
|
||||
/// <summary>Empty leaves the videos folder unset; a path must be absolute and outside the archive and the workspace.</summary>
|
||||
private string? ValidateVideosFolder(string text) =>
|
||||
text.Trim().Length == 0 ? null
|
||||
: VideosFolders.Problem(text.Trim(), _s.LastArchivePath, Shell.Services.Workspace.Root) is { } problem ? VideoText.FolderReason(problem) : null;
|
||||
|
||||
/// <summary>Opens the videos folder in Explorer, creating it first (it is Chronos's own folder for copies).</summary>
|
||||
private void OpenVideosFolder()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_s.VideosFolder)) return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_s.VideosFolder);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
Log.Warning("settings", $"The videos folder could not be created: {ex.Message}");
|
||||
Shell.Notify(Loc.L("Errors.Videos.FolderCreate", _s.VideosFolder), ErrorText.For(ex), isError: true);
|
||||
return;
|
||||
}
|
||||
ShellActions.Reveal(_s.VideosFolder);
|
||||
}
|
||||
|
||||
private void Browse(EditableField field, string titleKey)
|
||||
{
|
||||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
|
||||
@@ -1620,8 +1656,10 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
_s.FileTemplate = defaults.FileTemplate;
|
||||
_s.ProxyLongEdge = defaults.ProxyLongEdge;
|
||||
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
|
||||
_s.VideosFolder = defaults.VideosFolder;
|
||||
FolderTemplate.Load(_s.FolderTemplate);
|
||||
FileTemplate.Load(_s.FileTemplate);
|
||||
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
|
||||
UpdatePreview();
|
||||
Save();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1682,6 +1720,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
|
||||
FolderTemplate.Load(_s.FolderTemplate);
|
||||
FileTemplate.Load(_s.FileTemplate);
|
||||
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
|
||||
LoadImportFields();
|
||||
LoadAnalysisFields();
|
||||
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
|
||||
@@ -1765,6 +1804,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
ArchiveRoot.Refresh();
|
||||
FolderTemplate.Refresh();
|
||||
FileTemplate.Refresh();
|
||||
VideosFolder.Refresh();
|
||||
SessionGap.Refresh();
|
||||
MinimumFrames.Refresh();
|
||||
// Decimals are written in the language's own way ("6.25", "6,25").
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
<UserControl x:Class="Chronos.App.Sections.VideosView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:vid="clr-namespace:Chronos.App.Videos">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Button.Bar" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Margin" Value="0,0,8,8" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
</Style>
|
||||
<Style x:Key="Button.Quick" TargetType="Button" BasedOn="{StaticResource Button.Icon}">
|
||||
<Setter Property="Width" Value="28" />
|
||||
<Setter Property="Height" Value="28" />
|
||||
<Setter Property="MinWidth" Value="28" />
|
||||
<Setter Property="Margin" Value="6,0,0,0" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
</Style>
|
||||
<Style x:Key="ComboBox.ToolbarFilter" TargetType="ComboBox" BasedOn="{StaticResource ComboBox.Filter}">
|
||||
<Setter Property="Margin" Value="10,4,0,4" />
|
||||
<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>
|
||||
<DataTemplate x:Key="Template.Status" DataType="{x:Type v:CardStatus}">
|
||||
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Text}" ToolTip="{Binding ToolTip}" Margin="0,0,8,0" />
|
||||
</DataTemplate>
|
||||
<!--
|
||||
One render's own menu (the card's and the row's): it acts on the render, or on the selection when the render is part of
|
||||
it. Tag carries the section's view model to the menu, which lives outside the visual tree.
|
||||
-->
|
||||
<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 MenuPlayToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.ShowInFolder}" Command="{Binding PlacementTarget.Tag.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
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="{Binding MenuCopyOnServerToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Videos.OpenInEdit}" Command="{Binding PlacementTarget.Tag.OpenInEditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
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="{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}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.Video}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
|
||||
</Style>
|
||||
<Style x:Key="ListBoxItem.VideoRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Height" Value="38" />
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.Video}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Toolbar: search, kind, codec, year, source, order · cards or list (decision 20). -->
|
||||
<Grid Grid.ColumnSpan="2" Margin="20,0" MinHeight="56">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="260" />
|
||||
<ColumnDefinition Width="3*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox VerticalAlignment="Top" Margin="0,12,0,0" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Videos.Search}" ToolTip="{l:Loc Tooltips.Videos.Search}" AutomationProperties.Name="{l:Loc Videos.Search}" />
|
||||
<WrapPanel Grid.Column="1" VerticalAlignment="Top" Margin="0,8">
|
||||
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Kinds}" SelectedItem="{Binding SelectedKind}" Tag="{Binding IsKindFiltered}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.Kind}" AutomationProperties.Name="{l:Loc Videos.Kind.All}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Codecs}" SelectedItem="{Binding SelectedCodec}" Tag="{Binding IsCodecFiltered}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.Codec}" AutomationProperties.Name="{l:Loc Videos.Codec.All}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Years}" SelectedItem="{Binding SelectedYear}" Tag="{Binding IsYearFiltered}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.Year}" AutomationProperties.Name="{l:Loc Videos.Year.All}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" Tag="{Binding IsSourceFiltered}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.Source}" AutomationProperties.Name="{l:Loc Videos.Source.All}" />
|
||||
<ComboBox Style="{StaticResource ComboBox.ToolbarFilter}" ItemsSource="{Binding Sorts}" SelectedItem="{Binding SelectedSort}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.Sort}" AutomationProperties.Name="{l:Loc Videos.Sort.Newest}" />
|
||||
</WrapPanel>
|
||||
<v:SegmentedControl Grid.Column="2" VerticalAlignment="Top" Margin="10,12,0,0" SelectedIndex="{Binding LayoutIndex, Mode=TwoWay}"
|
||||
AutomationProperties.Name="{l:Loc Videos.View.Grid}">
|
||||
<v:SegmentedItem Glyph="{StaticResource Icon.ViewGrid}" ToolTip="{l:Loc Tooltips.Videos.View}" AutomationProperties.Name="{l:Loc Videos.View.Grid}" />
|
||||
<v:SegmentedItem Glyph="{StaticResource Icon.ViewList}" ToolTip="{l:Loc Tooltips.Videos.View}" AutomationProperties.Name="{l:Loc Videos.View.List}" />
|
||||
</v:SegmentedControl>
|
||||
<Button Grid.Column="3" Style="{StaticResource Button.Quick}" VerticalAlignment="Top" Margin="8,14,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Refresh}"
|
||||
Command="{Binding RefreshCommand}" ToolTip="{l:Loc Tooltips.Videos.Refresh}" AutomationProperties.Name="{l:Loc Videos.Refresh}" />
|
||||
</Grid>
|
||||
|
||||
<!-- The sequence the list is narrowed to (a chip that clears that filter alone), and why the server's videos are not listed. -->
|
||||
<WrapPanel Grid.Row="1" Grid.ColumnSpan="2" Margin="20,0,20,4">
|
||||
<Button Style="{StaticResource Button.Chip}" Content="{Binding SequenceFilterText}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Command="{Binding ClearSequenceCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.ClearSequence}" Visibility="{Binding IsSequenceFiltered, Converter={StaticResource BoolToVisibility}}" Margin="0,0,12,4" />
|
||||
<ui:StatusGlyph Kind="Offline" Text="{Binding ServerStatusText}" ToolTip="{Binding ServerStatusToolTip}" VerticalAlignment="Center" Margin="0,0,12,4"
|
||||
Visibility="{Binding IsServerLimited, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ProgressBar Width="120" Height="4" IsIndeterminate="True" VerticalAlignment="Center" Margin="0,0,12,4"
|
||||
Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
|
||||
<!-- Cards: the sequence's cover (or the still itself), title, preset, details and state chips. -->
|
||||
<ListBox x:Name="CardGrid" Grid.Row="2" Style="{StaticResource ListBox.Cards}" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.VideoCard}"
|
||||
Visibility="{Binding IsGrid, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Shell.Nav.Videos}"
|
||||
KeyboardNavigation.TabNavigation="Continue">
|
||||
<ListBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding PlayCommand}" />
|
||||
<KeyBinding Key="Delete" Command="{Binding DeleteCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
|
||||
<v:SequenceCard Title="{Binding Title}" Subtitle="{Binding DetailsText}" Badge="{Binding DurationText}" Statuses="{Binding States}" Thumbnail="{Binding Poster}"
|
||||
IsSelected="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}, Mode=TwoWay}"
|
||||
SelectToolTip="{l:Loc Tooltips.Videos.Select}" ToolTip="{Binding ToolTip}" Loaded="OnCardLoaded">
|
||||
<v:SequenceCard.ActionsContent>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.Play}"
|
||||
Command="{Binding DataContext.PlayCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
|
||||
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="{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="{Binding MenuCopyToolTip}" AutomationProperties.Name="{Binding MenuCopyText}" />
|
||||
</StackPanel>
|
||||
</v:SequenceCard.ActionsContent>
|
||||
</v:SequenceCard>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- List: title, preset, format, duration, size, date and state. -->
|
||||
<Border Grid.Row="2" Style="{StaticResource Border.Panel}" Margin="20,4,20,12" Visibility="{Binding IsList, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,6">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="2*" MinWidth="120" />
|
||||
<ColumnDefinition Style="{StaticResource Column.Preset}" />
|
||||
<ColumnDefinition Style="{StaticResource Column.Format}" />
|
||||
<ColumnDefinition Width="72" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<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.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.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>
|
||||
<ListBox x:Name="RowList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.VideoRow}" SelectionMode="Extended"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutomationProperties.Name="{l:Loc Shell.Nav.Videos}" KeyboardNavigation.TabNavigation="Continue">
|
||||
<ListBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding PlayCommand}" />
|
||||
<KeyBinding Key="Delete" Command="{Binding DeleteCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
|
||||
<Grid ToolTip="{Binding ToolTip}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="2*" MinWidth="120" />
|
||||
<ColumnDefinition Style="{StaticResource Column.Preset}" />
|
||||
<ColumnDefinition Style="{StaticResource Column.Format}" />
|
||||
<ColumnDefinition Width="72" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<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.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.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>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Empty states: no video anywhere, or none the filters keep. -->
|
||||
<ui:EmptyState Grid.Row="2" Message="{l:Loc Videos.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ui:EmptyState Grid.Row="2" Message="{l:Loc Videos.Empty}" Visibility="{Binding IsNoMatch, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Library.ClearFilters}" Command="{Binding ClearFiltersCommand}" ToolTip="{l:Loc Tooltips.Library.ClearFilters}" />
|
||||
</ui:EmptyState>
|
||||
|
||||
<!-- The player pane on the right (decision 21). -->
|
||||
<vid:VideoPlayerPane Grid.Row="2" Grid.Column="1" Width="420" Margin="0,4,20,12" DataContext="{Binding Player}"
|
||||
Visibility="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
<!-- The actions on the selection; Delete… stands apart at the far right, the destructive action last. -->
|
||||
<Border Grid.Row="3" Grid.ColumnSpan="2" Style="{StaticResource Border.Panel}" Padding="14,8,6,0" Margin="20,0,20,12" MinHeight="48"
|
||||
Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<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="{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="{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>
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.Destructive}" Height="30" Margin="8,0,8,8" VerticalAlignment="Top" Content="{l:Loc Videos.Delete}"
|
||||
Command="{Binding DeleteCommand}" ToolTip="{Binding DeleteToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Videos;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>Videos: every render made from the photos, here and on the server, in cards or a list, with a player beside them.</summary>
|
||||
public partial class VideosView : UserControl
|
||||
{
|
||||
public VideosView() => InitializeComponent();
|
||||
|
||||
private VideosViewModel? Model => DataContext as VideosViewModel;
|
||||
|
||||
/// <summary>A double click plays the render (or shows "Cannot play here" when it cannot).</summary>
|
||||
private void OnItemDoubleClick(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (sender is not ListBoxItem { DataContext: VideoRowViewModel row } || Model is not { } model) return;
|
||||
if (model.PlayCommand.CanExecute(row)) model.PlayCommand.Execute(row);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
/// <summary>A card asks for its cover only once it is on screen.</summary>
|
||||
private void OnCardLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is FrameworkElement { DataContext: VideoRowViewModel row }) row.RequestPoster();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,892 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Videos;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Windows.Security;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// The Videos section (owner review 1, R9; decisions 20 and 21): every render of this PC's archive, of the signed-in server
|
||||
/// and of the workspace (not sent yet) in one list, merged by render id, with filters, an order, cards or a list, and the
|
||||
/// actions on the selection: Play in the pane on the right, Show in folder, Copy (or Download) to the videos folder checked
|
||||
/// by hash, Copy on server, Delete… into the trash after a dry run, Open in Edit, and Send for the workspace's renders.
|
||||
/// An older server, or none, leaves this PC's videos with the reason.
|
||||
/// </summary>
|
||||
public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection
|
||||
{
|
||||
private IReadOnlyList<VideoEntry> _entries = [];
|
||||
private IReadOnlyList<VideoRowViewModel> _rows = [];
|
||||
private IReadOnlyList<FilterOption<string?>> _kinds = [];
|
||||
private IReadOnlyList<FilterOption<string?>> _codecs = [];
|
||||
private IReadOnlyList<FilterOption<int?>> _years = [];
|
||||
private IReadOnlyList<FilterOption<VideoSourceFilter>> _sources = [];
|
||||
private IReadOnlyList<FilterOption<string?>> _sorts = [];
|
||||
private FilterOption<string?> _kind = null!;
|
||||
private FilterOption<string?> _codec = null!;
|
||||
private FilterOption<int?> _year = null!;
|
||||
private FilterOption<VideoSourceFilter> _source = null!;
|
||||
private FilterOption<string?> _sort = null!;
|
||||
private string _searchText = string.Empty;
|
||||
private Guid? _sequenceId;
|
||||
private string? _sequenceTitle;
|
||||
private int _layoutIndex;
|
||||
private bool _isLoading;
|
||||
private int _loads;
|
||||
private VideoServer _server = VideoServer.SignedOut;
|
||||
private VideoPlayerViewModel? _player;
|
||||
private readonly Dictionary<Guid, Task<Sequence?>> _sequences = [];
|
||||
|
||||
public VideosViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Videos, "Icon.Videos")
|
||||
{
|
||||
Shell = shell;
|
||||
var services = shell.Services;
|
||||
LocalLibrary = () => services.Archives?.Videos;
|
||||
ServerVideos = () => ServerOf(services);
|
||||
WorkspaceRenders = ct => ReadWorkspaceAsync(services, ct);
|
||||
Folder = () => services.Settings.VideosFolder;
|
||||
Enqueue = async request =>
|
||||
{
|
||||
if (services.Engine is not { } engine) throw new InvalidOperationException("The job engine is not running.");
|
||||
await engine.EnqueueAsync(request);
|
||||
};
|
||||
Posters = (entry, width, ct) => PosterAsync(services, entry, width, ct);
|
||||
BuildOptions();
|
||||
|
||||
PlayCommand = new RelayCommand(p => Play(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
|
||||
ShowInFolderCommand = new RelayCommand(p => ShowInFolder(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
|
||||
CopyCommand = new AsyncRelayCommand((p, _) => CopyAsync(Targets(p)), p => CopyBlocker(Targets(p)) is null);
|
||||
CopyOnServerCommand = new AsyncRelayCommand((p, _) => CopyOnServerAsync(Targets(p)), p => CopyOnServerBlocker(Targets(p)) is null);
|
||||
DeleteCommand = new AsyncRelayCommand((p, _) => DeleteAsync(Targets(p)), p => DeleteBlocker(Targets(p)) is null);
|
||||
OpenInEditCommand = new RelayCommand(p => OpenInEdit(Target(p)), p => Target(p) is { } row && CanOpen(row.Entry));
|
||||
SendCommand = new AsyncRelayCommand((p, _) => SendAsync(Targets(p)), p => Targets(p).Any(r => r.Entry.IsUnsent));
|
||||
ClearFiltersCommand = new RelayCommand(ClearFilters, () => Filter.IsFiltered);
|
||||
ClearSequenceCommand = new RelayCommand(() => ShowSequence(null), () => IsSequenceFiltered);
|
||||
RefreshCommand = new AsyncRelayCommand(RefreshAsync);
|
||||
_layoutIndex = services.Settings.VideosLayout == LibraryLayout.List ? 1 : 0;
|
||||
ClearSelectionCommand = new RelayCommand(() =>
|
||||
{
|
||||
foreach (var row in _rows) row.IsSelected = false;
|
||||
}, () => HasSelection);
|
||||
ClosePlayerCommand = new RelayCommand(() => Player = null);
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
// ---- Sources (tests substitute their own) ----
|
||||
|
||||
/// <summary>This PC's videos library; null while the index is not open.</summary>
|
||||
internal Func<IVideoLibrary?> LocalLibrary { get; set; }
|
||||
|
||||
/// <summary>The signed-in server's videos, and what the account may do there.</summary>
|
||||
internal Func<VideoServer> ServerVideos { get; set; }
|
||||
|
||||
/// <summary>The workspace's renders not sent yet.</summary>
|
||||
internal Func<CancellationToken, Task<IReadOnlyList<VideoEntry>>> WorkspaceRenders { get; set; }
|
||||
|
||||
/// <summary>Queues a job of this PC (a copy into the videos folder).</summary>
|
||||
internal Func<ArchiveJobRequest, Task> Enqueue { get; set; }
|
||||
|
||||
/// <summary>The poster of a card: the sequence's cover, or the still itself.</summary>
|
||||
internal Func<VideoEntry, int, CancellationToken, Task<ImageSource?>> Posters { get; set; }
|
||||
|
||||
/// <summary>The videos folder of this PC (Settings › Archive); null or empty while unset.</summary>
|
||||
internal Func<string?> Folder { get; set; }
|
||||
|
||||
// ---- List ----
|
||||
|
||||
/// <summary>Every render, merged, before the filters.</summary>
|
||||
public IReadOnlyList<VideoEntry> Entries
|
||||
{
|
||||
get => _entries;
|
||||
private set
|
||||
{
|
||||
_entries = value;
|
||||
BuildOptions();
|
||||
Apply();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The renders the filters keep, in the chosen order.</summary>
|
||||
public IReadOnlyList<VideoRowViewModel> Rows
|
||||
{
|
||||
get => _rows;
|
||||
private set
|
||||
{
|
||||
foreach (var row in _rows)
|
||||
{
|
||||
row.SelectionChanged -= OnSelectionChanged;
|
||||
row.PosterRequested -= OnPosterRequested;
|
||||
}
|
||||
if (!Set(ref _rows, value)) return;
|
||||
foreach (var row in _rows)
|
||||
{
|
||||
row.Section = this;
|
||||
row.SelectionChanged += OnSelectionChanged;
|
||||
row.PosterRequested += OnPosterRequested;
|
||||
}
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(IsNoMatch));
|
||||
OnSelectionChanged(null);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLoading
|
||||
{
|
||||
get => _isLoading;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _isLoading, value)) return;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(IsNoMatch));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No video anywhere: "No videos".</summary>
|
||||
public bool IsEmpty => !_isLoading && _entries.Count == 0;
|
||||
|
||||
/// <summary>Videos, none of which the filters keep: "No videos" and Clear filters.</summary>
|
||||
public bool IsNoMatch => !_isLoading && _entries.Count > 0 && _rows.Count == 0;
|
||||
|
||||
/// <summary>The cards (0) or the list (1), kept for the next run (Settings: <see cref="AppSettings.VideosLayout"/>).</summary>
|
||||
public int LayoutIndex
|
||||
{
|
||||
get => _layoutIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
|
||||
Shell.Services.Settings.VideosLayout = value == 1 ? LibraryLayout.List : LibraryLayout.Grid;
|
||||
OnPropertyChanged(nameof(IsGrid));
|
||||
OnPropertyChanged(nameof(IsList));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsGrid => _layoutIndex == 0;
|
||||
public bool IsList => _layoutIndex == 1;
|
||||
|
||||
// ---- Filters ----
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _searchText;
|
||||
set
|
||||
{
|
||||
if (Set(ref _searchText, value ?? string.Empty)) Apply();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<FilterOption<string?>> Kinds { get => _kinds; private set => Set(ref _kinds, value); }
|
||||
public IReadOnlyList<FilterOption<string?>> Codecs { get => _codecs; private set => Set(ref _codecs, value); }
|
||||
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
|
||||
public IReadOnlyList<FilterOption<VideoSourceFilter>> Sources { get => _sources; private set => Set(ref _sources, value); }
|
||||
public IReadOnlyList<FilterOption<string?>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
|
||||
|
||||
public FilterOption<string?> SelectedKind
|
||||
{
|
||||
get => _kind;
|
||||
set => SetFilter(ref _kind, value ?? _kinds[0]);
|
||||
}
|
||||
|
||||
public FilterOption<string?> SelectedCodec
|
||||
{
|
||||
get => _codec;
|
||||
set => SetFilter(ref _codec, value ?? _codecs[0]);
|
||||
}
|
||||
|
||||
public FilterOption<int?> SelectedYear
|
||||
{
|
||||
get => _year;
|
||||
set => SetFilter(ref _year, value ?? _years[0]);
|
||||
}
|
||||
|
||||
public FilterOption<VideoSourceFilter> SelectedSource
|
||||
{
|
||||
get => _source;
|
||||
set => SetFilter(ref _source, value ?? _sources[0]);
|
||||
}
|
||||
|
||||
public FilterOption<string?> SelectedSort
|
||||
{
|
||||
get => _sort;
|
||||
set => SetFilter(ref _sort, value ?? _sorts[0]);
|
||||
}
|
||||
|
||||
public bool IsKindFiltered => _kind is { IsAny: false };
|
||||
public bool IsCodecFiltered => _codec is { IsAny: false };
|
||||
public bool IsYearFiltered => _year is { IsAny: false };
|
||||
public bool IsSourceFiltered => _source is { IsAny: false };
|
||||
|
||||
/// <summary>The sequence the list is narrowed to (the Export footer's and the Render menu's "Videos"); null for all.</summary>
|
||||
public Guid? SequenceId => _sequenceId;
|
||||
|
||||
/// <summary>The title of that sequence, shown as a chip that clears it.</summary>
|
||||
public string? SequenceFilterText => _sequenceId is null ? null : _sequenceTitle ?? _entries.FirstOrDefault(e => e.SequenceId == _sequenceId)?.Title;
|
||||
|
||||
public bool IsSequenceFiltered => _sequenceId is not null;
|
||||
|
||||
/// <summary>The filters and the order in force.</summary>
|
||||
public VideoFilter Filter => new()
|
||||
{
|
||||
Text = _searchText,
|
||||
Kind = _kind?.Value,
|
||||
Codec = _codec?.Value,
|
||||
Year = _year?.Value,
|
||||
Source = _source?.Value ?? VideoSourceFilter.All,
|
||||
SequenceId = _sequenceId,
|
||||
Sort = _sort?.Value,
|
||||
};
|
||||
|
||||
public ICommand ClearFiltersCommand { get; }
|
||||
|
||||
/// <summary>The sequence chip: the videos of every sequence again, the other filters kept.</summary>
|
||||
public ICommand ClearSequenceCommand { get; }
|
||||
|
||||
/// <summary>Reads this PC's, the server's and the workspace's videos again (<see cref="RefreshAsync"/>).</summary>
|
||||
public ICommand RefreshCommand { get; }
|
||||
|
||||
/// <summary>Narrows the list to the videos of one sequence (null: every sequence).</summary>
|
||||
public void ShowSequence(Guid? sequenceId, string? title = null)
|
||||
{
|
||||
_sequenceId = sequenceId;
|
||||
_sequenceTitle = sequenceId is null ? null : title;
|
||||
OnPropertyChanged(nameof(SequenceId));
|
||||
OnPropertyChanged(nameof(SequenceFilterText));
|
||||
OnPropertyChanged(nameof(IsSequenceFiltered));
|
||||
Apply();
|
||||
}
|
||||
|
||||
/// <summary>The editor's links to this section (<see cref="Chronos.App.Editor.VideosLink"/>) narrow it the same way.</summary>
|
||||
void Chronos.App.Editor.IVideosSection.ShowSequence(Guid? sequenceId) => ShowSequence(sequenceId);
|
||||
|
||||
// ---- Server ----
|
||||
|
||||
/// <summary>How the signed-in server's videos reach the list.</summary>
|
||||
public VideoServerState ServerState => _server.State;
|
||||
|
||||
/// <summary>The server's videos are not listed: the status line says why.</summary>
|
||||
public bool IsServerLimited => _server.State != VideoServerState.Available && (_server.State != VideoServerState.SignedOut || Shell.Services.Server.HasSavedSession);
|
||||
|
||||
/// <summary>"Server not reachable", or "Server" greyed out with its reason in <see cref="ServerStatusToolTip"/>.</summary>
|
||||
public string ServerStatusText => _server.State == VideoServerState.Unreachable ? Loc.L("Videos.ServerUnreachable") : Loc.L("Videos.Source.Server");
|
||||
|
||||
public string? ServerStatusToolTip => _server.State switch
|
||||
{
|
||||
VideoServerState.Old => Loc.L("Tooltips.Videos.ServerOld"),
|
||||
VideoServerState.SignedOut => Loc.L("Tooltips.Videos.ServerOffline"),
|
||||
VideoServerState.Unreachable => Loc.L("Tooltips.Videos.ServerOffline"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
// ---- Selection ----
|
||||
|
||||
public IReadOnlyList<VideoRowViewModel> SelectedRows => [.. _rows.Where(r => r.IsSelected)];
|
||||
|
||||
public bool HasSelection => _rows.Any(r => r.IsSelected);
|
||||
|
||||
/// <summary>"Selected: 3".</summary>
|
||||
public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(_rows.Count(r => r.IsSelected)));
|
||||
|
||||
public ICommand ClearSelectionCommand { get; }
|
||||
|
||||
// ---- Actions ----
|
||||
|
||||
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 => PlayToolTipOf(SelectedRows);
|
||||
|
||||
public ICommand ShowInFolderCommand { get; }
|
||||
public ICommand CopyCommand { get; }
|
||||
public ICommand CopyOnServerCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
public ICommand OpenInEditCommand { get; }
|
||||
public ICommand SendCommand { get; }
|
||||
|
||||
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
|
||||
public string CopyText => CopyTextOf(SelectedRows);
|
||||
|
||||
public string CopyToolTip => CopyToolTipOf(SelectedRows);
|
||||
|
||||
public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows);
|
||||
|
||||
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) => 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; }
|
||||
|
||||
/// <summary>The player pane on the right; null while closed.</summary>
|
||||
public VideoPlayerViewModel? Player
|
||||
{
|
||||
get => _player;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _player, value)) return;
|
||||
OnPropertyChanged(nameof(IsPlayerOpen));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPlayerOpen => _player is not null;
|
||||
|
||||
/// <summary>Reads the three places again and lists what they hold (the filters stay).</summary>
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
var load = ++_loads;
|
||||
IsLoading = true;
|
||||
try
|
||||
{
|
||||
var server = ServerVideos();
|
||||
var localTask = ReadLocalAsync();
|
||||
var serverTask = ReadServerAsync(server);
|
||||
var workspaceTask = ReadWorkspaceSafeAsync();
|
||||
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 = merged;
|
||||
OnPropertyChanged(nameof(ServerState));
|
||||
OnPropertyChanged(nameof(IsServerLimited));
|
||||
OnPropertyChanged(nameof(ServerStatusText));
|
||||
OnPropertyChanged(nameof(ServerStatusToolTip));
|
||||
OnPropertyChanged(nameof(SequenceFilterText));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (load == _loads) IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnActivated() => _ = RefreshAsync();
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
BuildOptions();
|
||||
// The rows' words are made with them: made again in the new language.
|
||||
Rows = [];
|
||||
Apply();
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<VideoEntry>> ReadLocalAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => VideoSources.ReadLocalAsync(LocalLibrary()));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("videos", "The videos of this PC could not be listed", ex);
|
||||
Shell.ReportError(ex);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
try
|
||||
{
|
||||
using var remote = connect();
|
||||
return (await VideoSources.ReadServerAsync(remote), server);
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
Log.Warning("videos", "The server's videos could not be listed", ex);
|
||||
return ([], server with { State = VideoServerState.Unreachable, Connect = null });
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<VideoEntry>> ReadWorkspaceSafeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await WorkspaceRenders(CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or WorkspaceException or DatabaseException)
|
||||
{
|
||||
Log.Warning("videos", "The workspace's renders could not be listed", ex);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<VideoEntry>> ReadWorkspaceAsync(AppServices services, CancellationToken cancellationToken)
|
||||
{
|
||||
var workspace = services.Workspace;
|
||||
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
|
||||
var projects = await workspace.ListAsync(cancellationToken);
|
||||
return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The signed-in session's server, its capability and the account's rights.</summary>
|
||||
private static VideoServer ServerOf(AppServices services)
|
||||
{
|
||||
var session = services.Server;
|
||||
if (!session.IsConnected || session.Flow is not { Address: { } address, Token: { } token, Info: { } info }) return VideoServer.SignedOut;
|
||||
return VideoServer.Of(info, session.User?.Permissions ?? 0, () =>
|
||||
new ChronosRemoteVideos(new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token }));
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
{
|
||||
// A row is kept while its render reads the same (its selection and its poster with it).
|
||||
var cache = _rows.ToDictionary(r => r.Entry.Id);
|
||||
Rows = [.. Filter.Apply(_entries).Select(e => cache.TryGetValue(e.Id, out var row)
|
||||
? row.Entry == e ? row : new VideoRowViewModel(e) { IsSelected = row.IsSelected, Poster = row.Poster }
|
||||
: new VideoRowViewModel(e))];
|
||||
if (_player is { } player && !_entries.Any(e => e.Id == player.Entry.Id)) Player = null;
|
||||
OnPropertyChanged(nameof(Filter));
|
||||
}
|
||||
|
||||
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
|
||||
{
|
||||
if (EqualityComparer<FilterOption<T>>.Default.Equals(field, value)) return;
|
||||
field = value;
|
||||
OnPropertyChanged(name);
|
||||
OnPropertyChanged(nameof(IsKindFiltered));
|
||||
OnPropertyChanged(nameof(IsCodecFiltered));
|
||||
OnPropertyChanged(nameof(IsYearFiltered));
|
||||
OnPropertyChanged(nameof(IsSourceFiltered));
|
||||
Apply();
|
||||
}
|
||||
|
||||
private void ClearFilters()
|
||||
{
|
||||
_searchText = string.Empty;
|
||||
_kind = _kinds[0];
|
||||
_codec = _codecs[0];
|
||||
_year = _years[0];
|
||||
_source = _sources[0];
|
||||
_sequenceId = null;
|
||||
_sequenceTitle = null;
|
||||
OnAllPropertiesChanged();
|
||||
Apply();
|
||||
}
|
||||
|
||||
/// <summary>The choices of the filters: kinds, sources and orders fixed, codecs and years those the videos have; each choice kept.</summary>
|
||||
private void BuildOptions()
|
||||
{
|
||||
var kind = _kind?.Value;
|
||||
var codec = _codec?.Value;
|
||||
var year = _year?.Value;
|
||||
var source = _source?.Value ?? VideoSourceFilter.All;
|
||||
var sort = _sort?.Value;
|
||||
var allKinds = Loc.L("Videos.Kind.All");
|
||||
Kinds =
|
||||
[
|
||||
new(null, allKinds, allKinds, IsAny: true),
|
||||
.. new[] { RenderKind.Video, RenderKind.Still, RenderKind.Sequence }.Select(k => new FilterOption<string?>(k, VideoText.Kind(k), VideoText.Kind(k))),
|
||||
];
|
||||
var allCodecs = Loc.L("Videos.Codec.All");
|
||||
Codecs =
|
||||
[
|
||||
new(null, allCodecs, allCodecs, IsAny: true),
|
||||
.. _entries.Select(e => e.Codec).OfType<string>().Where(c => c.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Append(codec).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Select(c => new FilterOption<string?>(c, VideoSources.CodecText(c), VideoSources.CodecText(c))).OrderBy(o => o.Label, StringComparer.CurrentCulture),
|
||||
];
|
||||
var allYears = Loc.L("Videos.Year.All");
|
||||
Years =
|
||||
[
|
||||
new(null, allYears, allYears, IsAny: true),
|
||||
.. _entries.Select(e => (int?)e.Year).Append(year).OfType<int>().Distinct().OrderDescending()
|
||||
.Select(y => new FilterOption<int?>(y, y.ToString(Loc.Culture), y.ToString(Loc.Culture))),
|
||||
];
|
||||
var allSources = Loc.L("Videos.Source.All");
|
||||
Sources =
|
||||
[
|
||||
new(VideoSourceFilter.All, allSources, allSources, IsAny: true),
|
||||
new(VideoSourceFilter.Local, Loc.L("Videos.Source.Local"), Loc.L("Videos.Source.Local")),
|
||||
new(VideoSourceFilter.Server, Loc.L("Videos.Source.Server"), Loc.L("Videos.Source.Server")),
|
||||
new(VideoSourceFilter.NotSent, Loc.L("Videos.Source.NotSent"), Loc.L("Videos.Source.NotSent")),
|
||||
];
|
||||
Sorts = [.. VideoSorts.All.Select(s => new FilterOption<string?>(s, SortText(s), SortText(s), IsAny: s == VideoSorts.Newest))];
|
||||
_kind = _kinds.First(o => o.Value == kind);
|
||||
_codec = _codecs.FirstOrDefault(o => string.Equals(o.Value, codec, StringComparison.OrdinalIgnoreCase)) ?? _codecs[0];
|
||||
_year = _years.First(o => o.Value == year);
|
||||
_source = _sources.First(o => o.Value == source);
|
||||
_sort = _sorts.FirstOrDefault(o => o.Value == sort) ?? _sorts[0];
|
||||
OnPropertyChanged(nameof(SelectedKind));
|
||||
OnPropertyChanged(nameof(SelectedCodec));
|
||||
OnPropertyChanged(nameof(SelectedYear));
|
||||
OnPropertyChanged(nameof(SelectedSource));
|
||||
OnPropertyChanged(nameof(SelectedSort));
|
||||
}
|
||||
|
||||
private static string SortText(string sort) => sort switch
|
||||
{
|
||||
VideoSorts.Oldest => Loc.L("Videos.Sort.Oldest"),
|
||||
VideoSorts.Largest => Loc.L("Videos.Sort.Largest"),
|
||||
VideoSorts.Title => Loc.L("Videos.Sort.Title"),
|
||||
_ => Loc.L("Videos.Sort.Newest"),
|
||||
};
|
||||
|
||||
private void OnSelectionChanged(VideoRowViewModel? row)
|
||||
{
|
||||
OnPropertyChanged(nameof(HasSelection));
|
||||
OnPropertyChanged(nameof(SelectedRows));
|
||||
OnPropertyChanged(nameof(SelectionText));
|
||||
OnPropertyChanged(nameof(CopyText));
|
||||
OnPropertyChanged(nameof(PlayToolTip));
|
||||
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();
|
||||
}
|
||||
|
||||
private async void OnPosterRequested(VideoRowViewModel row)
|
||||
{
|
||||
try
|
||||
{
|
||||
row.Poster = await Posters(row.Entry, 472, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or DatabaseException or InvalidOperationException
|
||||
or OperationCanceledException)
|
||||
{
|
||||
Log.Info("videos", $"The poster of {row.Entry.FileName} could not be loaded: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A still shows itself; any other render of this PC its sequence's cover.</summary>
|
||||
private async Task<ImageSource?> PosterAsync(AppServices services, VideoEntry entry, int width, CancellationToken cancellationToken)
|
||||
{
|
||||
if (entry.Kind == RenderKind.Still && entry.HasLocalFile && VideoSources.ShowsAsImage(entry.LocalPath))
|
||||
{
|
||||
return await Task.Run<ImageSource?>(() =>
|
||||
{
|
||||
using var stream = File.OpenRead(entry.LocalPath!);
|
||||
return ThumbnailService.DecodeStream(stream, 1, width);
|
||||
}, cancellationToken);
|
||||
}
|
||||
if (!entry.IsLocal || services.Database is not { } db || services.Thumbnails is not { } thumbnails) return null;
|
||||
if (!_sequences.TryGetValue(entry.SequenceId, out var sequence)) _sequences[entry.SequenceId] = sequence = db.Sequences.GetAsync(entry.SequenceId, cancellationToken);
|
||||
return await sequence is { } found ? await thumbnails.HeroAsync(found, width, cancellationToken) : null;
|
||||
}
|
||||
|
||||
// ---- What the actions apply to ----
|
||||
|
||||
/// <summary>A row's own menu acts on the row, or on the selection when the row is part of it; the toolbar on the selection.</summary>
|
||||
private IReadOnlyList<VideoRowViewModel> Targets(object? parameter) =>
|
||||
parameter is VideoRowViewModel row ? row.IsSelected ? SelectedRows : [row] : SelectedRows;
|
||||
|
||||
private VideoRowViewModel? Target(object? parameter) => Targets(parameter) is [var one] ? one : null;
|
||||
|
||||
private string? FolderProblem()
|
||||
{
|
||||
var folder = Folder();
|
||||
var problem = VideosFolders.Problem(folder, Shell.Services.Settings.LastArchivePath, Shell.Services.Workspace.Root);
|
||||
return problem ?? LocalLibrary()?.FolderProblem(folder);
|
||||
}
|
||||
|
||||
/// <summary>Why Copy to folder cannot run on <paramref name="rows"/>; null when it can.</summary>
|
||||
internal string? CopyBlocker(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
if (rows.Count == 0) return Loc.L("Tooltips.Videos.Copy");
|
||||
if (!rows.Any(r => Copyable(r.Entry))) return rows.All(r => r.Entry.Missing) ? Loc.L("Tooltips.Videos.Missing") : Loc.L("Tooltips.Videos.WorkspaceRow");
|
||||
if (FolderProblem() is { } problem) return VideoText.FolderReason(problem);
|
||||
return LocalLibrary() is { IsAvailable: true } ? null : Loc.L("Tooltips.Videos.Copy");
|
||||
}
|
||||
|
||||
/// <summary>Why Copy on server cannot run on <paramref name="rows"/>; null when it can.</summary>
|
||||
internal string? CopyOnServerBlocker(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
if (_server.State != VideoServerState.Available) return ServerStatusToolTip;
|
||||
if (!_server.CanEdit) return Loc.L("Tooltips.Videos.NoEditRight");
|
||||
return rows.Any(r => r.Entry is { IsOnServer: true, Missing: false }) ? null : Loc.L("Tooltips.Videos.OnServer");
|
||||
}
|
||||
|
||||
/// <summary>Why Delete… cannot run on <paramref name="rows"/>; null when it can.</summary>
|
||||
internal string? DeleteBlocker(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
if (rows.Count == 0) return Loc.L("Tooltips.Videos.Delete");
|
||||
if (rows.All(r => r.Entry.IsUnsent)) return Loc.L("Tooltips.Videos.WorkspaceRow");
|
||||
var local = rows.Any(r => r.Entry.IsLocal) && LocalLibrary() is { IsAvailable: true };
|
||||
var server = rows.Any(r => !r.Entry.IsLocal && r.Entry.IsOnServer);
|
||||
if (local) return null;
|
||||
if (server && _server.State != VideoServerState.Available) return ServerStatusToolTip;
|
||||
if (server && !_server.CanDelete) return Loc.L("Tooltips.Videos.NoDeleteRight");
|
||||
return server ? null : Loc.L("Tooltips.Videos.Delete");
|
||||
}
|
||||
|
||||
/// <summary>A render Copy to folder takes: this PC's file, or the server's alone (downloaded).</summary>
|
||||
private bool Copyable(VideoEntry entry) =>
|
||||
!entry.IsUnsent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available));
|
||||
|
||||
private static bool CanOpen(VideoEntry entry) => entry.IsLocal || entry is { IsUnsent: true, WorkspaceServerHome: false };
|
||||
|
||||
// ---- Actions ----
|
||||
|
||||
private void Play(VideoRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
Player = new VideoPlayerViewModel(row.Entry, ClosePlayerCommand, new RelayCommand(() => ShowInFolder(row), () => row.Entry.HasLocalFile));
|
||||
}
|
||||
|
||||
private static void ShowInFolder(VideoRowViewModel? row)
|
||||
{
|
||||
if (row?.Entry is { HasLocalFile: true, LocalPath: { } path }) ShellActions.Reveal(path);
|
||||
}
|
||||
|
||||
private void OpenInEdit(VideoRowViewModel? row)
|
||||
{
|
||||
if (row is not null && CanOpen(row.Entry)) Shell.OpenSequence(row.Entry.SequenceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy to folder: this PC's renders are copied into the videos folder, the server's alone downloaded there, each checked
|
||||
/// by hash (a <see cref="JobKind.VideoCopy"/> job of this PC); the renders themselves are never touched.
|
||||
/// </summary>
|
||||
internal async Task CopyAsync(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
if (CopyBlocker(rows) is { } blocker)
|
||||
{
|
||||
Shell.Notify(blocker, isError: true);
|
||||
return;
|
||||
}
|
||||
var folder = Path.GetFullPath(Folder()!);
|
||||
var library = LocalLibrary()!;
|
||||
var copyable = rows.Select(r => r.Entry).Where(Copyable).ToList();
|
||||
try
|
||||
{
|
||||
foreach (var (fromServer, ids) in new[] { (false, copyable.Where(e => e.IsLocal)), (true, copyable.Where(e => !e.IsLocal)) })
|
||||
{
|
||||
IReadOnlyList<Guid> list = [.. ids.Select(e => e.Id)];
|
||||
if (list.Count == 0) continue;
|
||||
await Enqueue(library.CopyJob(new VideoCopyParameters(list, folder, fromServer, Environment.MachineName)));
|
||||
}
|
||||
Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(copyable.Count)), Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"),
|
||||
() => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
Shell.Notify(VideoText.Error(ex), isError: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidOperationException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copy on server: the server copies its renders into its own videos folder, checked by hash.</summary>
|
||||
internal async Task CopyOnServerAsync(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
var blocker = CopyOnServerBlocker(rows);
|
||||
if (blocker is not null || _server.Connect is not { } connect)
|
||||
{
|
||||
Shell.Notify(blocker ?? Loc.L("Tooltips.Videos.ServerOffline"), isError: true);
|
||||
return;
|
||||
}
|
||||
IReadOnlyList<Guid> ids = [.. rows.Where(r => r.Entry is { IsOnServer: true, Missing: false }).Select(r => r.Entry.Id)];
|
||||
try
|
||||
{
|
||||
using var remote = connect();
|
||||
await remote.CopyAsync(ids);
|
||||
Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(ids.Count)));
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
Log.Warning("videos", "Copying videos on the server failed", ex);
|
||||
Shell.Notify(ErrorText.ForServer(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete…: the dry run first (this PC's renders and the server's alone apart), then one confirmation saying what goes,
|
||||
/// its bytes, what stays and why, and that copies in the videos folder stay; then each delete with its plan's
|
||||
/// fingerprint, which a changed plan refuses with nothing moved.
|
||||
/// </summary>
|
||||
internal async Task DeleteAsync(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
if (DeleteBlocker(rows) is { } blocker)
|
||||
{
|
||||
Shell.Notify(blocker, isError: true);
|
||||
return;
|
||||
}
|
||||
var library = LocalLibrary();
|
||||
IReadOnlyList<Guid> localIds = library is { IsAvailable: true } ? [.. rows.Where(r => r.Entry.IsLocal).Select(r => r.Entry.Id)] : [];
|
||||
IReadOnlyList<Guid> serverIds = _server is { State: VideoServerState.Available, CanDelete: true }
|
||||
? [.. rows.Where(r => !r.Entry.IsLocal && r.Entry.IsOnServer).Select(r => r.Entry.Id)]
|
||||
: [];
|
||||
VideoDeletePlans plans;
|
||||
try
|
||||
{
|
||||
var local = localIds.Count > 0 ? await Task.Run(() => library!.PlanDeleteAsync(localIds)) : null;
|
||||
VideoDeletePlanDto? server = null;
|
||||
if (serverIds.Count > 0 && _server.Connect is { } connect)
|
||||
{
|
||||
using var remote = connect();
|
||||
server = await remote.PlanDeleteAsync(serverIds);
|
||||
}
|
||||
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)
|
||||
{
|
||||
Shell.Notify(ErrorText.ForServer(ex), isError: true);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
return;
|
||||
}
|
||||
LastDeletePlans = plans;
|
||||
if (plans.Request() is not { } request)
|
||||
{
|
||||
if (plans.Blocked > 0) Shell.Notify(Loc.L("Videos.Delete.Blocked", Formatting.Count(plans.Blocked)), string.Join(Environment.NewLine, plans.Lines()), isError: true);
|
||||
return;
|
||||
}
|
||||
if (!Shell.Services.Dialogs.Confirm(request)) return;
|
||||
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(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(serverIds, serverPlan.Fingerprint);
|
||||
deleted += result.Items.Count;
|
||||
}
|
||||
Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted)));
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
Shell.Notify(VideoText.Error(ex), isError: true);
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Error?.Code == VideoErrors.PlanChanged)
|
||||
{
|
||||
Shell.Notify(Loc.L("Errors.Videos.Fingerprint"), isError: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
Shell.Notify(ErrorText.ForServer(ex), isError: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
await RefreshAsync();
|
||||
}
|
||||
|
||||
/// <summary>The plans of the last Delete… (tests).</summary>
|
||||
internal VideoDeletePlans? LastDeletePlans { get; private set; }
|
||||
|
||||
/// <summary>Send: queues the sending home of the workspace projects' renders not sent yet.</summary>
|
||||
private async Task SendAsync(IReadOnlyList<VideoRowViewModel> rows)
|
||||
{
|
||||
foreach (var project in rows.Select(r => r.Entry).Where(e => e.IsUnsent && e.WorkspaceProjectId is not null).Select(e => e.WorkspaceProjectId!.Value).Distinct())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await Shell.Services.Workspace.SendRendersAsync(project))
|
||||
Shell.Notify(Loc.L("Editor.Render.Sending"), null, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("videos", $"The renders of workspace project {project} could not be queued to be sent", ex);
|
||||
Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What Send does for <paramref name="row"/>, worded for its project's home.</summary>
|
||||
public static string SendToolTip(VideoRowViewModel row)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", row.Entry.WorkspaceServerHome);
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,7 @@ public static class SyncText
|
||||
["export.nameTemplate"] = "Server.Setting.OutputName",
|
||||
["export.folder"] = "Server.Setting.ExportFolder",
|
||||
["export.batch"] = "Server.Setting.Batch",
|
||||
["export.playback"] = "Server.Setting.Playback",
|
||||
["excludedFrames"] = "Server.Setting.ExcludedFrames",
|
||||
["heroFrame"] = "Server.Setting.HeroFrame",
|
||||
};
|
||||
|
||||
@@ -13,20 +13,22 @@
|
||||
<ui:ChronosWindow.TaskbarItemInfo>
|
||||
<TaskbarItemInfo ProgressState="{Binding TaskbarState}" ProgressValue="{Binding TaskbarProgress}" />
|
||||
</ui:ChronosWindow.TaskbarItemInfo>
|
||||
<!-- Sections by keyboard, as the rail tooltips list them (BRIEF §12.1): Ctrl+1…6 down the rail, Ctrl+, for Settings. -->
|
||||
<!-- Sections by keyboard, as the rail tooltips list them (BRIEF §12.1): Ctrl+1…7 down the rail (Videos at Ctrl+4, owner review 1, R9), Ctrl+, for Settings. -->
|
||||
<ui:ChronosWindow.InputBindings>
|
||||
<KeyBinding Key="D1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
|
||||
<KeyBinding Key="D2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
|
||||
<KeyBinding Key="D3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Edit}" />
|
||||
<KeyBinding Key="D4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="D5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="D6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="D4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Videos}" />
|
||||
<KeyBinding Key="D5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="D6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="D7" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="NumPad1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
|
||||
<KeyBinding Key="NumPad2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
|
||||
<KeyBinding Key="NumPad3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Edit}" />
|
||||
<KeyBinding Key="NumPad4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="NumPad5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="NumPad6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="NumPad4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Videos}" />
|
||||
<KeyBinding Key="NumPad5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
|
||||
<KeyBinding Key="NumPad6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
|
||||
<KeyBinding Key="NumPad7" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
|
||||
<KeyBinding Key="OemComma" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Settings}" />
|
||||
<!-- The rail's names or its icons alone (owner review 1). -->
|
||||
<KeyBinding Key="B" Modifiers="Control" Command="{Binding ToggleRailCommand}" />
|
||||
|
||||
@@ -17,13 +17,14 @@ using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Theming;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Chronos.exe --capture <dir></c>: renders every client screen at 1440×900 in the dark and light themes to
|
||||
/// <c><screen>-<theme>.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
|
||||
/// one, then the sync table with transfers, a conflict and its confirmation, then the sequence editor on an archive
|
||||
/// one, then the Videos section, then the sync table with transfers, a conflict and its confirmation, then the sequence editor on an archive
|
||||
/// sequence and on a server sequence with proxies, its server job and a read-only account), plus the Library, the
|
||||
/// editor's Exposure tab and the import plan in Arabic (<c>*-rtl-dark.png</c>, right to left), for visual review,
|
||||
/// the pixel diff against <c>tests/visual/baselines</c> and phase reports (BRIEF §20.2), then exits. The pictures are
|
||||
@@ -140,6 +141,8 @@ public static class ScreenCapture
|
||||
written += await SaveAsync(window, directory, "archive-" + view, theme);
|
||||
}
|
||||
}
|
||||
written += await CaptureVideosAsync(window, shell, sample, directory);
|
||||
|
||||
// The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the
|
||||
// conflict's confirmation (after the other screens, so the Jobs capture keeps its own sample).
|
||||
await sample.CacheProxiesAsync();
|
||||
@@ -224,6 +227,42 @@ public static class ScreenCapture
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Videos section (owner review 1, R9) on <see cref="SampleData.FillVideosAsync"/> in both themes: the cards of this
|
||||
/// PC's, the server's and the workspace's renders (<c>videos</c>), then the list with the still selected and shown in the
|
||||
/// player pane (<c>videos-list</c>); the cards again after, with nothing selected.
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureVideosAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
{
|
||||
var videos = shell.Videos;
|
||||
await sample.FillVideosAsync(videos);
|
||||
var written = 0;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
DismissToasts(window);
|
||||
videos.LayoutIndex = 0;
|
||||
shell.Navigate(SectionKey.Videos);
|
||||
await videos.RefreshAsync();
|
||||
await Settle(window);
|
||||
// The cards ask for their covers once shown; the covers decode off the UI thread.
|
||||
for (var i = 0; i < 40 && videos.Rows.Any(r => r.Entry.IsLocal && r.Poster is null); i++) await Task.Delay(50);
|
||||
written += await SaveAsync(window, directory, "videos", theme, waitForThumbnails: shell);
|
||||
|
||||
videos.LayoutIndex = 1;
|
||||
if (videos.Rows.FirstOrDefault(r => r.Entry.Kind == Core.Model.RenderKind.Still) is { } still)
|
||||
{
|
||||
still.IsSelected = true;
|
||||
videos.PlayCommand.Execute(still);
|
||||
}
|
||||
written += await SaveAsync(window, directory, "videos-list", theme);
|
||||
videos.ClosePlayerCommand.Execute(null);
|
||||
videos.ClearSelectionCommand.Execute(null);
|
||||
videos.LayoutIndex = 0;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
|
||||
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
|
||||
|
||||
@@ -251,7 +290,8 @@ public static class ScreenCapture
|
||||
/// The editor on the synthetic sunset: every step of the Edit path in both themes (<c>edit-<step>-<theme>.png</c>,
|
||||
/// the Camera step with a keyframe selected, the Export step as Export.html with the crop mask and no compare), then
|
||||
/// the preview overlays, the waveform, the "what changed" toast of Optimise all, the picker over the open sequence
|
||||
/// (<c>edit-change</c>), the crop box, straighten and look scenes (<see cref="CaptureFramingAsync"/>), the Export step of the sequence once the server has it (Sync on) with two "Save both" copies
|
||||
/// (<c>edit-change</c>), the crop box, straighten and look scenes (<see cref="CaptureFramingAsync"/>), the Export groups
|
||||
/// and the Render menu (<see cref="CaptureExportAsync"/>), the Export step of the sequence once the server has it (Sync on) with two "Save both" copies
|
||||
/// to restore, and the Analysis step while the analysis runs (<c>edit-busy</c>).
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
@@ -298,6 +338,7 @@ public static class ScreenCapture
|
||||
shell.Sequence.CancelPickCommand.Execute(null);
|
||||
}
|
||||
written += await CaptureFramingAsync(window, editor, directory);
|
||||
written += await CaptureExportAsync(window, editor, directory);
|
||||
|
||||
// The server has the sequence (Sync can be ticked) and two copies of this PC's settings were kept by "Save both".
|
||||
await sample.KeepEditorCopiesAsync(id);
|
||||
@@ -307,11 +348,14 @@ public static class ScreenCapture
|
||||
export.SyncToServer = true;
|
||||
editor.SelectedTab = export;
|
||||
editor.IsCompare = false;
|
||||
// Sync and Restore are rows of the File group: the groups above it folded to their summaries.
|
||||
var groups = OpenGroups(export, export.FileGroup);
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
written += await SaveEditorAsync(window, editor, directory, "edit-export-copies", theme);
|
||||
}
|
||||
RestoreGroups(export, groups);
|
||||
export.SyncToServer = false;
|
||||
editor.SelectedTab = editor.Exposure;
|
||||
editor.IsCompare = true;
|
||||
@@ -374,6 +418,105 @@ public static class ScreenCapture
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Export step of owner review 1 (R3) in both themes: Output and File folded to their summary lines, Encoding and
|
||||
/// Playback open on a boomerang played twice with fades, scrolled down to Playback's last row (<c>edit-export-playback</c>),
|
||||
/// undone after with the groups as they were; then the header's Render ▾ menu dropped down over the Export step
|
||||
/// (<c>edit-render-menu</c>).
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureExportAsync(MainWindow window, EditorViewModel editor, string directory)
|
||||
{
|
||||
var written = 0;
|
||||
var session = editor.Session;
|
||||
var export = editor.Tabs.OfType<ExportTab>().Single();
|
||||
var frame = editor.CurrentIndex;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
editor.SelectedTab = export;
|
||||
editor.IsCompare = false;
|
||||
editor.CurrentIndex = 40;
|
||||
var open = OpenGroups(export, export.EncodingGroup, export.PlaybackGroup);
|
||||
var played = session.Edit(SampleData.Boomerang);
|
||||
await Settle(window);
|
||||
// The panel ends with Playback's last row: scrolled down to it, with as much of Encoding as fits above.
|
||||
var panel = ScrollerOf<SettingGroup>(window);
|
||||
panel?.ScrollToBottom();
|
||||
written += await SaveEditorAsync(window, editor, directory, "edit-export-playback", theme);
|
||||
panel?.ScrollToTop();
|
||||
if (played) session.Undo();
|
||||
RestoreGroups(export, open);
|
||||
|
||||
await Settle(window);
|
||||
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", "edit-render-menu was still busy");
|
||||
written += await SaveRenderMenuAsync(window, editor, directory, theme);
|
||||
}
|
||||
// The scenes after keep the frame they had.
|
||||
editor.CurrentIndex = frame;
|
||||
return written;
|
||||
}
|
||||
|
||||
private static SettingGroup[] GroupsOf(ExportTab export) => [export.OutputGroup, export.EncodingGroup, export.PlaybackGroup, export.FileGroup];
|
||||
|
||||
/// <summary>Opens the Export step's groups <paramref name="open"/> and folds the others; returns which were open, for <see cref="RestoreGroups"/>.</summary>
|
||||
private static bool[] OpenGroups(ExportTab export, params SettingGroup[] open)
|
||||
{
|
||||
var groups = GroupsOf(export);
|
||||
var before = groups.Select(g => g.IsExpanded).ToArray();
|
||||
foreach (var group in groups) group.IsExpanded = open.Contains(group);
|
||||
return before;
|
||||
}
|
||||
|
||||
/// <summary>The Export step's groups open or folded as <see cref="OpenGroups"/> found them (the app keeps them for the next run).</summary>
|
||||
private static void RestoreGroups(ExportTab export, bool[] open)
|
||||
{
|
||||
var groups = GroupsOf(export);
|
||||
for (var i = 0; i < groups.Length; i++) groups[i].IsExpanded = open[i];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window with the header's Render ▾ menu dropped down below its button, as the menu shows it. A context menu opens
|
||||
/// in a popup of its own, on screen, which the window's picture does not hold: the menu is made from the same entries
|
||||
/// (<see cref="SplitButton.CreateItem"/>), laid out apart and drawn over the window where it drops down (kept inside the
|
||||
/// window, as Windows keeps it on the screen).
|
||||
/// </summary>
|
||||
private static async Task<int> SaveRenderMenuAsync(MainWindow window, EditorViewModel editor, string directory, AppTheme theme)
|
||||
{
|
||||
await Settle(window);
|
||||
if (FindVisual<SplitButton>(window, b => b.Name == "RenderButton") is not { } button)
|
||||
{
|
||||
Log.Warning("capture", "The Render button is not shown; edit-render-menu skipped");
|
||||
return 0;
|
||||
}
|
||||
var menu = new ContextMenu { FlowDirection = window.FlowDirection };
|
||||
var template = button.TryFindResource(SplitButton.ItemTemplateKey) as DataTemplate;
|
||||
foreach (var entry in editor.RenderMenuItems) menu.Items.Add(SplitButton.CreateItem(entry, template));
|
||||
menu.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
|
||||
menu.Arrange(new Rect(menu.DesiredSize));
|
||||
menu.UpdateLayout();
|
||||
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
menu.UpdateLayout();
|
||||
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
|
||||
// Below the button, 4 px apart (SplitButton's placement), its left edge on the button's.
|
||||
var at = button.TranslatePoint(new Point(0, button.ActualHeight + 4), root);
|
||||
at = new Point(Math.Round(Math.Clamp(at.X, 0, Math.Max(0, root.ActualWidth - menu.ActualWidth))), Math.Round(at.Y));
|
||||
return Save(window, Path.Combine(directory, $"edit-render-menu-{theme.ToString().ToLowerInvariant()}.png"), (menu, at)) ? 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>The first shown element of type <typeparamref name="T"/> under <paramref name="root"/> that <paramref name="match"/> takes; null when none.</summary>
|
||||
private static T? FindVisual<T>(DependencyObject root, Func<T, bool> match)
|
||||
where T : FrameworkElement
|
||||
{
|
||||
var pending = new Stack<DependencyObject>([root]);
|
||||
while (pending.Count > 0)
|
||||
{
|
||||
var node = pending.Pop();
|
||||
if (node is T { IsVisible: true } found && match(found)) return found;
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) pending.Push(VisualTreeHelper.GetChild(node, i));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The scroll viewer around the shown row whose data is a <typeparamref name="TRow"/>; null when none is shown.</summary>
|
||||
private static ScrollViewer? ScrollerOf<TRow>(DependencyObject root)
|
||||
{
|
||||
@@ -455,7 +598,10 @@ public static class ScreenCapture
|
||||
written += await SaveEditorAsync(window, editor, directory, "edit-remote", theme);
|
||||
editor.SelectedTab = export;
|
||||
editor.IsCompare = false;
|
||||
// The server's encoder is the Encoding group's first row, the folder it keeps the renders in the File group's.
|
||||
var groups = OpenGroups(export, export.EncodingGroup, export.FileGroup);
|
||||
written += await SaveEditorAsync(window, editor, directory, "edit-remote-export", theme);
|
||||
RestoreGroups(export, groups);
|
||||
}
|
||||
|
||||
sample.RunServerRender();
|
||||
@@ -522,7 +668,8 @@ public static class ScreenCapture
|
||||
window.UpdateLayout();
|
||||
}
|
||||
|
||||
private static bool Save(Window window, string path)
|
||||
/// <param name="overlay">An element laid out apart (a drop-down menu) drawn over the window with its top left at the point given.</param>
|
||||
private static bool Save(Window window, string path, (FrameworkElement Element, Point At)? overlay = null)
|
||||
{
|
||||
if (VisualTreeHelper.GetChildrenCount(window) == 0) window.ApplyTemplate();
|
||||
if (VisualTreeHelper.GetChildrenCount(window) == 0)
|
||||
@@ -542,8 +689,24 @@ public static class ScreenCapture
|
||||
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
// A right-to-left window's content already renders mirrored, as on screen.
|
||||
bitmap.Render(root);
|
||||
BitmapSource picture = bitmap;
|
||||
if (overlay is ({ } element, var at))
|
||||
{
|
||||
var layer = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(element.ActualHeight * dpi.DpiScaleY),
|
||||
dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
layer.Render(element);
|
||||
var drawing = new DrawingVisual();
|
||||
using (var context = drawing.RenderOpen())
|
||||
{
|
||||
context.DrawImage(bitmap, new Rect(0, 0, width / dpi.DpiScaleX, height / dpi.DpiScaleY));
|
||||
context.DrawImage(layer, new Rect(at, new Size(layer.PixelWidth / dpi.DpiScaleX, layer.PixelHeight / dpi.DpiScaleY)));
|
||||
}
|
||||
var composed = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
composed.Render(drawing);
|
||||
picture = composed;
|
||||
}
|
||||
var encoder = new PngBitmapEncoder();
|
||||
encoder.Frames.Add(BitmapFrame.Create(bitmap));
|
||||
encoder.Frames.Add(BitmapFrame.Create(picture));
|
||||
using var stream = File.Create(path);
|
||||
encoder.Save(stream);
|
||||
return true;
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
<DataTemplate DataType="{x:Type s:LibraryViewModel}"><s:LibraryView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ImportViewModel}"><s:ImportView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SequenceViewModel}"><s:SequenceView /></DataTemplate>
|
||||
<!-- The videos library (owner review 1, R9). -->
|
||||
<DataTemplate DataType="{x:Type s:VideosViewModel}"><s:VideosView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ArchiveViewModel}"><s:ArchiveView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobsViewModel}"><s:JobsView /></DataTemplate>
|
||||
<!-- Jobs › Scheduled, the second tab of Jobs (owner review 2, R10). -->
|
||||
|
||||
@@ -10,6 +10,9 @@ public enum SectionKey
|
||||
|
||||
/// <summary>One sequence analysed, edited and rendered step by step (owner review 1, R7; formerly Sequence).</summary>
|
||||
Edit,
|
||||
|
||||
/// <summary>Every render of this PC, of the server and of the workspace in one list (owner review 1, R9; Ctrl+4).</summary>
|
||||
Videos,
|
||||
Archive,
|
||||
Jobs,
|
||||
Server,
|
||||
|
||||
@@ -44,12 +44,14 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Sequence = new SequenceViewModel(this);
|
||||
// The workspace's clean-up never takes the project open in Edit (phase 5c).
|
||||
services.Workspace.OpenProject = () => Sequence.OpenProjectId;
|
||||
Videos = new VideosViewModel(this);
|
||||
Archive = new ArchiveViewModel(this);
|
||||
Jobs = new JobsViewModel(this);
|
||||
Server = new ServerViewModel(this);
|
||||
Settings = new SettingsViewModel(this);
|
||||
About = new AboutViewModel(this);
|
||||
TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
|
||||
// Videos after Edit (owner review 1, R9, decision 20): Ctrl+4, then Archive, Jobs and Server at Ctrl+5…7.
|
||||
TopSections = [Library, Import, Sequence, Videos, Archive, Jobs, Server];
|
||||
// About is the last page of Settings (owner review 2, R5): Settings alone docks at the bottom of the rail.
|
||||
BottomSections = [Settings];
|
||||
foreach (var section in AllSections) section.InCollapsedRail = _isRailCollapsed;
|
||||
@@ -57,7 +59,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Library.IsSelected = true;
|
||||
Library.PropertyChanged += OnCurrentChanged;
|
||||
|
||||
// The rail and its shortcuts (Ctrl+1…6, Ctrl+,) navigate only while no first-run dialog covers the shell.
|
||||
// The rail and its shortcuts (Ctrl+1…7, Ctrl+,) navigate only while no first-run dialog covers the shell.
|
||||
NavigateCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is SectionViewModel s) Navigate(s.Key);
|
||||
@@ -75,6 +77,10 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
public LibraryViewModel Library { get; }
|
||||
public ImportViewModel Import { get; }
|
||||
public SequenceViewModel Sequence { get; }
|
||||
|
||||
/// <summary>The videos library (owner review 1, R9).</summary>
|
||||
public VideosViewModel Videos { get; }
|
||||
|
||||
public ArchiveViewModel Archive { get; }
|
||||
public JobsViewModel Jobs { get; }
|
||||
public ServerViewModel Server { get; }
|
||||
@@ -194,6 +200,16 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
/// </summary>
|
||||
internal void KeepSequence(Guid? sequenceId) => CurrentSequenceId = sequenceId;
|
||||
|
||||
/// <summary>
|
||||
/// Opens Videos, narrowed to the renders of <paramref name="sequenceId"/> (the Export footer's "Videos (n)" and the Render
|
||||
/// menu's "Videos"), or to every render with null; <paramref name="title"/> names the sequence in its filter chip.
|
||||
/// </summary>
|
||||
public void OpenVideos(Guid? sequenceId = null, string? title = null)
|
||||
{
|
||||
Videos.ShowSequence(sequenceId, title);
|
||||
Navigate(SectionKey.Videos);
|
||||
}
|
||||
|
||||
/// <summary>Closes the first-run overlay for good.</summary>
|
||||
public void CompleteWelcome()
|
||||
{
|
||||
@@ -362,6 +378,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
Jobs.Dispose();
|
||||
Library.Dispose();
|
||||
Import.Dispose();
|
||||
Videos.Dispose();
|
||||
Archive.Dispose();
|
||||
Server.Dispose();
|
||||
Settings.Dispose();
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<UserControl x:Class="Chronos.App.Videos.VideoPlayerPane"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui">
|
||||
<!--
|
||||
The player pane of the Videos section (decision 21): the render played in-process (Windows Media Foundation through
|
||||
MediaElement), a still, GIF or APNG shown as an image, and "Cannot play here" when Windows cannot decode the file, with
|
||||
Show in folder still offered. Pictures stay left to right in a right-to-left window.
|
||||
-->
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="14">
|
||||
<DockPanel>
|
||||
<DockPanel DockPanel.Dock="Top">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Command="{Binding CloseCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.ClosePlayer}" AutomationProperties.Name="{l:Loc Videos.Player.Close}" VerticalAlignment="Top" />
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Title}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
|
||||
<TextBlock Text="{Binding DetailsText}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" FlowDirection="LeftToRight" HorizontalAlignment="Left"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Margin="0,12,0,0">
|
||||
<Button Content="{l:Loc Videos.Play}" ui:ButtonIcon.Glyph="{StaticResource Icon.Play}" Click="OnReplay" ToolTip="{l:Loc Tooltips.Videos.Play}"
|
||||
Visibility="{Binding IsVideo, Converter={StaticResource BoolToVisibility}}" Margin="0,0,8,0" />
|
||||
<Button Content="{l:Loc Videos.ShowInFolder}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}" Command="{Binding ShowInFolderCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" ToolTipService.ShowOnDisabled="True" />
|
||||
</StackPanel>
|
||||
<Border Margin="0,12,0,0" CornerRadius="6" Background="{DynamicResource Brush.Preview}" MinHeight="180" ClipToBounds="True" FlowDirection="LeftToRight">
|
||||
<Grid>
|
||||
<MediaElement x:Name="Media" Source="{Binding Source}" LoadedBehavior="Manual" UnloadedBehavior="Close" Stretch="Uniform" MediaFailed="OnMediaFailed"
|
||||
MediaOpened="OnMediaOpened" Visibility="{Binding IsVideo, Converter={StaticResource BoolToVisibility}}" Loaded="OnMediaLoaded"
|
||||
AutomationProperties.Name="{Binding Title}" />
|
||||
<Image Source="{Binding Image}" Stretch="Uniform" Visibility="{Binding IsImage, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{Binding Title}" />
|
||||
<ui:EmptyState Message="{Binding CannotPlayText}" ToolTip="{Binding CannotPlayToolTip}" Visibility="{Binding CannotPlay, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>The player pane: plays the render in-process and falls back to "Cannot play here" when Windows cannot decode it.</summary>
|
||||
public partial class VideoPlayerPane : UserControl
|
||||
{
|
||||
public VideoPlayerPane()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += (_, _) => Start();
|
||||
}
|
||||
|
||||
private VideoPlayerViewModel? Model => DataContext as VideoPlayerViewModel;
|
||||
|
||||
private void OnMediaLoaded(object sender, RoutedEventArgs e) => Start();
|
||||
|
||||
/// <summary>A new render plays from its start.</summary>
|
||||
private void Start()
|
||||
{
|
||||
if (!Media.IsLoaded) return;
|
||||
if (Model is { IsVideo: true })
|
||||
{
|
||||
Media.Position = TimeSpan.Zero;
|
||||
Media.Play();
|
||||
}
|
||||
else
|
||||
{
|
||||
Media.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReplay(object sender, RoutedEventArgs e) => Start();
|
||||
|
||||
private void OnMediaOpened(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// A file that opens without a video stream (audio alone, a codec Windows lacks) shows nothing: said as such.
|
||||
if (!Media.HasVideo) Model?.MediaFailed(null);
|
||||
}
|
||||
|
||||
private void OnMediaFailed(object? sender, ExceptionRoutedEventArgs e) => Model?.MediaFailed(e.ErrorException);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>What the player pane shows (decision 21).</summary>
|
||||
public enum VideoPlayerMode
|
||||
{
|
||||
/// <summary>A video file, played in-process by Windows Media Foundation (WPF <c>MediaElement</c>).</summary>
|
||||
Video,
|
||||
|
||||
/// <summary>A still, a GIF or an APNG, shown as an image.</summary>
|
||||
Image,
|
||||
|
||||
/// <summary>Windows cannot decode the file here (or it is not on this PC): "Cannot play here", Show in folder stays.</summary>
|
||||
CannotPlay,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The right-hand player pane of the Videos section (decision 21): one render played in-process, never handed to another
|
||||
/// program (BRIEF §8.6). A file Windows cannot decode says so, and Show in folder stays offered.
|
||||
/// </summary>
|
||||
public sealed class VideoPlayerViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>The longest edge an image is decoded at for the pane.</summary>
|
||||
public const int ImageEdge = 1600;
|
||||
|
||||
private VideoPlayerMode _mode;
|
||||
private ImageSource? _image;
|
||||
|
||||
public VideoPlayerViewModel(VideoEntry entry, ICommand close, ICommand showInFolder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
Entry = entry;
|
||||
CloseCommand = close;
|
||||
ShowInFolderCommand = showInFolder;
|
||||
_mode = ModeOf(entry);
|
||||
if (_mode == VideoPlayerMode.Video) Source = new Uri(entry.LocalPath!, UriKind.Absolute);
|
||||
}
|
||||
|
||||
public VideoEntry Entry { get; }
|
||||
|
||||
public string Title => Entry.Title;
|
||||
|
||||
public string DetailsText => VideoText.Details(Entry);
|
||||
|
||||
public VideoPlayerMode Mode
|
||||
{
|
||||
get => _mode;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _mode, value)) return;
|
||||
OnPropertyChanged(nameof(IsVideo));
|
||||
OnPropertyChanged(nameof(IsImage));
|
||||
OnPropertyChanged(nameof(CannotPlay));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsVideo => _mode == VideoPlayerMode.Video;
|
||||
public bool IsImage => _mode == VideoPlayerMode.Image;
|
||||
public bool CannotPlay => _mode == VideoPlayerMode.CannotPlay;
|
||||
|
||||
/// <summary>The video file the <c>MediaElement</c> plays; null for an image or a file that cannot play.</summary>
|
||||
public Uri? Source { get; }
|
||||
|
||||
/// <summary>The still (or the first frame of a GIF or APNG), decoded at <see cref="ImageEdge"/> once asked for.</summary>
|
||||
public ImageSource? Image
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_image is null && _mode == VideoPlayerMode.Image) _image = LoadImage();
|
||||
return _image;
|
||||
}
|
||||
}
|
||||
|
||||
public string CannotPlayText => Loc.L("Videos.Player.CannotPlay");
|
||||
|
||||
public string CannotPlayToolTip => Loc.L("Tooltips.Videos.CannotPlay");
|
||||
|
||||
public ICommand CloseCommand { get; }
|
||||
|
||||
public ICommand ShowInFolderCommand { get; }
|
||||
|
||||
/// <summary>Show in folder applies: the file is on this PC.</summary>
|
||||
public bool CanShowInFolder => Entry.HasLocalFile;
|
||||
|
||||
/// <summary>The <c>MediaElement</c> could not open or decode the file (a codec Windows lacks, HEVC without its extension).</summary>
|
||||
public void MediaFailed(Exception? error)
|
||||
{
|
||||
Log.Info("videos", $"{Entry.FileName} cannot play here: {error?.Message}");
|
||||
Mode = VideoPlayerMode.CannotPlay;
|
||||
}
|
||||
|
||||
/// <summary>How <paramref name="entry"/> plays: as a video or an image when its file is here and of a kind the pane shows, else not.</summary>
|
||||
public static VideoPlayerMode ModeOf(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (!entry.HasLocalFile || entry.Kind == RenderKind.Sequence || !File.Exists(entry.LocalPath)) return VideoPlayerMode.CannotPlay;
|
||||
if (entry.Kind == RenderKind.Still || VideoSources.ShowsAsImage(entry.LocalPath)) return VideoPlayerMode.Image;
|
||||
return VideoSources.PlaysAsVideo(entry.LocalPath) ? VideoPlayerMode.Video : VideoPlayerMode.CannotPlay;
|
||||
}
|
||||
|
||||
private BitmapSource? LoadImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(Entry.LocalPath!);
|
||||
var image = new BitmapImage();
|
||||
image.BeginInit();
|
||||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||||
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
|
||||
if (Entry.Width >= Entry.Height) image.DecodePixelWidth = Math.Min(ImageEdge, Math.Max(1, Entry.Width));
|
||||
else image.DecodePixelHeight = Math.Min(ImageEdge, Math.Max(1, Entry.Height));
|
||||
image.StreamSource = stream;
|
||||
image.EndInit();
|
||||
image.Freeze();
|
||||
return image;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
Log.Info("videos", $"{Entry.FileName} cannot be shown here: {ex.Message}");
|
||||
Mode = VideoPlayerMode.CannotPlay;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Media;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>The words of the Videos section: kinds, states, details and the errors of the videos library.</summary>
|
||||
public static class VideoText
|
||||
{
|
||||
/// <summary>"Videos", "Stills", "Image sequences"; a newer kind as it is.</summary>
|
||||
public static string Kind(string kind) => kind switch
|
||||
{
|
||||
RenderKind.Video => Loc.L("Videos.Kind.Video"),
|
||||
RenderKind.Still => Loc.L("Videos.Kind.Still"),
|
||||
RenderKind.Sequence => Loc.L("Videos.Kind.Sequence"),
|
||||
_ => kind,
|
||||
};
|
||||
|
||||
/// <summary>"0:42" for a video; empty for a still, which has no duration.</summary>
|
||||
public static string Duration(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
return entry.Kind == RenderKind.Still || entry.DurationSeconds <= 0 ? string.Empty : Formatting.Elapsed(TimeSpan.FromSeconds(entry.DurationSeconds));
|
||||
}
|
||||
|
||||
/// <summary>"3840×2160 · HEVC" (the size and codec, left to right in every language).</summary>
|
||||
public static string Format(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var size = entry.Width > 0 && entry.Height > 0
|
||||
? entry.Width.ToString(CultureInfo.InvariantCulture) + "×" + entry.Height.ToString(CultureInfo.InvariantCulture)
|
||||
: string.Empty;
|
||||
var codec = VideoSources.CodecText(entry.Codec);
|
||||
return size.Length == 0 ? codec : codec.Length == 0 ? size : size + Loc.Separator + codec;
|
||||
}
|
||||
|
||||
/// <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 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>
|
||||
public static IReadOnlyList<CardStatus> States(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var states = new List<CardStatus>();
|
||||
if (entry.Missing) states.Add(new CardStatus(StatusKind.Warning, Loc.L("Videos.State.Missing"), Loc.L("Tooltips.Videos.Missing")));
|
||||
if (entry.IsUnsent) states.Add(new CardStatus(StatusKind.Queued, Loc.L("Videos.State.NotSent"), Loc.L("Tooltips.Videos.NotSent")));
|
||||
else if (entry.IsLocal && entry.IsOnServer) states.Add(new CardStatus(StatusKind.Synced, Loc.L("Videos.State.HereAndServer"), Loc.L("Tooltips.Videos.HereAndServer")));
|
||||
else if (entry.IsLocal) states.Add(new CardStatus(StatusKind.Done, Loc.L("Videos.State.Here"), Loc.L("Tooltips.Videos.Here")));
|
||||
else if (entry.IsOnServer) states.Add(new CardStatus(StatusKind.Remote, Loc.L("Videos.State.OnServer"), Loc.L("Tooltips.Videos.OnServer")));
|
||||
if (entry.Copies.Count > 0)
|
||||
{
|
||||
states.Add(new CardStatus(StatusKind.Rendered, Loc.L("Videos.State.Copied"),
|
||||
Loc.L("Tooltips.Videos.Copied", string.Join(Environment.NewLine, entry.Copies.Select(Formatting.LeftToRight)))));
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
/// <summary>The sentence of a videos library error (<see cref="VideoErrors"/>); <paramref name="name"/> is the file or sequence it is about.</summary>
|
||||
public static string Error(VideoLibraryException ex, string? name = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
return ex.Code switch
|
||||
{
|
||||
VideoErrors.FolderUnset => Loc.L("Errors.Videos.FolderUnset"),
|
||||
VideoErrors.FolderInvalid => Loc.L("Errors.Videos.FolderInsideArchive"),
|
||||
VideoErrors.PlanChanged => Loc.L("Errors.Videos.Fingerprint"),
|
||||
VideoErrors.HashMismatch => Loc.L("Errors.Videos.TrashMismatch"),
|
||||
VideoErrors.NoSpace => Loc.L("Errors.Videos.NoSpace", name ?? string.Empty),
|
||||
VideoErrors.SequenceGone => Loc.L("Errors.Videos.SequenceGone", name ?? string.Empty),
|
||||
VideoErrors.Busy => Loc.L("Errors.Videos.Busy", name ?? string.Empty),
|
||||
_ => ex.Message,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Why a copy into <paramref name="problem"/>'s folder is refused (a tooltip), from <see cref="VideosFolders.Problem"/>.</summary>
|
||||
public static string FolderReason(string problem) =>
|
||||
problem == VideoErrors.FolderUnset ? Loc.L("Tooltips.Videos.FolderUnset") : Loc.L("Errors.Videos.FolderInsideArchive");
|
||||
|
||||
/// <summary>
|
||||
/// Play's tooltip for <paramref name="entry"/>: what Play does for a file on this PC; for a video only the server holds,
|
||||
/// that it plays here once copied to this PC; for a file that is gone, that it is missing.
|
||||
/// </summary>
|
||||
public static string PlayToolTip(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (entry.HasLocalFile) return Loc.L("Tooltips.Videos.Play");
|
||||
if (entry.Missing) return Loc.L("Tooltips.Videos.Missing");
|
||||
return entry.IsOnServer ? Loc.L("Tooltips.Videos.PlayServer") : Loc.L("Tooltips.Videos.Play");
|
||||
}
|
||||
|
||||
/// <summary>"In use by a job", "Not found".</summary>
|
||||
public static string BlockReason(string reason) =>
|
||||
reason == VideoBlockReasons.Busy ? Loc.L("Videos.Blocked.Busy") : Loc.L("Videos.Blocked.NotFound");
|
||||
}
|
||||
|
||||
/// <summary>One render of the Videos section, as a card of the grid or a row of the list.</summary>
|
||||
public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
|
||||
{
|
||||
private bool _isSelected;
|
||||
private ImageSource? _poster;
|
||||
private bool _posterRequested;
|
||||
|
||||
public VideoEntry Entry { get; } = entry;
|
||||
|
||||
public string Title => Entry.Title;
|
||||
|
||||
/// <summary>The preset name (and the project's, when a project was rendered).</summary>
|
||||
public string Subtitle => Entry.ProjectName is { Length: > 0 } project ? Entry.PresetName + Loc.Separator + project : Entry.PresetName;
|
||||
|
||||
public string DetailsText => VideoText.Details(Entry);
|
||||
public string FormatText => VideoText.Format(Entry);
|
||||
public string DurationText => VideoText.Duration(Entry);
|
||||
public string SizeText => Formatting.Bytes(Entry.Bytes);
|
||||
public string DateText => Formatting.Date(Entry.Created) + " " + Formatting.TimeOfDay(Entry.Created);
|
||||
public string KindText => VideoText.Kind(Entry.Kind);
|
||||
public IReadOnlyList<CardStatus> States { get; } = VideoText.States(entry);
|
||||
|
||||
/// <summary>The card's and the row's tooltip: what it is, then how to select it.</summary>
|
||||
public string ToolTip => Entry.IsUnsent ? Loc.L("Tooltips.Videos.WorkspaceRow") : Loc.L("Tooltips.Videos.Select");
|
||||
|
||||
/// <summary>
|
||||
/// Play's tooltip: what it does, or why it waits (a server's video plays here once it is copied to this PC, a file
|
||||
/// that is gone plays nowhere).
|
||||
/// </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);
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isSelected, value)) SelectionChanged?.Invoke(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence's cover, or the still itself; null until loaded (<see cref="RequestPoster"/>).</summary>
|
||||
public ImageSource? Poster
|
||||
{
|
||||
get => _poster;
|
||||
internal set => Set(ref _poster, value);
|
||||
}
|
||||
|
||||
/// <summary>The card came on screen: its poster is loaded once by <see cref="PosterRequested"/>.</summary>
|
||||
public void RequestPoster()
|
||||
{
|
||||
if (_posterRequested || _poster is not null) return;
|
||||
_posterRequested = true;
|
||||
PosterRequested?.Invoke(this);
|
||||
}
|
||||
|
||||
internal event Action<VideoRowViewModel>? SelectionChanged;
|
||||
|
||||
internal event Action<VideoRowViewModel>? PosterRequested;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a delete of videos (decision 17) in the words of its confirmation: what goes into the trash (and how
|
||||
/// 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>
|
||||
/// <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);
|
||||
|
||||
/// <summary>The bytes that move into the trash.</summary>
|
||||
public long Bytes => (Local?.Bytes ?? 0) + (Server?.Bytes ?? 0);
|
||||
|
||||
/// <summary>The renders left where they are.</summary>
|
||||
public int Blocked => (Local?.Blocked.Count ?? 0) + (Server?.Blocked.Count ?? 0);
|
||||
|
||||
/// <summary>The renders whose file is missing: only their entry goes.</summary>
|
||||
public int Missing => (Local?.Items.Count(i => i.Missing) ?? 0) + (Server?.Items.Count(i => i.Missing) ?? 0);
|
||||
|
||||
/// <summary>The lines of what goes, then of what stays and why (<see cref="DeletePlans.ListedLines"/> each, the rest counted).</summary>
|
||||
public IReadOnlyList<string> Lines()
|
||||
{
|
||||
var goes = (Local?.Items.Select(i => (i.SequenceTitle, i.FileName, i.Render.Bytes, i.Missing)) ?? [])
|
||||
.Concat(Server?.Items.Select(i => (i.SequenceTitle, FileName: i.FileName ?? string.Empty, i.Bytes, i.Missing)) ?? []).ToList();
|
||||
var lines = new List<string>();
|
||||
foreach (var (title, file, bytes, missing) in goes.Take(DeletePlans.ListedLines))
|
||||
{
|
||||
lines.Add(Loc.L("Archive.Delete.Line", title, Formatting.LeftToRight(file),
|
||||
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 => (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()
|
||||
{
|
||||
if (Count == 0) return null;
|
||||
var message = Loc.L("Videos.Delete.Summary", Formatting.Count(Count), Formatting.Bytes(Bytes)) + Environment.NewLine + Loc.L("Videos.Delete.CopiesStay");
|
||||
if (Missing > 0) message += Environment.NewLine + Loc.L("Videos.Delete.Missing");
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Videos.Delete.Title"),
|
||||
Message = message,
|
||||
Detail = string.Join(Environment.NewLine, Lines()),
|
||||
IsDetailMonospaced = false,
|
||||
DetailToolTip = Loc.L("Tooltips.Videos.Delete"),
|
||||
SafeText = Loc.L("Archive.Delete.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
|
||||
ActionText = Loc.L("Videos.Delete.Confirm"),
|
||||
ActionToolTip = Loc.L("Tooltips.Videos.DeleteConfirm"),
|
||||
IsDestructive = true,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Videos;
|
||||
|
||||
/// <summary>Which renders the Videos section lists (its Source filter, owner review 1, R9).</summary>
|
||||
public enum VideoSourceFilter
|
||||
{
|
||||
All,
|
||||
|
||||
/// <summary>Renders whose file is on this PC: the archive's and the workspace's not sent yet.</summary>
|
||||
Local,
|
||||
|
||||
/// <summary>Renders the signed-in server holds.</summary>
|
||||
Server,
|
||||
|
||||
/// <summary>Renders of workspace projects not at their home yet.</summary>
|
||||
NotSent,
|
||||
}
|
||||
|
||||
/// <summary>How the signed-in server's videos reach the Videos section.</summary>
|
||||
public enum VideoServerState
|
||||
{
|
||||
/// <summary>Listed with this PC's.</summary>
|
||||
Available,
|
||||
|
||||
/// <summary>Not signed in to a server: this PC's videos alone.</summary>
|
||||
SignedOut,
|
||||
|
||||
/// <summary>The server's Chronos has no videos library (no <see cref="ServerCapabilities.Videos"/>): this PC's videos alone.</summary>
|
||||
Old,
|
||||
|
||||
/// <summary>The server did not answer: this PC's videos alone.</summary>
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One render of the Videos section (decision 20): the archive's, the signed-in server's and the workspace's renders merged
|
||||
/// by render id, with where its file is. WPF-free.
|
||||
/// </summary>
|
||||
public sealed record VideoEntry
|
||||
{
|
||||
public required Guid Id { get; init; }
|
||||
public required Guid SequenceId { get; init; }
|
||||
|
||||
/// <summary>The sequence's display title.</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
public required string PresetName { get; init; }
|
||||
public string? Codec { get; init; }
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
public double Fps { get; init; }
|
||||
public double DurationSeconds { get; init; }
|
||||
public long Bytes { get; init; }
|
||||
public DateTimeOffset Created { get; init; }
|
||||
|
||||
/// <summary><see cref="RenderKind.Video"/>, <see cref="RenderKind.Still"/>, <see cref="RenderKind.Sequence"/> or a newer kind as it is.</summary>
|
||||
public required string Kind { get; init; }
|
||||
|
||||
/// <summary>The file (or folder) name.</summary>
|
||||
public required string FileName { get; init; }
|
||||
|
||||
/// <summary>The file (or folder) on this PC; null for a render the server alone holds.</summary>
|
||||
public string? LocalPath { get; init; }
|
||||
|
||||
/// <summary>The render is in this PC's index (its archive).</summary>
|
||||
public bool IsLocal { get; init; }
|
||||
|
||||
/// <summary>The signed-in server holds the render.</summary>
|
||||
public bool IsOnServer { get; init; }
|
||||
|
||||
/// <summary>A workspace render not at its home yet: read-only here (Play, Show in folder, Send).</summary>
|
||||
public bool IsUnsent { get; init; }
|
||||
|
||||
/// <summary>The file is not where it was recorded (here, or on the server for a render the server alone holds).</summary>
|
||||
public bool Missing { get; init; }
|
||||
|
||||
/// <summary>The workspace project of an unsent render; null otherwise.</summary>
|
||||
public Guid? WorkspaceProjectId { get; init; }
|
||||
|
||||
/// <summary>The workspace project's home is a server.</summary>
|
||||
public bool WorkspaceServerHome { get; init; }
|
||||
|
||||
/// <summary>The project rendered; null for a render of the sequence's settings.</summary>
|
||||
public string? ProjectName { get; init; }
|
||||
|
||||
/// <summary>The paths of its verified copies in videos folders (of this PC and of the server).</summary>
|
||||
public IReadOnlyList<string> Copies { get; init; } = [];
|
||||
|
||||
/// <summary>The render's file is on this PC.</summary>
|
||||
public bool HasLocalFile => LocalPath is not null && !Missing;
|
||||
|
||||
/// <summary>The year the render was made (UTC, as the server filters it).</summary>
|
||||
public int Year => Created.UtcDateTime.Year;
|
||||
}
|
||||
|
||||
/// <summary>The filters and the order of the Videos section; every member optional, combined with "and".</summary>
|
||||
public sealed record VideoFilter
|
||||
{
|
||||
public static VideoFilter None { get; } = new();
|
||||
|
||||
/// <summary>Text in the title, the preset name or the file name (any case).</summary>
|
||||
public string? Text { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="RenderKind"/>; null for every kind.</summary>
|
||||
public string? Kind { get; init; }
|
||||
|
||||
/// <summary>A codec as recorded; null for every codec.</summary>
|
||||
public string? Codec { get; init; }
|
||||
|
||||
public int? Year { get; init; }
|
||||
|
||||
public VideoSourceFilter Source { get; init; }
|
||||
|
||||
/// <summary>The renders of one sequence (the Export footer's and the Render menu's "Videos").</summary>
|
||||
public Guid? SequenceId { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="VideoSorts"/>; null for newest first.</summary>
|
||||
public string? Sort { get; init; }
|
||||
|
||||
/// <summary>Anything narrows the list (the order alone does not).</summary>
|
||||
public bool IsFiltered => !string.IsNullOrWhiteSpace(Text) || Kind is not null || Codec is not null || Year is not null || Source != VideoSourceFilter.All
|
||||
|| SequenceId is not null;
|
||||
|
||||
public bool Matches(VideoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (SequenceId is { } sequence && entry.SequenceId != sequence) return false;
|
||||
if (Kind is { } kind && !string.Equals(entry.Kind, kind, StringComparison.Ordinal)) return false;
|
||||
if (Codec is { } codec && !string.Equals(entry.Codec, codec, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (Year is { } year && entry.Year != year) return false;
|
||||
if (Source switch
|
||||
{
|
||||
VideoSourceFilter.Local => !entry.IsLocal && !entry.IsUnsent,
|
||||
VideoSourceFilter.Server => !entry.IsOnServer,
|
||||
VideoSourceFilter.NotSent => !entry.IsUnsent,
|
||||
_ => false,
|
||||
})
|
||||
return false;
|
||||
if (Text?.Trim() is { Length: > 0 } text
|
||||
&& !entry.Title.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
&& !entry.PresetName.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
&& !entry.FileName.Contains(text, StringComparison.CurrentCultureIgnoreCase))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The entries that match, in the chosen order (ties newest first, then by id, so the order is stable).</summary>
|
||||
public IReadOnlyList<VideoEntry> Apply(IEnumerable<VideoEntry> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
var matching = entries.Where(Matches);
|
||||
IOrderedEnumerable<VideoEntry> ordered = Sort switch
|
||||
{
|
||||
VideoSorts.Oldest => matching.OrderBy(e => e.Created),
|
||||
VideoSorts.Largest => matching.OrderByDescending(e => e.Bytes).ThenByDescending(e => e.Created),
|
||||
VideoSorts.Title => matching.OrderBy(e => e.Title, StringComparer.CurrentCultureIgnoreCase).ThenByDescending(e => e.Created),
|
||||
_ => matching.OrderByDescending(e => e.Created),
|
||||
};
|
||||
return [.. ordered.ThenBy(e => e.Id)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in server's videos library (<c>/api/v1/videos</c>) as the Videos section uses it; one connection, disposed
|
||||
/// after use. Tests substitute a fake server.
|
||||
/// </summary>
|
||||
public interface IRemoteVideos : IDisposable
|
||||
{
|
||||
/// <summary>One page of the server's videos.</summary>
|
||||
Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The dry run of deleting <paramref name="ids"/> into the server's trash.</summary>
|
||||
Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The delete as planned; a changed plan is a 409 <c>plan_changed</c>.</summary>
|
||||
Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Queues the copy of <paramref name="ids"/> into the server's videos folder.</summary>
|
||||
Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary><see cref="IRemoteVideos"/> over a signed-in <see cref="ChronosClient"/>, which it owns.</summary>
|
||||
public sealed class ChronosRemoteVideos(ChronosClient client) : IRemoteVideos
|
||||
{
|
||||
public Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) => client.ListVideosAsync(query, cancellationToken);
|
||||
|
||||
public Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) =>
|
||||
client.PlanDeleteVideosAsync(ids, cancellationToken);
|
||||
|
||||
public Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default) =>
|
||||
client.DeleteVideosAsync(ids, fingerprint, cancellationToken);
|
||||
|
||||
public Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => client.CopyVideosAsync(ids, cancellationToken);
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in server as the Videos section sees it: whether its videos can be listed, a connection when they can, and
|
||||
/// what the account may do there.
|
||||
/// </summary>
|
||||
/// <param name="Connect">A new connection to the server; null unless <paramref name="State"/> is <see cref="VideoServerState.Available"/>.</param>
|
||||
public sealed record VideoServer(VideoServerState State, Func<IRemoteVideos>? Connect = null, bool CanEdit = false, bool CanDelete = false)
|
||||
{
|
||||
public static VideoServer SignedOut { get; } = new(VideoServerState.SignedOut);
|
||||
|
||||
/// <summary>The server of <paramref name="info"/> for an account of <paramref name="permissions"/>: <see cref="VideoServerState.Old"/> without the capability.</summary>
|
||||
public static VideoServer Of(ServerInfo? info, long permissions, Func<IRemoteVideos> connect)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connect);
|
||||
if (info is null) return SignedOut;
|
||||
if (!info.Capabilities.Contains(ServerCapabilities.Videos)) return new VideoServer(VideoServerState.Old);
|
||||
return new VideoServer(VideoServerState.Available, connect, (permissions & (long)Permissions.Edit) != 0, (permissions & (long)Permissions.Delete) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reading and merging the three places renders are (decision 20): the archive, the signed-in server, the workspace.</summary>
|
||||
public static class VideoSources
|
||||
{
|
||||
/// <summary>Pages read from one place at most (500 videos each).</summary>
|
||||
public const int MaxPages = 40;
|
||||
|
||||
/// <summary>Extensions the player pane plays with Windows Media Foundation (decision 21).</summary>
|
||||
private static readonly string[] VideoExtensions = [".mp4", ".m4v", ".mov", ".wmv", ".avi", ".mkv", ".webm"];
|
||||
|
||||
/// <summary>Extensions the player pane shows as an image (stills, GIF, APNG).</summary>
|
||||
private static readonly string[] ImageExtensions = [".png", ".apng", ".jpg", ".jpeg", ".tif", ".tiff", ".gif", ".bmp"];
|
||||
|
||||
/// <summary>A render of this PC's index.</summary>
|
||||
public static VideoEntry FromLocal(VideoItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var render = item.Render;
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = render.Id,
|
||||
SequenceId = render.SequenceId,
|
||||
Title = item.SequenceTitle,
|
||||
PresetName = render.PresetName,
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = render.Bytes,
|
||||
Created = render.Created,
|
||||
Kind = item.Kind,
|
||||
FileName = item.FileName,
|
||||
LocalPath = item.FullPath,
|
||||
IsLocal = true,
|
||||
Missing = item.Missing,
|
||||
ProjectName = item.ProjectName,
|
||||
Copies = [.. item.Copies.Select(c => c.Path)],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A render of the signed-in server.</summary>
|
||||
public static VideoEntry FromServer(VideoDto video)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(video);
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = video.Id,
|
||||
SequenceId = video.SequenceId,
|
||||
Title = video.SequenceTitle,
|
||||
PresetName = video.PresetName,
|
||||
Codec = video.Codec,
|
||||
Width = video.Width,
|
||||
Height = video.Height,
|
||||
Fps = video.Fps,
|
||||
DurationSeconds = video.DurationSeconds,
|
||||
Bytes = video.Bytes,
|
||||
Created = video.Created,
|
||||
Kind = video.Kind,
|
||||
FileName = video.FileName ?? video.PresetName,
|
||||
IsOnServer = true,
|
||||
Missing = video.State == VideoStates.Missing,
|
||||
ProjectName = video.ProjectName,
|
||||
Copies = [.. video.Copies.Select(c => c.Path)],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A workspace render not sent yet (<paramref name="path"/> its file on this PC).</summary>
|
||||
public static VideoEntry FromWorkspace(WorkspaceRenderEntry render, WorkspaceEntry project, string path, bool exists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(render);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return new VideoEntry
|
||||
{
|
||||
Id = render.RenderId,
|
||||
SequenceId = project.SequenceId,
|
||||
Title = project.SequenceTitle,
|
||||
PresetName = render.PresetName,
|
||||
Codec = render.Codec,
|
||||
Width = render.Width,
|
||||
Height = render.Height,
|
||||
Fps = render.Fps,
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Bytes = render.Size,
|
||||
Created = render.Rendered,
|
||||
Kind = RenderKind.Of(null, render.Codec, render.Fps, render.DurationSeconds),
|
||||
FileName = Path.GetFileName(path.TrimEnd('/', '\\')),
|
||||
LocalPath = path,
|
||||
IsUnsent = true,
|
||||
Missing = !exists,
|
||||
WorkspaceProjectId = project.ProjectId,
|
||||
WorkspaceServerHome = project.IsServerHome,
|
||||
ProjectName = project.Name,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One list, one entry per render id: this PC's renders first (their file here), marked when the server holds the same
|
||||
/// render too ("Here and on server"); the server's other renders; then the workspace's renders that neither holds yet.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<VideoEntry> Merge(IEnumerable<VideoEntry> local, IEnumerable<VideoEntry> server, IEnumerable<VideoEntry> workspace)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
ArgumentNullException.ThrowIfNull(server);
|
||||
ArgumentNullException.ThrowIfNull(workspace);
|
||||
var merged = new Dictionary<Guid, VideoEntry>();
|
||||
var order = new List<Guid>();
|
||||
foreach (var entry in local)
|
||||
{
|
||||
if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
|
||||
}
|
||||
foreach (var entry in server)
|
||||
{
|
||||
if (merged.TryGetValue(entry.Id, out var here))
|
||||
{
|
||||
merged[entry.Id] = here with { IsOnServer = true, Copies = [.. here.Copies.Concat(entry.Copies).Distinct(StringComparer.OrdinalIgnoreCase)] };
|
||||
}
|
||||
else if (merged.TryAdd(entry.Id, entry))
|
||||
{
|
||||
order.Add(entry.Id);
|
||||
}
|
||||
}
|
||||
// A workspace render the archive or the server holds was sent: the library's entry stands for it.
|
||||
foreach (var entry in workspace)
|
||||
{
|
||||
if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
|
||||
}
|
||||
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)
|
||||
{
|
||||
if (library is null || !library.IsAvailable) return [];
|
||||
var entries = new List<VideoEntry>();
|
||||
string? cursor = null;
|
||||
for (var page = 0; page < MaxPages; page++)
|
||||
{
|
||||
var read = await library.ListAsync(new VideoQuery { Cursor = cursor, Limit = VideoQuery.MaxLimit }, cancellationToken).ConfigureAwait(false);
|
||||
entries.AddRange(read.Items.Select(FromLocal));
|
||||
cursor = read.Next;
|
||||
if (cursor is null) break;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>Every render of the server (<see cref="MaxPages"/> pages at most).</summary>
|
||||
public static async Task<IReadOnlyList<VideoEntry>> ReadServerAsync(IRemoteVideos remote, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
var entries = new List<VideoEntry>();
|
||||
string? cursor = null;
|
||||
for (var page = 0; page < MaxPages; page++)
|
||||
{
|
||||
var read = await remote.ListAsync(new VideoQueryDto(Cursor: cursor, Limit: VideoQuery.MaxLimit), cancellationToken).ConfigureAwait(false);
|
||||
entries.AddRange(read.Items.Select(FromServer));
|
||||
cursor = read.Next;
|
||||
if (cursor is null) break;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The workspace renders not at their home yet, of every project whose ledger reads (one that does not is logged and
|
||||
/// skipped: it never hides the others).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceStore store, IEnumerable<WorkspaceEntry> projects)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(projects);
|
||||
var entries = new List<VideoEntry>();
|
||||
foreach (var project in projects.Where(p => p.IsReadable))
|
||||
{
|
||||
try
|
||||
{
|
||||
var folder = store.Project(project.ProjectId);
|
||||
foreach (var render in folder.ReadRenders().Unsent)
|
||||
{
|
||||
var path = folder.ExportFile(render.File);
|
||||
entries.Add(FromWorkspace(render, project, path, File.Exists(path) || Directory.Exists(path)));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>"H.264", "HEVC", "PNG"… for a codec as recorded; the recorded name in capitals for one this Chronos does not know.</summary>
|
||||
public static string CodecText(string? codec) =>
|
||||
codec is null or { Length: 0 } ? string.Empty
|
||||
: Enum.TryParse<VideoCodec>(codec, ignoreCase: true, out var known) && Enum.IsDefined(known) ? ExportNaming.CodecLabel(known)
|
||||
: codec.ToUpperInvariant();
|
||||
|
||||
/// <summary>The player pane can play the file as a video.</summary>
|
||||
public static bool PlaysAsVideo(string? path) => path is not null && VideoExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The player pane shows the file as an image.</summary>
|
||||
public static bool ShowsAsImage(string? path) => path is not null && ImageExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>The videos folder of this PC (decision 15): where Copy to folder puts renders.</summary>
|
||||
public static class VideosFolders
|
||||
{
|
||||
/// <summary><c>%USERPROFILE%\Videos\Chronos</c>; null when Windows names no videos folder (decision 15, Q12).</summary>
|
||||
public static string? Default()
|
||||
{
|
||||
var videos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
|
||||
return string.IsNullOrEmpty(videos) ? null : Path.Combine(videos, "Chronos");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder, as one of <see cref="VideoErrors"/>: unset, or inside (or
|
||||
/// equal to) the archive root or the workspace; null when it can.
|
||||
/// </summary>
|
||||
public static string? Problem(string? folder, params string?[] refused)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(folder)) return VideoErrors.FolderInvalid;
|
||||
full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
foreach (var root in refused)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||
string other;
|
||||
try
|
||||
{
|
||||
other = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (string.Equals(full, other, StringComparison.OrdinalIgnoreCase)
|
||||
|| full.StartsWith(other + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -126,6 +126,37 @@ public static class ExportNaming
|
||||
return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, taken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of a still (owner review 1, R8, "Save frame"): the expanded <paramref name="template"/>, " - " and the 1-based
|
||||
/// number of source frame <paramref name="frameIndex"/> in at least four digits, "2026-09-28 Harbour - 4K HEVC - 0123".
|
||||
/// </summary>
|
||||
public static string StillName(string template, ExportNameContext context, int frameIndex)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(frameIndex);
|
||||
var name = Expand(template, context).Name;
|
||||
return PathTemplate.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{name} - {frameIndex + 1:D4}"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Full path of a still inside <paramref name="folder"/>: <see cref="StillName"/> plus the image extension of the codec
|
||||
/// (one file, never a folder), made unique like <see cref="OutputPath(string, string, ExportNameContext, Func{string, bool}?)"/>.
|
||||
/// </summary>
|
||||
public static string StillPath(string folder, string template, ExportNameContext context, int frameIndex, Func<string, bool>? taken = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
return Unique(folder, StillName(template, context, frameIndex), VideoCodecInfo.FileExtension(context.Codec), taken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Path of a still of a project's export: <see cref="ExportSettings.Folder"/> or, when unset, the sequence's exports
|
||||
/// folder, named by <see cref="ExportSettings.NameTemplate"/> and the frame number.
|
||||
/// </summary>
|
||||
public static string StillPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, int frameIndex, Func<string, bool>? taken = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return StillPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, frameIndex, taken);
|
||||
}
|
||||
|
||||
/// <summary>"name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists or is <paramref name="taken"/>.</summary>
|
||||
public static string Unique(string folder, string name, string extension, Func<string, bool>? taken = null)
|
||||
{
|
||||
|
||||
@@ -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)) ?? ".";
|
||||
|
||||
@@ -164,6 +164,86 @@ public sealed record Render
|
||||
|
||||
/// <summary>The project version rendered; null for a render of the sequence's settings.</summary>
|
||||
public Guid? ProjectVersionId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Lower-case hex SHA-256 of a single-file render (owner review 1, R9), hashed when it is recorded; null for an image
|
||||
/// sequence's folder (verified file by file when copied) and for a render recorded before migration 0010, hashed the
|
||||
/// first time it is copied, deleted or restored.
|
||||
/// </summary>
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// What the render is beyond its codec (<see cref="RenderKind"/>): null for a video or an image sequence (told apart by
|
||||
/// <see cref="Codec"/>), <see cref="RenderKind.Still"/> for one frame saved as an image. A text, so a newer Chronos can add
|
||||
/// kinds.
|
||||
/// </summary>
|
||||
public string? Kind { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The values of <see cref="Render.Kind"/> and of the videos library's kinds (owner review 1, R9).</summary>
|
||||
public static class RenderKind
|
||||
{
|
||||
/// <summary>A video file (MP4, AVI, GIF, APNG): <see cref="Render.Kind"/> null and a video codec.</summary>
|
||||
public const string Video = "video";
|
||||
|
||||
/// <summary>A folder of numbered images: <see cref="Render.Kind"/> null and an image-sequence codec.</summary>
|
||||
public const string Sequence = "sequence";
|
||||
|
||||
/// <summary>One frame saved as one image ("Save frame"): fps 0 and duration 0.</summary>
|
||||
public const string Still = "still";
|
||||
|
||||
/// <summary>
|
||||
/// The library kind of a render: its <see cref="Render.Kind"/> when set (a kind of a newer Chronos as it is), else
|
||||
/// <see cref="Sequence"/> for an image-sequence codec and <see cref="Video"/> otherwise.
|
||||
/// </summary>
|
||||
public static string Of(string? kind, string? codec) =>
|
||||
kind is { Length: > 0 } ? kind
|
||||
: codec is { } c && c.EndsWith("sequence", StringComparison.OrdinalIgnoreCase) ? Sequence
|
||||
: Video;
|
||||
|
||||
/// <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, render.Fps, render.DurationSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A verified copy of a render in a videos folder (owner review 1, R9; <c>render_copies</c>): recorded once the copy matched
|
||||
/// its render. There is no link to <c>renders</c>, so the copy of a server render downloaded to a PC is recorded too, and a
|
||||
/// copy outlives its render's deletion (copies are the user's files; Chronos never deletes them).
|
||||
/// </summary>
|
||||
public sealed record RenderCopy
|
||||
{
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>The render copied (of this index, or of the server it was downloaded from).</summary>
|
||||
public required Guid RenderId { get; init; }
|
||||
|
||||
/// <summary>Absolute path of the copy (a file, or a folder for an image sequence).</summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>Lower-case hex SHA-256 the copy was verified against; null for an image sequence's folder (verified per file).</summary>
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
public long Bytes { get; init; }
|
||||
|
||||
public DateTimeOffset CopiedAt { get; init; }
|
||||
|
||||
/// <summary>The user (server) or the PC (desktop) that copied it.</summary>
|
||||
public string? CopiedBy { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -123,6 +123,12 @@ public enum JobKind
|
||||
/// source kept until every file is verified (owner review 2, R8, phase 5c); stored as 23.
|
||||
/// </summary>
|
||||
WorkspaceMove = 23,
|
||||
|
||||
/// <summary>
|
||||
/// Copies renders into the videos folder (owner review 1, R9), each copy hash-verified against its render before it takes
|
||||
/// its name, the render itself never touched; on the desktop a server-only render is downloaded into it; stored as 24.
|
||||
/// </summary>
|
||||
VideoCopy = 24,
|
||||
}
|
||||
|
||||
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
|
||||
|
||||
@@ -278,6 +278,116 @@ public sealed record ExportSettings
|
||||
/// </summary>
|
||||
public bool SyncToServer { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How the rendered frames play (owner review 1, R8): direction, loops, fades and a hold at the end, applied by
|
||||
/// <c>OutputProgram</c> between the plan and the encoder. Null at the default (forward, once, no fades, no hold), which
|
||||
/// <see cref="ProjectSettings.ToJson"/> writes whenever <see cref="PlaybackSettings.IsDefault"/>. Settings format 3. It
|
||||
/// lives in the export, so the batch presets of the export inherit it.
|
||||
/// </summary>
|
||||
public PlaybackSettings? Playback { get; init; }
|
||||
|
||||
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The directions of <see cref="PlaybackSettings.Direction"/>: texts, not an enum, so a newer Chronos can add one.</summary>
|
||||
public static class PlaybackDirection
|
||||
{
|
||||
/// <summary>The plan as it is (the default, never written).</summary>
|
||||
public const string Forward = "forward";
|
||||
|
||||
/// <summary>The plan from its last frame to its first.</summary>
|
||||
public const string Reverse = "reverse";
|
||||
|
||||
/// <summary>Forward, then backward without repeating the turning frame.</summary>
|
||||
public const string Boomerang = "boomerang";
|
||||
|
||||
/// <summary>The directions this Chronos renders, in the order the editor offers them.</summary>
|
||||
public static IReadOnlyList<string> All { get; } = [Forward, Reverse, Boomerang];
|
||||
|
||||
/// <summary>Whether this Chronos renders <paramref name="direction"/> (null is forward); the comparison ignores case.</summary>
|
||||
public static bool IsKnown(string? direction) =>
|
||||
direction is null || All.Contains(direction, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The playback of an export (owner review 1, R8; settings format 3): each member null at its default and omitted then, so
|
||||
/// a project that sets nothing here keeps its text. Values out of range are clamped when rendered
|
||||
/// (<see cref="EffectiveLoops"/> and the other effective values); a direction this Chronos does not know renders forward
|
||||
/// with the warning <c>Export.Render.DirectionUnknown</c>.
|
||||
/// </summary>
|
||||
public sealed record PlaybackSettings
|
||||
{
|
||||
/// <summary>The most passes a video plays (<see cref="Loops"/>).</summary>
|
||||
public const int MaxLoops = 10;
|
||||
|
||||
/// <summary>The longest fade in or out, in seconds.</summary>
|
||||
public const double MaxFadeSeconds = 30;
|
||||
|
||||
/// <summary>The longest hold of the last frame, in seconds.</summary>
|
||||
public const double MaxHoldSeconds = 60;
|
||||
|
||||
/// <summary><see cref="PlaybackDirection"/>: null for forward; "reverse" or "boomerang".</summary>
|
||||
public string? Direction { get; init; }
|
||||
|
||||
/// <summary>Passes of the whole video, 1..<see cref="MaxLoops"/>; null for 1.</summary>
|
||||
public int? Loops { get; init; }
|
||||
|
||||
/// <summary>Seconds of fade from black at the start, 0..<see cref="MaxFadeSeconds"/>; null for 0.</summary>
|
||||
public double? FadeIn { get; init; }
|
||||
|
||||
/// <summary>Seconds of fade to black at the end, 0..<see cref="MaxFadeSeconds"/>; null for 0.</summary>
|
||||
public double? FadeOut { get; init; }
|
||||
|
||||
/// <summary>Seconds the last frame stays on screen after the last pass, 0..<see cref="MaxHoldSeconds"/>; null for 0.</summary>
|
||||
public double? HoldEnd { get; init; }
|
||||
|
||||
/// <summary>The direction rendered: forward for null and for a direction this Chronos does not know.</summary>
|
||||
[JsonIgnore]
|
||||
public string EffectiveDirection => Direction is { } d && PlaybackDirection.IsKnown(d) ? d.ToLowerInvariant() : PlaybackDirection.Forward;
|
||||
|
||||
/// <summary>The passes rendered, clamped to 1..<see cref="MaxLoops"/>.</summary>
|
||||
[JsonIgnore]
|
||||
public int EffectiveLoops => Math.Clamp(Loops ?? 1, 1, MaxLoops);
|
||||
|
||||
/// <summary>The fade in rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
|
||||
[JsonIgnore]
|
||||
public double EffectiveFadeIn => Seconds(FadeIn, MaxFadeSeconds);
|
||||
|
||||
/// <summary>The fade out rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
|
||||
[JsonIgnore]
|
||||
public double EffectiveFadeOut => Seconds(FadeOut, MaxFadeSeconds);
|
||||
|
||||
/// <summary>The hold rendered, in seconds, clamped (a value that is not finite counts as 0).</summary>
|
||||
[JsonIgnore]
|
||||
public double EffectiveHoldEnd => Seconds(HoldEnd, MaxHoldSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// The playback renders as the default (forward, once, no fades, no hold) and holds nothing a newer Chronos wrote: the
|
||||
/// export then writes no playback at all. A direction this Chronos does not know is not the default (it is a newer
|
||||
/// Chronos's), so it is kept and raises the format.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public bool IsDefault =>
|
||||
(Direction is null || string.Equals(Direction, PlaybackDirection.Forward, StringComparison.OrdinalIgnoreCase))
|
||||
&& EffectiveLoops == 1 && EffectiveFadeIn == 0 && EffectiveFadeOut == 0 && EffectiveHoldEnd == 0 && Extra is not { Count: > 0 };
|
||||
|
||||
/// <summary>
|
||||
/// The same playback with each member at its default (forward, 1, 0) set to null, so it is not written; values out of
|
||||
/// range and unknown directions stay as they are. <see cref="ProjectSettings.ToJson"/> writes the playback this way.
|
||||
/// </summary>
|
||||
public PlaybackSettings Normalized() => this with
|
||||
{
|
||||
Direction = string.Equals(Direction, PlaybackDirection.Forward, StringComparison.OrdinalIgnoreCase) ? null : Direction,
|
||||
Loops = Loops == 1 ? null : Loops,
|
||||
FadeIn = FadeIn == 0 ? null : FadeIn,
|
||||
FadeOut = FadeOut == 0 ? null : FadeOut,
|
||||
HoldEnd = HoldEnd == 0 ? null : HoldEnd,
|
||||
};
|
||||
|
||||
private static double Seconds(double? value, double max) => value is { } v && double.IsFinite(v) ? Math.Clamp(v, 0, max) : 0;
|
||||
|
||||
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
@@ -323,7 +433,10 @@ public sealed record LookSettings
|
||||
public sealed record ProjectSettings
|
||||
{
|
||||
/// <summary>The highest settings format this Chronos reads; a project of a higher one opens read-only (<see cref="IsNewerFormat"/>).</summary>
|
||||
public const int CurrentVersion = 2;
|
||||
public const int CurrentVersion = 3;
|
||||
|
||||
/// <summary>The format of a project whose export plays other than forward once without fades (<see cref="ExportSettings.Playback"/>).</summary>
|
||||
public const int PlaybackVersion = 3;
|
||||
|
||||
/// <summary>The format of a project that uses nothing added since the first one, which most projects are written as.</summary>
|
||||
public const int BaseVersion = 1;
|
||||
@@ -377,11 +490,13 @@ public sealed record ProjectSettings
|
||||
public bool IsNewerFormat => Version > CurrentVersion;
|
||||
|
||||
/// <summary>
|
||||
/// The lowest settings format that renders these settings the same: 2 while a turn, mirror, flip or straighten
|
||||
/// The lowest settings format that renders these settings the same: 3 while the export's playback is not the default
|
||||
/// (<see cref="PlaybackSettings.IsDefault"/>), 2 while a turn, mirror, flip or straighten
|
||||
/// (<see cref="CameraSettings.IsOriented"/>) or a look other than the identity is set, otherwise <see cref="BaseVersion"/>.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public int RequiredFormat => Camera.IsOriented || Look is { IsIdentity: false } ? 2 : BaseVersion;
|
||||
public int RequiredFormat =>
|
||||
Export.Playback is { IsDefault: false } ? PlaybackVersion : Camera.IsOriented || Look is { IsIdentity: false } ? 2 : BaseVersion;
|
||||
|
||||
/// <summary>The format <see cref="ToJson"/> writes: <see cref="RequiredFormat"/>, or a newer format read, kept as it is.</summary>
|
||||
[JsonIgnore]
|
||||
@@ -389,9 +504,16 @@ public sealed record ProjectSettings
|
||||
|
||||
/// <summary>
|
||||
/// The settings as JSON, stamped with <see cref="WrittenFormat"/>. Every serialisation of a project goes through here,
|
||||
/// so the version written always matches the members used.
|
||||
/// so the version written always matches the members used; a playback at its default is written as none, and each of
|
||||
/// its members at its default is left out (<see cref="PlaybackSettings.Normalized"/>).
|
||||
/// </summary>
|
||||
public string ToJson() => JsonSerializer.Serialize(Version == WrittenFormat ? this : this with { Version = WrittenFormat }, ProjectJson.Default.ProjectSettings);
|
||||
public string ToJson()
|
||||
{
|
||||
var written = Export.Playback is { } playback
|
||||
? this with { Export = Export with { Playback = playback.IsDefault ? null : playback.Normalized() } }
|
||||
: this;
|
||||
return JsonSerializer.Serialize(written.Version == WrittenFormat ? written : written with { Version = WrittenFormat }, ProjectJson.Default.ProjectSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a project; members missing from <paramref name="json"/> (an API client's partial settings, an older file)
|
||||
@@ -821,4 +943,5 @@ public sealed record ProjectSettings
|
||||
UseStringEnumConverter = true,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(ProjectSettings))]
|
||||
[JsonSerializable(typeof(PlaybackSettings))]
|
||||
internal sealed partial class ProjectJson : JsonSerializerContext;
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Color;
|
||||
@@ -58,4 +60,27 @@ public static class FrameFinish
|
||||
if (look is { IsIdentity: false } && LookFilter.IsKnown(look.Filter)) LookFilter.Apply(frame, look.Filter, Strength(look));
|
||||
if (knee is > 0 and < 1 and var k) ExposureProcessor.Apply(frame, 0, null, k);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fade to and from black of the output program (owner review 1, R8; <see cref="ProgramEntry.Gain"/>): every sample
|
||||
/// of the finished linear-light <paramref name="frame"/> multiplied by <paramref name="gain"/>, in place. It runs after
|
||||
/// <see cref="Apply"/>, so neither the look nor the knee sees a darkened frame. A gain of 1 or more (or not finite)
|
||||
/// leaves the frame as it is; 0 or less makes it black.
|
||||
/// </summary>
|
||||
public static void Fade(ImageBuffer frame, double gain)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
if (!double.IsFinite(gain) || gain >= 1) return;
|
||||
var data = frame.Data;
|
||||
if (gain <= 0)
|
||||
{
|
||||
data.Clear();
|
||||
return;
|
||||
}
|
||||
var factor = (float)gain;
|
||||
var vectors = MemoryMarshal.Cast<float, Vector<float>>(data);
|
||||
var scale = new Vector<float>(factor);
|
||||
for (var i = 0; i < vectors.Length; i++) vectors[i] *= scale;
|
||||
for (var i = vectors.Length * Vector<float>.Count; i < data.Length; i++) data[i] *= factor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>One frame the encoder receives, in emission order (<see cref="OutputProgram"/>).</summary>
|
||||
/// <param name="PlanIndex">The frame of <see cref="RenderPlan.Frames"/> rendered for it.</param>
|
||||
/// <param name="Duration90k">How long it shows, on the 90 kHz clock: the planned frame's duration, a share of it (a held
|
||||
/// frame split per slot inside a fade), or longer (the hold at the end).</param>
|
||||
/// <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>
|
||||
/// <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,
|
||||
/// with the fade gain of each, from the export's <see cref="PlaybackSettings"/>. Reverse is the plan backwards; a boomerang
|
||||
/// is forward then backward without repeating the turning frame; loops repeat the pass (a boomerang's later passes start at
|
||||
/// its second frame, so the joint is not doubled); the hold extends the last emitted frame; fades longer than half of the
|
||||
/// program are scaled to fit (warning <see cref="FadesShortenedWarning"/>). Every pass is rendered again, so the render
|
||||
/// time grows with <see cref="Count"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Durations stay on the plan's 90 kHz values: a pass sums to the plan's duration and the hold is a whole number of output
|
||||
/// periods, so constant-rate outputs keep their grid. The fade gain of an entry is taken at its start inside the fade in and
|
||||
/// at its end inside the fade out, so the first and the last emitted frames are black.
|
||||
/// </remarks>
|
||||
public sealed class OutputProgram
|
||||
{
|
||||
/// <summary>Warning key: the fades were longer than half of the program and were scaled to fit.</summary>
|
||||
public const string FadesShortenedWarning = "Export.Render.FadesShortened";
|
||||
|
||||
/// <summary>Warning key: the playback names a direction this Chronos does not know ({0}); the video plays forward.</summary>
|
||||
public const string DirectionUnknownWarning = "Export.Render.DirectionUnknown";
|
||||
|
||||
/// <summary>Warning key: a boomerang is not rendered with star trails; the video plays forward.</summary>
|
||||
public const string BoomerangStackWarning = "Export.Render.BoomerangStack";
|
||||
|
||||
private OutputProgram(IReadOnlyList<ProgramEntry> entries, IReadOnlyList<RenderWarning> warnings)
|
||||
{
|
||||
Entries = entries;
|
||||
Warnings = warnings;
|
||||
long total = 0;
|
||||
foreach (var entry in entries) total += entry.Duration90k;
|
||||
Duration90k = total;
|
||||
}
|
||||
|
||||
/// <summary>The emitted frames, in order.</summary>
|
||||
public IReadOnlyList<ProgramEntry> Entries { get; }
|
||||
|
||||
/// <summary>Frames the encoder receives (and the render renders).</summary>
|
||||
public int Count => Entries.Count;
|
||||
|
||||
/// <summary>Exact total duration on the 90 kHz clock, holds included.</summary>
|
||||
public long Duration90k { get; }
|
||||
|
||||
/// <summary>The duration in seconds.</summary>
|
||||
public double DurationSeconds => Duration90k / 90000.0;
|
||||
|
||||
/// <summary>What the program changed of the playback asked for (fades shortened, an unknown direction played forward).</summary>
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; }
|
||||
|
||||
/// <summary>The program of <paramref name="plan"/>'s frames played as <paramref name="playback"/> says (null: forward once).</summary>
|
||||
public static OutputProgram Build(RenderPlan plan, PlaybackSettings? playback, Rational frameRate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return Build(plan.Frames, playback, frameRate);
|
||||
}
|
||||
|
||||
/// <summary>The program of the planned <paramref name="frames"/> played as <paramref name="playback"/> says (null: forward once).</summary>
|
||||
/// <param name="frameRate">The output frame rate: the grid a held frame is split on inside a fade.</param>
|
||||
public static OutputProgram Build(IReadOnlyList<PlannedFrame> frames, PlaybackSettings? playback, Rational frameRate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
if (frameRate.Numerator <= 0 || frameRate.Denominator <= 0) throw new ArgumentOutOfRangeException(nameof(frameRate));
|
||||
var warnings = new List<RenderWarning>();
|
||||
if (playback?.Direction is { } unknown && !PlaybackDirection.IsKnown(unknown)) warnings.Add(new RenderWarning(DirectionUnknownWarning, unknown));
|
||||
if (frames.Count == 0) return new OutputProgram([], warnings);
|
||||
playback ??= new PlaybackSettings();
|
||||
|
||||
// The passes: plan indices in emission order, each frame for its planned duration.
|
||||
var entries = new List<ProgramEntry>(frames.Count * playback.EffectiveLoops);
|
||||
var direction = frames.Count == 1 ? PlaybackDirection.Forward : playback.EffectiveDirection;
|
||||
for (var pass = 0; pass < playback.EffectiveLoops; pass++)
|
||||
{
|
||||
switch (direction)
|
||||
{
|
||||
case PlaybackDirection.Reverse:
|
||||
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, 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, pass));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The hold: whole output periods added to the last frame.
|
||||
if (playback.EffectiveHoldEnd > 0)
|
||||
{
|
||||
var periods = long.Max(1, (long)double.Round(playback.EffectiveHoldEnd * frameRate.Value));
|
||||
var last = entries[^1];
|
||||
entries[^1] = last with { Duration90k = last.Duration90k + RenderPlan.TicksAt(frameRate, periods) };
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
foreach (var entry in entries) total += entry.Duration90k;
|
||||
var fadeIn = (long)double.Round(playback.EffectiveFadeIn * 90000);
|
||||
var fadeOut = (long)double.Round(playback.EffectiveFadeOut * 90000);
|
||||
if (fadeIn + fadeOut == 0) return new OutputProgram(entries, warnings);
|
||||
if (fadeIn + fadeOut > total / 2)
|
||||
{
|
||||
// Both fades shrink by the same factor until together they take half of the program.
|
||||
var scale = (double)(total / 2) / (fadeIn + fadeOut);
|
||||
fadeIn = (long)double.Floor(fadeIn * scale);
|
||||
fadeOut = (long)double.Floor(fadeOut * scale);
|
||||
warnings.Add(new RenderWarning(FadesShortenedWarning));
|
||||
}
|
||||
return new OutputProgram(Faded(entries, total, fadeIn, fadeOut, frameRate), warnings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entries with the fade gains: an entry that reaches into a fade is split into its output periods (a held frame
|
||||
/// otherwise keeps one gain for its whole time), and each part takes the gain of its own time.
|
||||
/// </summary>
|
||||
private static List<ProgramEntry> Faded(List<ProgramEntry> entries, long total, long fadeIn, long fadeOut, Rational frameRate)
|
||||
{
|
||||
var period = 90000.0 * frameRate.Denominator / frameRate.Numerator;
|
||||
var faded = new List<ProgramEntry>(entries.Count);
|
||||
long start = 0;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var end = start + entry.Duration90k;
|
||||
if (start >= fadeIn && end <= total - fadeOut)
|
||||
{
|
||||
faded.Add(entry);
|
||||
start = end;
|
||||
continue;
|
||||
}
|
||||
var parts = int.Max(1, (int)double.Round(entry.Duration90k / period));
|
||||
long previous = 0;
|
||||
for (var part = 1; part <= parts; part++)
|
||||
{
|
||||
var boundary = (long)double.Round((double)entry.Duration90k * part / parts);
|
||||
if (boundary == previous) continue;
|
||||
faded.Add(entry with { Duration90k = boundary - previous, Gain = Gain(start + previous, start + boundary, total, fadeIn, fadeOut) });
|
||||
previous = boundary;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return faded;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The linear gain of the time from <paramref name="start"/> to <paramref name="end"/>: the fade in at its start, the fade
|
||||
/// out at its end, the darker of the two, through the sRGB curve so the ramp looks even.
|
||||
/// </summary>
|
||||
private static double Gain(long start, long end, long total, long fadeIn, long fadeOut)
|
||||
{
|
||||
var level = 1.0;
|
||||
if (fadeIn > 0 && start < fadeIn) level = double.Min(level, (double)start / fadeIn);
|
||||
if (fadeOut > 0 && end > total - fadeOut) level = double.Min(level, (double)(total - end) / fadeOut);
|
||||
return level >= 1 ? 1 : ColorSpace.SrgbToLinear(double.Clamp(level, 0, 1));
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,18 @@ public sealed record RenderInput
|
||||
}
|
||||
|
||||
/// <summary>One output of a render: the resolved export values and where the file (or sequence folder) goes.</summary>
|
||||
/// <param name="OutputPath">Full path of the file, or of the folder for image sequences (see <see cref="ExportNaming.OutputPath"/>).</param>
|
||||
public sealed record RenderTarget(ResolvedExport Export, string OutputPath);
|
||||
/// <param name="OutputPath">Full path of the file, or of the folder for image sequences (see <see cref="ExportNaming.OutputPath"/>);
|
||||
/// for a still, the image file (<see cref="ExportNaming.StillPath(string, string, ExportNameContext, int, Func{string, bool}?)"/>).</param>
|
||||
/// <param name="StillFrame">
|
||||
/// Owner review 1, R8, "Save frame": the source frame saved as one image (PNG, JPEG or TIFF, <see cref="RenderRules.StillCodecs"/>)
|
||||
/// at the export's output size, with every correction and look, without stacking, interpolation, motion blur or playback;
|
||||
/// null renders the video.
|
||||
/// </param>
|
||||
public sealed record RenderTarget(ResolvedExport Export, string OutputPath, int? StillFrame = null)
|
||||
{
|
||||
/// <summary>The target saves one frame as an image (<see cref="StillFrame"/>).</summary>
|
||||
public bool IsStill => StillFrame is not null;
|
||||
}
|
||||
|
||||
/// <summary>Tuning of a render that is not part of the project.</summary>
|
||||
public sealed record RenderOptions
|
||||
|
||||
@@ -16,7 +16,9 @@ namespace Chronos.Core.Render;
|
||||
/// <see cref="IRenderFrameSource"/> at the working size; per-frame exposure corrections (deflicker, holy grail, white
|
||||
/// balance, regions) are applied; stabilisation, virtual camera and crop are resampled once to the output size;
|
||||
/// fractional positions are synthesised from the bidirectional flow; motion blur follows the flow with shutter-angle
|
||||
/// composition; stacking (median, mean, star trails) and the finish (look, then highlight knee: <see cref="FrameFinish"/>) come last, then the encoder. Encoding of a
|
||||
/// composition; stacking (median, mean, star trails) and the finish (look, then highlight knee, then the fade:
|
||||
/// <see cref="FrameFinish"/>) come last, then the encoder. Frames are rendered in the order of the <see cref="OutputProgram"/>
|
||||
/// (direction, loops, hold, fades); a still target renders one source frame into one image. Encoding of a
|
||||
/// frame overlaps the processing of the next. Cancellation and failures leave no output behind (sessions delete their
|
||||
/// partial files on dispose) and every background task is awaited, so exceptions surface exactly once.
|
||||
/// </summary>
|
||||
@@ -60,7 +62,7 @@ public sealed class RenderPipeline(IReadOnlyList<IVideoEncoderProvider> encoders
|
||||
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
|
||||
throw new RenderException(notice.Key, $"No encoder can produce {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args);
|
||||
}
|
||||
if (setup.Plan.Frames.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
|
||||
if (setup.Still is null && setup.Program.Count == 0) throw new RenderException("Export.Render.NoFrames", "Every frame is excluded.");
|
||||
using var run = new RenderRun(input, corrections, setup, options, progress);
|
||||
return await run.ExecuteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -98,12 +100,16 @@ 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;
|
||||
private readonly RenderOptions _options;
|
||||
private readonly IProgress<RenderProgress>? _progress;
|
||||
private readonly RenderPlan _plan;
|
||||
private readonly OutputProgram _program;
|
||||
private readonly RenderGeometry _geometry;
|
||||
private readonly PreparedFrameCache _prepared;
|
||||
private readonly FlowCache _flows = new(2);
|
||||
@@ -129,6 +135,7 @@ internal sealed class RenderRun : IDisposable
|
||||
_options = options;
|
||||
_progress = progress;
|
||||
_plan = setup.Plan;
|
||||
_program = setup.Program;
|
||||
_geometry = setup.Geometry;
|
||||
_prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames));
|
||||
_workingEdge = _geometry.WorkingLongEdge;
|
||||
@@ -148,14 +155,19 @@ internal sealed class RenderRun : IDisposable
|
||||
{
|
||||
var settings = _setup.Encoder.Settings;
|
||||
_clock.Start();
|
||||
Log.Info(RenderPipeline.LogCategory, $"Rendering {_plan.Frames.Count} frames ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
|
||||
if (_setup.Still is { } still)
|
||||
Log.Info(RenderPipeline.LogCategory, $"Saving frame {still.From} as {settings.Codec} {settings.Width}×{settings.Height}: {settings.OutputPath}");
|
||||
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, _plan.Frames.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
|
||||
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _program.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
|
||||
session.Complete();
|
||||
ignored = [.. session.Ignored];
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -170,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,
|
||||
@@ -178,8 +192,9 @@ internal sealed class RenderRun : IDisposable
|
||||
Width = settings.Width,
|
||||
Height = settings.Height,
|
||||
FrameRate = settings.FrameRate,
|
||||
DurationSeconds = _plan.DurationSeconds,
|
||||
FrameCount = _plan.Frames.Count,
|
||||
DurationSeconds = _setup.Still is null ? _program.DurationSeconds : 0,
|
||||
FrameCount = _program.Count,
|
||||
Kind = _setup.Still is null ? null : Model.RenderKind.Still,
|
||||
Bytes = RenderResult.SizeOf(settings.OutputPath),
|
||||
EncoderName = session.EncoderName,
|
||||
Hardware = session.IsHardware,
|
||||
@@ -199,6 +214,13 @@ internal sealed class RenderRun : IDisposable
|
||||
|
||||
private async Task RenderFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_setup.Still is { } still)
|
||||
{
|
||||
// Save frame: the one source frame, whole, with every correction and the finish; no stacking and no playback.
|
||||
var picture = await RenderFrameAsync(still, blur: false, cancellationToken).ConfigureAwait(false);
|
||||
await EmitAsync(picture, new ProgramEntry(0, still.Duration90k, 1)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var stack = _input.Project.Stack;
|
||||
switch (stack.Mode)
|
||||
{
|
||||
@@ -206,58 +228,132 @@ internal sealed class RenderRun : IDisposable
|
||||
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case StackSetting.StarTrails:
|
||||
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
|
||||
{
|
||||
foreach (var planned in _plan.Frames)
|
||||
await RenderProgramAsync(async (entry, token) =>
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) trails.Add(frame);
|
||||
await EmitAsync(trails.Result!.Clone(), planned.Duration90k).ConfigureAwait(false);
|
||||
}
|
||||
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:
|
||||
foreach (var planned in _plan.Frames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var frame = await RenderFrameAsync(planned, _setup.MotionBlur, cancellationToken).ConfigureAwait(false);
|
||||
await EmitAsync(frame, planned.Duration90k).ConfigureAwait(false);
|
||||
}
|
||||
await RenderProgramAsync((entry, token) => RenderFrameAsync(_plan.Frames[entry.PlanIndex], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Centred median/mean window: output k is emitted once frame k + half has been pushed (the tail reuses the
|
||||
/// last full window).</summary>
|
||||
/// <summary>
|
||||
/// Emits the program's entries in order, each rendered by <paramref name="render"/> from its plan index. Consecutive
|
||||
/// 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<ProgramEntry, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = _program.Entries;
|
||||
ImageBuffer? kept = null;
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var entry = entries[i];
|
||||
var frame = kept ?? await render(entry, cancellationToken).ConfigureAwait(false);
|
||||
kept = null;
|
||||
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex && entries[i + 1].Pass == entry.Pass)
|
||||
{
|
||||
try
|
||||
{
|
||||
kept = frame.Clone();
|
||||
}
|
||||
catch
|
||||
{
|
||||
frame.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
await EmitAsync(frame, entry).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
kept?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Median/mean stacks, one centred window per plan frame whatever the program's order: frame k combines plan frames
|
||||
/// k − half … k + half, cut to the plan at the start and shifted inside it at the end (as a forward render always did).
|
||||
/// Stepping to the next frame in the direction the program travels pushes one frame; a turn or the shrinking window at the
|
||||
/// plan's start fills the window again.
|
||||
/// </summary>
|
||||
private async Task RenderWindowStackAsync(StackSettings stack, CancellationToken cancellationToken)
|
||||
{
|
||||
var window = int.Max(1, stack.Length);
|
||||
var half = (window - 1) / 2;
|
||||
var last = _plan.Frames.Count - 1;
|
||||
using var stacker = new TemporalStacker(window, stack.Mode == StackSetting.Median ? StackMode.Median : StackMode.Mean);
|
||||
var pending = new Queue<PlannedFrame>();
|
||||
foreach (var planned in _plan.Frames)
|
||||
// Plan indices in the stacker, oldest (the next evicted) first.
|
||||
var held = new List<int>(window + 1);
|
||||
var previous = -1;
|
||||
await RenderProgramAsync(async (entry, token) =>
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using (var frame = await RenderFrameAsync(planned, blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame);
|
||||
pending.Enqueue(planned);
|
||||
if (pending.Count > half) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
while (pending.Count > 0) await EmitStackAsync(stacker, pending.Dequeue(), cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
previous = index;
|
||||
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
|
||||
try
|
||||
{
|
||||
stacker.Render(output, token);
|
||||
return output;
|
||||
}
|
||||
catch
|
||||
{
|
||||
output.Dispose();
|
||||
throw;
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task EmitStackAsync(TemporalStacker stacker, PlannedFrame planned, CancellationToken cancellationToken)
|
||||
/// <summary>Makes the stacker hold exactly plan frames <paramref name="lo"/>…<paramref name="hi"/>.</summary>
|
||||
private async Task WindowAsync(TemporalStacker stacker, List<int> held, int lo, int hi, bool forward, CancellationToken cancellationToken)
|
||||
{
|
||||
var output = new ImageBuffer(_geometry.OutputWidth, _geometry.OutputHeight, 3, clear: false);
|
||||
try
|
||||
bool Holds(IEnumerable<int> frames) => frames.Count() == hi - lo + 1 && frames.All(i => i >= lo && i <= hi);
|
||||
if (Holds(held)) return;
|
||||
var missing = Enumerable.Range(lo, hi - lo + 1).Where(i => !held.Contains(i)).ToList();
|
||||
if (missing.Count == 1 && Holds(held.Skip(held.Count == stacker.Window ? 1 : 0).Append(missing[0])))
|
||||
{
|
||||
stacker.Render(output, cancellationToken);
|
||||
await PushAsync(stacker, held, missing[0], cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch
|
||||
{
|
||||
output.Dispose();
|
||||
throw;
|
||||
}
|
||||
await EmitAsync(output, planned.Duration90k).ConfigureAwait(false);
|
||||
stacker.Clear();
|
||||
held.Clear();
|
||||
// Pushed in the direction of travel, so the next step evicts the frame it leaves behind.
|
||||
for (var k = 0; k <= hi - lo; k++) await PushAsync(stacker, held, forward ? lo + k : hi - k, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task PushAsync(TemporalStacker stacker, List<int> held, int index, CancellationToken cancellationToken)
|
||||
{
|
||||
using (var frame = await RenderFrameAsync(_plan.Frames[index], blur: false, cancellationToken).ConfigureAwait(false)) stacker.Push(frame);
|
||||
held.Add(index);
|
||||
if (held.Count > stacker.Window) held.RemoveAt(0);
|
||||
}
|
||||
|
||||
/// <summary>The picture of one planned frame at the output size (a new buffer owned by the caller).</summary>
|
||||
@@ -400,14 +496,19 @@ internal sealed class RenderRun : IDisposable
|
||||
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
|
||||
}
|
||||
|
||||
/// <summary>Finishes the frame (look, then knee) and hands it to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
|
||||
private async Task EmitAsync(ImageBuffer frame, long duration90k)
|
||||
/// <summary>
|
||||
/// Finishes the frame (look, then knee, then the entry's fade) and hands it to the encoder for the entry's duration once
|
||||
/// the previous frame is encoded; owns <paramref name="frame"/>.
|
||||
/// </summary>
|
||||
private async Task EmitAsync(ImageBuffer frame, ProgramEntry entry)
|
||||
{
|
||||
ImageBuffer? preview = null;
|
||||
var duration90k = entry.Duration90k;
|
||||
try
|
||||
{
|
||||
await FlushEncodingAsync().ConfigureAwait(false);
|
||||
FrameFinish.Apply(frame, _look, _knee);
|
||||
if (entry.Gain < 1) FrameFinish.Fade(frame, entry.Gain);
|
||||
_done++;
|
||||
if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge);
|
||||
}
|
||||
@@ -424,8 +525,8 @@ internal sealed class RenderRun : IDisposable
|
||||
if (_progress is not null)
|
||||
{
|
||||
var fps = Fps();
|
||||
_progress.Report(new RenderProgress(RenderStage.Rendering, _done, _plan.Frames.Count, fps, _clock.Elapsed,
|
||||
fps > 0 ? TimeSpan.FromSeconds((_plan.Frames.Count - _done) / fps) : null, preview));
|
||||
_progress.Report(new RenderProgress(RenderStage.Rendering, _done, _program.Count, fps, _clock.Elapsed,
|
||||
fps > 0 ? TimeSpan.FromSeconds((_program.Count - _done) / fps) : null, preview));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -17,11 +17,19 @@ public sealed record RenderResult
|
||||
public required int Width { get; init; }
|
||||
public required int Height { get; init; }
|
||||
public required Rational FrameRate { get; init; }
|
||||
|
||||
/// <summary>The video's duration, holds included (<see cref="OutputProgram.DurationSeconds"/>); 0 for a still.</summary>
|
||||
public required double DurationSeconds { get; init; }
|
||||
|
||||
/// <summary>Output pictures rendered (held frames count once).</summary>
|
||||
/// <summary>
|
||||
/// Pictures the encoder received (<see cref="OutputProgram.Count"/>): every pass and loop, a held frame once, or once per
|
||||
/// output period inside a fade; 1 for a still.
|
||||
/// </summary>
|
||||
public required int FrameCount { get; init; }
|
||||
|
||||
/// <summary><see cref="Model.Render.Kind"/>: <see cref="Model.RenderKind.Still"/> for one frame saved as an image, else null.</summary>
|
||||
public string? Kind { get; init; }
|
||||
|
||||
/// <summary>Size of the file, or of every file of a sequence.</summary>
|
||||
public required long Bytes { get; init; }
|
||||
|
||||
@@ -46,11 +54,13 @@ public sealed record RenderResult
|
||||
Codec = Codec.ToString(),
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
Fps = FrameRate.Value,
|
||||
DurationSeconds = DurationSeconds,
|
||||
// A still is recorded with no frame rate and no duration (DECISIONS 2026-11-05, phase 5 (12)).
|
||||
Fps = Kind == Model.RenderKind.Still ? 0 : FrameRate.Value,
|
||||
DurationSeconds = Kind == Model.RenderKind.Still ? 0 : DurationSeconds,
|
||||
Bytes = Bytes,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
ProducedBy = producedBy,
|
||||
Kind = Kind,
|
||||
};
|
||||
|
||||
/// <summary>Bytes of a file, or the total of the files in a folder.</summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
@@ -9,11 +10,41 @@ namespace Chronos.Core.Render;
|
||||
/// </summary>
|
||||
public static class RenderRules
|
||||
{
|
||||
/// <summary>
|
||||
/// The settings format a still job needs (owner review 1, R8, "Save frame"): an older program reads the job as a render
|
||||
/// of the whole video, so it must never claim one.
|
||||
/// </summary>
|
||||
public const int StillFormat = 3;
|
||||
|
||||
/// <summary>The codecs a still frame is saved with, in the order "Save frame" offers them: PNG, JPEG and TIFF 16-bit.</summary>
|
||||
public static IReadOnlyList<VideoCodec> StillCodecs { get; } = [VideoCodec.PngSequence, VideoCodec.JpegSequence, VideoCodec.Tiff16Sequence];
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="RequiredFormat(ProjectSettings, ResolvedExport, int, int)"/>, and at least <see cref="StillFormat"/> for a
|
||||
/// still job (<paramref name="still"/>: one frame saved as an image).
|
||||
/// </summary>
|
||||
public static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight, bool still)
|
||||
{
|
||||
var format = RequiredFormat(settings, export, sourceWidth, sourceHeight);
|
||||
return still ? int.Max(format, StillFormat) : format;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings format a render of <paramref name="target"/> needs: <see cref="RequiredFormat(ProjectSettings, ResolvedExport, int, int, bool)"/>
|
||||
/// for its export, a still when <see cref="RenderTarget.StillFrame"/> is set.
|
||||
/// </summary>
|
||||
public static int RequiredFormat(ProjectSettings settings, RenderTarget target, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
return RequiredFormat(settings, target.Export, sourceWidth, sourceHeight, target.IsStill);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> on a source of the given
|
||||
/// (Exif-oriented) size needs: the format the settings are written in (<see cref="ProjectSettings.WrittenFormat"/>), and
|
||||
/// at least 2 when the chosen proportions change a fixed-size preset's size (<see cref="RenderSize"/>), which a format-1
|
||||
/// program would render at the preset's own ratio.
|
||||
/// (Exif-oriented) size needs: the format the settings are written in (<see cref="ProjectSettings.WrittenFormat"/>, 3 when
|
||||
/// <see cref="ExportSettings.Playback"/> plays other than forward once, so the settings must carry the export the job
|
||||
/// renders), and at least 2 when the chosen proportions change a fixed-size preset's size (<see cref="RenderSize"/>), which
|
||||
/// a format-1 program would render at the preset's own ratio.
|
||||
/// </summary>
|
||||
public static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
|
||||
@@ -5,27 +5,44 @@ using Chronos.Core.Video;
|
||||
namespace Chronos.Core.Render;
|
||||
|
||||
/// <summary>
|
||||
/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments) and plan.
|
||||
/// The Export tab uses it for the output size, encoder notices, plan chart and estimates.
|
||||
/// What a render will do, decided before its first frame: output geometry, encoder (with its adjustments), plan and output
|
||||
/// program. The Export tab uses it for the output size, encoder notices, plan chart and estimates; <see cref="Program"/> is
|
||||
/// what the encoder receives (owner review 1, R8).
|
||||
/// </summary>
|
||||
public sealed record RenderSetup
|
||||
{
|
||||
private readonly OutputProgram? _program;
|
||||
|
||||
public required RenderTarget Target { get; init; }
|
||||
public required RenderGeometry Geometry { get; init; }
|
||||
public required EncoderSelection Encoder { get; init; }
|
||||
public required RenderPlan Plan { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The frames in the order and for the time they are emitted (owner review 1, R8): the plan played as the export's
|
||||
/// <see cref="ExportSettings.Playback"/> says. A still's program is its one frame. Defaults to the plan forward once.
|
||||
/// </summary>
|
||||
public OutputProgram Program
|
||||
{
|
||||
get => _program ?? OutputProgram.Build(Plan, null, Plan.FrameRate);
|
||||
init => _program = value;
|
||||
}
|
||||
|
||||
/// <summary>The frame a still target saves (<see cref="RenderTarget.StillFrame"/>): whole, never interpolated; null for a video.</summary>
|
||||
public PlannedFrame? Still { get; init; }
|
||||
|
||||
/// <summary>Synthetic motion blur applies (it is off while stacking).</summary>
|
||||
public bool MotionBlur { get; init; }
|
||||
|
||||
/// <summary>The preparation pass decodes frames (no corrections were supplied and a module needs measurements).</summary>
|
||||
public bool NeedsPreparation { get; init; }
|
||||
|
||||
/// <summary>Geometry, plan and encoder remarks.</summary>
|
||||
/// <summary>Geometry, plan, program and encoder remarks.</summary>
|
||||
public IReadOnlyList<RenderWarning> Warnings { get; init; } = [];
|
||||
|
||||
/// <summary>Decides geometry, encoder and plan for one target.</summary>
|
||||
/// <summary>Decides geometry, encoder, plan and program for one target.</summary>
|
||||
/// <param name="corrections">Prepared corrections when available (their stabilisation zoom affects the decode size).</param>
|
||||
/// <exception cref="RenderException">A still target names a frame the sequence does not have.</exception>
|
||||
public static RenderSetup Create(RenderInput input, RenderTarget target, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host,
|
||||
RenderOptions? options = null, RenderCorrections? corrections = null)
|
||||
{
|
||||
@@ -34,21 +51,49 @@ public sealed record RenderSetup
|
||||
ArgumentNullException.ThrowIfNull(encoders);
|
||||
options ??= RenderOptions.Default;
|
||||
if (input.Frames.Count != input.Source.FrameCount) throw new ArgumentException("One metadata entry per source frame is required.", nameof(input));
|
||||
if (target.StillFrame is { } wanted && (wanted < 0 || wanted >= input.Source.FrameCount))
|
||||
throw new RenderException("Export.Render.StillMissing", $"Frame {wanted} is not in the sequence of {input.Source.FrameCount} frames.");
|
||||
var project = input.Project;
|
||||
var geometry = RenderGeometry.Create(project.Camera, target.Export, input.Source.Width, input.Source.Height,
|
||||
corrections?.StabilizationZoom ?? 1, options.MaxWorkingLongEdge);
|
||||
var selection = EncoderSelector.Select(target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight), encoders, host);
|
||||
var requested = target.Export.ToEncodeSettings(target.OutputPath, geometry.OutputWidth, geometry.OutputHeight);
|
||||
// "TIFF 16-bit" is what Save frame offers, whatever depth the export's video has.
|
||||
if (target.IsStill) requested = requested with { SingleImage = true, BitDepth = requested.Codec == VideoCodec.Tiff16Sequence ? 16 : requested.BitDepth };
|
||||
var selection = EncoderSelector.Select(requested, encoders, host);
|
||||
geometry = geometry.WithOutputSize(selection.Settings.Width, selection.Settings.Height);
|
||||
var times = new DateTime?[input.Frames.Count];
|
||||
for (var i = 0; i < times.Length; i++) times[i] = input.Frames[i].CapturedAt;
|
||||
var plan = RenderPlan.Build(times, project, selection.Settings.FrameRate, options.Plan);
|
||||
var rate = selection.Settings.FrameRate;
|
||||
var plan = RenderPlan.Build(times, project, rate, options.Plan);
|
||||
|
||||
var warnings = new List<RenderWarning>(geometry.Warnings);
|
||||
warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k)));
|
||||
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
|
||||
var stacking = project.Stack.Mode != StackSetting.None;
|
||||
var blur = project.Motion.MotionBlur.Resolve(false);
|
||||
if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking"));
|
||||
OutputProgram program;
|
||||
PlannedFrame? still = null;
|
||||
if (target.StillFrame is { } index)
|
||||
{
|
||||
// One source frame, whole: no stacking, interpolation, blur or playback, so no plan remark applies.
|
||||
still = new PlannedFrame(index, index, index, 0, 0, RenderPlan.TicksAt(rate, 1), 0, 1, 0, PlannedFrameFlags.None);
|
||||
program = OutputProgram.Build([still.Value], null, rate);
|
||||
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
|
||||
blur = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
warnings.AddRange(plan.Warnings.Select(k => new RenderWarning(k)));
|
||||
warnings.AddRange(selection.Notices.Select(n => new RenderWarning(n.Key, n.Args)));
|
||||
if (blur && stacking) warnings.Add(new RenderWarning("Export.Render.BlurOffWhileStacking"));
|
||||
var playback = project.Export.Playback;
|
||||
if (project.Stack.Mode == StackSetting.StarTrails && playback?.EffectiveDirection == PlaybackDirection.Boomerang)
|
||||
{
|
||||
// Trails cannot shrink on the way back, so the video plays forward (DECISIONS 2026-11-05, phase 5 (11)).
|
||||
warnings.Add(new RenderWarning(OutputProgram.BoomerangStackWarning));
|
||||
playback = playback with { Direction = null };
|
||||
}
|
||||
program = OutputProgram.Build(plan, playback, rate);
|
||||
warnings.AddRange(program.Warnings);
|
||||
}
|
||||
var exposure = project.Exposure;
|
||||
var measuring = exposure.Deflicker.Resolve(false) || exposure.HolyGrail.Resolve(false)
|
||||
|| exposure.WhiteBalanceSmoothing.Resolve(false) || project.Motion.Stabilize.Resolve(false);
|
||||
@@ -58,20 +103,38 @@ public sealed record RenderSetup
|
||||
Geometry = geometry,
|
||||
Encoder = selection,
|
||||
Plan = plan,
|
||||
Program = program,
|
||||
Still = still,
|
||||
MotionBlur = blur && !stacking,
|
||||
NeedsPreparation = corrections is null && measuring,
|
||||
Warnings = warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The render's workload in the units of <see cref="ExportEstimator"/>.</summary>
|
||||
/// <summary>
|
||||
/// The render's workload in the units of <see cref="ExportEstimator"/>, from the output program: every pass and loop is
|
||||
/// rendered again, so the time grows with them, and the duration includes the hold. A still is one picture of no duration.
|
||||
/// </summary>
|
||||
public ExportWorkload Workload()
|
||||
{
|
||||
var edge = Geometry.WorkingLongEdge;
|
||||
var shortEdge = (long)double.Round(edge * (double)int.Min(Geometry.SourceWidth, Geometry.SourceHeight) / int.Max(Geometry.SourceWidth, Geometry.SourceHeight));
|
||||
var flowFrames = MotionBlur ? Plan.Frames.Count : Plan.Statistics.InterpolatedFrames;
|
||||
return new ExportWorkload(Plan.Frames.Count, Plan.SlotCount, Plan.DurationSeconds, Geometry.OutputWidth, Geometry.OutputHeight, edge * shortEdge,
|
||||
flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false);
|
||||
var program = Program;
|
||||
var flowFrames = 0;
|
||||
if (Still is null)
|
||||
{
|
||||
// A frame split over the periods of a fade is rendered once; every other entry is rendered again.
|
||||
for (var i = 0; i < program.Count; i++)
|
||||
{
|
||||
var entry = program.Entries[i];
|
||||
if (i > 0 && program.Entries[i - 1].PlanIndex == entry.PlanIndex) continue;
|
||||
if (MotionBlur || Plan.Frames[entry.PlanIndex].IsInterpolated) flowFrames++;
|
||||
}
|
||||
}
|
||||
var rate = Encoder.Settings.FrameRate;
|
||||
var periods = Still is null ? (int)double.Round(program.Duration90k * (double)rate.Numerator / (90000.0 * rate.Denominator)) : 1;
|
||||
return new ExportWorkload(program.Count, periods, Still is null ? program.DurationSeconds : 0, Geometry.OutputWidth, Geometry.OutputHeight,
|
||||
edge * shortEdge, flowFrames, NeedsPreparation ? Plan.IncludedFrames.Count : 0, Encoder.Capability?.Hardware ?? false);
|
||||
}
|
||||
|
||||
/// <summary>Size and time estimates for the values the encoder will actually use.</summary>
|
||||
|
||||
@@ -102,11 +102,21 @@ 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>
|
||||
public string? EncoderName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// One frame saved as one image file at <see cref="OutputPath"/> (owner review 1, R8, "Save frame") instead of a numbered
|
||||
/// sequence in a folder: the image-sequence codecs PNG, JPEG and TIFF only, and exactly one frame.
|
||||
/// </summary>
|
||||
public bool SingleImage { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>One open encode. Frames are linear-light buffers at the output size.</summary>
|
||||
@@ -122,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>
|
||||
|
||||
@@ -2,7 +2,8 @@ namespace Chronos.Core.Video.Managed;
|
||||
|
||||
/// <summary>
|
||||
/// The encoders every platform has (BRIEF §11.3): MJPEG in AVI, JPEG / PNG (8 or 16-bit) / TIFF-16 / linear DNG image
|
||||
/// sequences, animated GIF and APNG, all written by the in-house codecs. Frames are linear-light buffers at the output
|
||||
/// sequences, animated GIF and APNG, and one PNG, JPEG or TIFF still (<see cref="EncodeSettings.SingleImage"/>), all
|
||||
/// written by the in-house codecs. Frames are linear-light buffers at the output
|
||||
/// size. Single files are written to a temporary sibling and renamed on <see cref="IVideoEncoderSession.Complete"/>;
|
||||
/// sequences go to a temporary folder renamed the same way, so a cancelled or failed encode leaves nothing behind.
|
||||
/// AVI and image sequences are constant frame rate: a frame lasting several periods is repeated.
|
||||
@@ -44,6 +45,7 @@ public sealed class ManagedEncoderProvider : IVideoEncoderProvider
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
if (Problem(settings) is { } problem) throw new NotSupportedException(problem);
|
||||
var name = Capabilities.First(c => c.Codec == settings.Codec).Name;
|
||||
if (settings.SingleImage) return new StillImageSession(settings, name);
|
||||
return settings.Codec switch
|
||||
{
|
||||
VideoCodec.Mjpeg => new AviMjpegSession(settings, name),
|
||||
@@ -59,6 +61,7 @@ public sealed class ManagedEncoderProvider : IVideoEncoderProvider
|
||||
if (s.Width is <= 0 or > MaxDimension || s.Height is <= 0 or > MaxDimension) return $"{s.Width}×{s.Height} is outside 1–{MaxDimension}";
|
||||
if (s.FrameRate.Numerator <= 0 || s.FrameRate.Denominator <= 0) return "The frame rate must be positive";
|
||||
if (!BitDepths(s.Codec).Contains(s.BitDepth)) return $"{s.Codec} cannot be written with {s.BitDepth}-bit samples";
|
||||
if (s.SingleImage && !StillImageSession.Takes(s.Codec)) return $"{s.Codec} cannot be saved as a single image";
|
||||
return string.IsNullOrWhiteSpace(s.OutputPath) ? "No output path" : null;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -201,6 +202,37 @@ internal sealed class ApngSession : SingleFileSession
|
||||
protected override void Finish() => _encoder.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One frame saved as one image file (owner review 1, R8, "Save frame"; <see cref="EncodeSettings.SingleImage"/>): PNG (8 or
|
||||
/// 16-bit), JPEG or TIFF (16 or 8-bit) at <see cref="EncodeSettings.OutputPath"/>, written to a temporary sibling and renamed
|
||||
/// into place on completion like the other single files. A second frame is refused.
|
||||
/// </summary>
|
||||
internal sealed class StillImageSession(EncodeSettings settings, string encoderName) : SingleFileSession(settings, encoderName)
|
||||
{
|
||||
private bool _written;
|
||||
|
||||
/// <summary>The codecs a still is saved with.</summary>
|
||||
public static bool Takes(VideoCodec codec) => codec is VideoCodec.PngSequence or VideoCodec.JpegSequence or VideoCodec.Tiff16Sequence;
|
||||
|
||||
protected override void Write(ImageBuffer frame, long duration90k)
|
||||
{
|
||||
if (_written) throw new InvalidOperationException("A still holds one frame");
|
||||
var bytes = Settings.Codec switch
|
||||
{
|
||||
VideoCodec.JpegSequence => JpegEncoder.Encode(frame, JpegOptions(Settings.Quality)),
|
||||
VideoCodec.PngSequence => PngEncoder.Encode(frame, Settings.BitDepth == 16 ? 16 : 8, CompressionLevel.Optimal),
|
||||
VideoCodec.Tiff16Sequence => TiffWriter.Write(frame, new TiffWriteOptions { BitsPerSample = Settings.BitDepth == 8 ? 8 : 16 }),
|
||||
_ => throw new NotSupportedException($"{Settings.Codec} cannot be saved as a single image"),
|
||||
};
|
||||
File.Write(bytes);
|
||||
_written = true;
|
||||
}
|
||||
|
||||
protected override void Finish()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Numbered image files (<c><folder name>_000001.ext</c>, 1-based, six digits) in the output folder. Files are written
|
||||
/// (and flushed) into a hidden temporary sibling folder that is renamed to the output folder on completion. Frames are
|
||||
|
||||
@@ -47,6 +47,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
|
||||
Converter = new MassConverter(db, _writer, Ingest, FrameTrash, Trash, this);
|
||||
Projects = new ProjectService(db, _writer);
|
||||
Videos = new Chronos.Data.Videos.VideoLibrary(db, _writer);
|
||||
var shared = Housekeeping.CleanupSteps.Shared(Trash);
|
||||
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
|
||||
}
|
||||
@@ -68,6 +69,12 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// <summary>Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6).</summary>
|
||||
public FrameTrash FrameTrash { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The videos library of this index (owner review 1, R9): every render listed, deleted into the trash, restored and copied
|
||||
/// into a videos folder (<see cref="JobKind.VideoCopy"/>, among <see cref="CreateJobHandlers"/>).
|
||||
/// </summary>
|
||||
public Chronos.Data.Videos.VideoLibrary Videos { get; }
|
||||
|
||||
/// <summary>Converts sequences to JPEG, TIFF-16 or linear DNG, replacing their frames or into new sequences (owner review 2, R7).</summary>
|
||||
public MassConverter Converter { get; }
|
||||
|
||||
@@ -111,6 +118,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
|
||||
new ConvertJobHandler(_db, Converter, _writer.Options.SequenceChanged),
|
||||
new Chronos.Data.Videos.VideoCopyJobHandler(_db, Videos),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -166,6 +174,15 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile (a server starts all the same).
|
||||
Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex);
|
||||
}
|
||||
try
|
||||
{
|
||||
// A delete of videos into the trash a crash interrupted completes, or is undone (owner review 1, R9).
|
||||
await Videos.RecoverAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException or DatabaseException)
|
||||
{
|
||||
Log.Warning("archive", $"Settling an interrupted delete of videos in {paths.Root} failed", ex);
|
||||
}
|
||||
return archive;
|
||||
}
|
||||
|
||||
@@ -509,10 +526,13 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
(await RestoreEntryAsync(archiveId, entryName, null, cancellationToken).ConfigureAwait(false)).Sequence;
|
||||
|
||||
/// <summary>
|
||||
/// Brings a trash entry back: a sequence into its folder (<see cref="SequenceTrash.RestoreAsync"/>), or photos into
|
||||
/// Brings a trash entry back: a sequence into its folder (<see cref="SequenceTrash.RestoreAsync"/>), photos into
|
||||
/// their sequence (<see cref="Archiving.FrameTrash.RestoreAsync"/>, which queues on <paramref name="followUps"/> what the
|
||||
/// frames need again).
|
||||
/// frames need again), or a video into its sequence's renders (<see cref="Chronos.Data.Videos.VideoLibrary.RestoreAsync"/>, owner
|
||||
/// review 1, R9: <see cref="TrashRestoreResult.Sequence"/> is the video's).
|
||||
/// </summary>
|
||||
/// <exception cref="Chronos.Data.Videos.VideoLibraryException">A video entry whose file no longer matches its record, or whose sequence
|
||||
/// is not in the index; nothing moved.</exception>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="SequenceInLibraryException">A sequence entry whose sequence is in the index already.</exception>
|
||||
/// <exception cref="TrashMismatchException">No file of a photo entry matches its record; nothing moved.</exception>
|
||||
@@ -522,6 +542,13 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
if (Chronos.Data.Videos.VideoTrashNames.IsEntryName(entryName))
|
||||
{
|
||||
var render = await Videos.RestoreAsync(archive.Id, entryName, cancellationToken).ConfigureAwait(false);
|
||||
var owner = await _db.Sequences.GetAsync(render.SequenceId, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"The sequence of render {render.Id} is not in the index.");
|
||||
return new TrashRestoreResult(TrashKind.Videos, owner, 0, [], false);
|
||||
}
|
||||
if (!Archiving.FrameTrash.IsPhotoEntry(entryName))
|
||||
return new TrashRestoreResult(TrashKind.Sequence, await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false), 0, [], false);
|
||||
var photos = await FrameTrash.RestoreAsync(archive, entryName, followUps, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -286,8 +286,8 @@ public sealed partial class SequenceTrash
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var (folder, recordPath) = Location(paths, entry);
|
||||
var now = FrameTrash.IsPhotoEntry(entry.Name)
|
||||
? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
|
||||
var now = FrameTrash.IsPhotoEntry(entry.Name) ? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
|
||||
: Videos.VideoTrashNames.IsEntryName(entry.Name) ? Videos.VideoTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
|
||||
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
|
||||
if (now is null || !Directory.Exists(folder)) return (null, null);
|
||||
var (files, bytes) = Measure(folder, cancellationToken);
|
||||
@@ -313,10 +313,11 @@ public sealed partial class SequenceTrash
|
||||
return Survey(archive, paths, entry.Name, record, where, cancellationToken).Deleted ? entry with { ConversionDeleted = true } : entry;
|
||||
}
|
||||
|
||||
/// <summary>The folder and record of an entry of either kind.</summary>
|
||||
/// <summary>The folder and record of an entry of any kind (a sequence, photos, or a video: owner review 1, R9).</summary>
|
||||
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
|
||||
{
|
||||
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.Location(paths, entry.Name);
|
||||
if (Videos.VideoTrashNames.IsEntryName(entry.Name)) return Videos.VideoTrash.Location(paths, entry.Name);
|
||||
var folder = Path.Combine(TrashDirectory(paths), Path.GetFileName(entry.Name));
|
||||
return (folder, folder + RecordExtension);
|
||||
}
|
||||
|
||||
@@ -60,6 +60,12 @@ public enum TrashKind
|
||||
|
||||
/// <summary>Originals a conversion replaced (owner review 2, R7): erased only while their replacements still match.</summary>
|
||||
Replaced,
|
||||
|
||||
/// <summary>
|
||||
/// A render deleted from the videos library (owner review 1, R9): its file under <c>trash/videos/</c> with a record, listed
|
||||
/// as "videos" (<see cref="Videos.VideoTrashNames"/>).
|
||||
/// </summary>
|
||||
Videos,
|
||||
}
|
||||
|
||||
/// <summary>An entry of an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it: a deleted sequence or deleted photos.</summary>
|
||||
@@ -207,8 +213,9 @@ public sealed partial class SequenceTrash
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entries of an archive's trash, newest first: deleted sequences (<c>trash/*.json</c>) and deleted photos
|
||||
/// (<c>trash/photos/*.json</c>); records whose folder is gone are left out.
|
||||
/// The entries of an archive's trash, newest first: deleted sequences (<c>trash/*.json</c>), deleted photos
|
||||
/// (<c>trash/photos/*.json</c>) and deleted videos (<c>trash/videos/*.json</c>, owner review 1, R9); records whose folder
|
||||
/// is gone are left out.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -226,6 +233,7 @@ public sealed partial class SequenceTrash
|
||||
entries.Add(Entry(archive.Id, name, record));
|
||||
}
|
||||
entries.AddRange(FrameTrash.List(archive, cancellationToken));
|
||||
entries.AddRange(Chronos.Data.Videos.VideoTrash.List(archive, cancellationToken));
|
||||
return entries.OrderByDescending(e => e.DeletedAt).ThenBy(e => e.Name, StringComparer.Ordinal).ToList();
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ public abstract class ChronosRepositories
|
||||
Schedules = new ScheduleRepository(access);
|
||||
FrameRemovals = new FrameRemovalRepository(access);
|
||||
Projects = new ProjectRepository(access);
|
||||
RenderCopies = new RenderCopyRepository(access);
|
||||
}
|
||||
|
||||
public ArchiveRepository Archives { get; }
|
||||
@@ -49,6 +50,9 @@ public abstract class ChronosRepositories
|
||||
|
||||
/// <summary>Projects of sequences and their versions (owner review 2, R8).</summary>
|
||||
public ProjectRepository Projects { get; }
|
||||
|
||||
/// <summary>Verified copies of renders in videos folders (owner review 1, R9).</summary>
|
||||
public RenderCopyRepository RenderCopies { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -24,7 +24,8 @@ public sealed record JobPriorityQueue
|
||||
/// <summary>
|
||||
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
|
||||
/// media into the workspace, which Edit waits for (owner review 2, R8), a workspace's local render and the move of the
|
||||
/// workspace folder, which Edit is held for (phase 5c); a local render's sending home at the normal level; the long
|
||||
/// workspace folder, which Edit is held for (phase 5c), and the copy of videos into the videos folder, a transfer the user
|
||||
/// waits for like a download (owner review 1, R9); a local render's sending home at the normal level; the long
|
||||
/// passes that resume anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
|
||||
@@ -36,6 +37,7 @@ public sealed record JobPriorityQueue
|
||||
[JobKind.WorkspaceRender] = JobKindPriority.High,
|
||||
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
|
||||
[JobKind.WorkspaceMove] = JobKindPriority.High,
|
||||
[JobKind.VideoCopy] = JobKindPriority.High,
|
||||
[JobKind.Verify] = JobKindPriority.Low,
|
||||
[JobKind.Proxies] = JobKindPriority.Low,
|
||||
[JobKind.Backup] = JobKindPriority.Low,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- The videos library (owner review 1, R9). Renders remember the SHA-256 of their file (null for an image sequence's
|
||||
-- folder, verified file by file when copied, and for renders recorded before this migration, hashed the first time they
|
||||
-- are copied, deleted or restored) and their kind (null for a video or an image sequence, told apart by the codec;
|
||||
-- 'still' for one frame saved as an image). The library lists every render newest first. render_copies records each
|
||||
-- hash-verified copy into a videos folder; it has no foreign key to renders, so the copy of a server render downloaded to
|
||||
-- a PC is recorded too, and a copy outlives its render. No backfill. Mirrors sqlite/0010_videos.sql.
|
||||
|
||||
ALTER TABLE renders ADD COLUMN sha256 text;
|
||||
ALTER TABLE renders ADD COLUMN kind text;
|
||||
CREATE INDEX ix_renders_created ON renders (created);
|
||||
|
||||
CREATE TABLE render_copies (
|
||||
id uuid NOT NULL PRIMARY KEY,
|
||||
render_id uuid NOT NULL,
|
||||
path text NOT NULL,
|
||||
sha256 text,
|
||||
bytes bigint NOT NULL DEFAULT 0,
|
||||
copied_at timestamptz NOT NULL,
|
||||
copied_by text
|
||||
);
|
||||
CREATE INDEX ix_render_copies_render ON render_copies (render_id);
|
||||
@@ -0,0 +1,21 @@
|
||||
-- The videos library (owner review 1, R9). Renders remember the SHA-256 of their file (null for an image sequence's
|
||||
-- folder, verified file by file when copied, and for renders recorded before this migration, hashed the first time they
|
||||
-- are copied, deleted or restored) and their kind (null for a video or an image sequence, told apart by the codec;
|
||||
-- 'still' for one frame saved as an image). The library lists every render newest first. render_copies records each
|
||||
-- hash-verified copy into a videos folder; it has no foreign key to renders, so the copy of a server render downloaded to
|
||||
-- a PC is recorded too, and a copy outlives its render. No backfill. Mirrors postgres/0010_videos.sql.
|
||||
|
||||
ALTER TABLE renders ADD COLUMN sha256 TEXT;
|
||||
ALTER TABLE renders ADD COLUMN kind TEXT;
|
||||
CREATE INDEX ix_renders_created ON renders (created);
|
||||
|
||||
CREATE TABLE render_copies (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
render_id TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
sha256 TEXT,
|
||||
bytes INTEGER NOT NULL DEFAULT 0,
|
||||
copied_at TEXT NOT NULL,
|
||||
copied_by TEXT
|
||||
);
|
||||
CREATE INDEX ix_render_copies_render ON render_copies (render_id);
|
||||
@@ -59,7 +59,11 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
var (projectId, projectVersionId) = await ProvenanceAsync(parameters, sequence, cancellation).ConfigureAwait(false);
|
||||
|
||||
using var names = new OutputNames();
|
||||
var all = Targets(export, parameters.PresetName);
|
||||
// A still saves one frame through the job's preset alone: a batch is a video's.
|
||||
var all = parameters.IsStill ? [new ExportTarget(ExportResolver.Resolve(export), parameters.PresetName)] : Targets(export, parameters.PresetName);
|
||||
var still = parameters.IsStill
|
||||
? SequenceRender.StillIndex(frames, parameters.StillFrame, parameters.StillPhoto) ?? throw new InvalidOperationException(Loc.L("Export.Render.StillMissing"))
|
||||
: -1;
|
||||
var resume = RenderCheckpoint.Parse(context.Checkpoint);
|
||||
var done = resume.Done.ToList();
|
||||
// A crash after a render row was written but before the checkpoint: that entry is finished.
|
||||
@@ -83,29 +87,46 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames), options, originals: !parameters.UseProxies,
|
||||
companions))
|
||||
{
|
||||
outcomes = await render.RenderAllAsync(
|
||||
targets,
|
||||
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
|
||||
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total),
|
||||
async (index, target, result) =>
|
||||
async ValueTask Record(int index, ExportTarget target, RenderResult result)
|
||||
{
|
||||
// The output is complete: record it even if the job is being cancelled, so it is never orphaned. A file is
|
||||
// hashed first (owner review 1, R9: copies and restores are verified against it); an image sequence's folder is not.
|
||||
string? sha = null;
|
||||
if (File.Exists(result.OutputPath))
|
||||
{
|
||||
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
|
||||
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with
|
||||
{
|
||||
Id = RenderId(context.Job.Id, index),
|
||||
OutputPath = Stored(paths, result.OutputPath),
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
};
|
||||
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
|
||||
done.Add(index);
|
||||
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
|
||||
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
|
||||
await options.NotifyAsync(sequence.Id, ProcessingOptions.RenderedChange, CancellationToken.None).ConfigureAwait(false);
|
||||
},
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
await context.ReportAsync(context.Done, context.Total, Loc.L("Export.Job.Verifying")).ConfigureAwait(false);
|
||||
sha = await ContentHash.Sha256Async(result.OutputPath, cancellationToken: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with
|
||||
{
|
||||
Id = RenderId(context.Job.Id, index),
|
||||
OutputPath = Stored(paths, result.OutputPath),
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
Sha256 = sha,
|
||||
Kind = parameters.IsStill ? RenderKind.Still : null,
|
||||
};
|
||||
if (parameters.IsStill) entity = entity with { Fps = 0, DurationSeconds = 0 };
|
||||
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
|
||||
done.Add(index);
|
||||
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
|
||||
context.Log(parameters.IsStill
|
||||
? Loc.L("Export.Log.StillSaved", (still + 1).ToString(Loc.Culture), Path.GetFileName(result.OutputPath))
|
||||
: Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
|
||||
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
|
||||
await options.NotifyAsync(sequence.Id, ProcessingOptions.RenderedChange, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (parameters.IsStill)
|
||||
outcomes = [await StillAsync(context, render, targets[0], still, sequence, project.Export, folder, names, done, Record).ConfigureAwait(false)];
|
||||
else
|
||||
outcomes = await render.RenderAllAsync(
|
||||
targets,
|
||||
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
|
||||
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total),
|
||||
Record,
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
if (render.StandIns.Count > 0)
|
||||
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", render.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
|
||||
// Recorded without the job's token: what decoding found holds even if the job is cancelled meanwhile, and a
|
||||
@@ -128,6 +149,34 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The still of a still job: frame <paramref name="frame"/> saved through the job's preset under the export's name and
|
||||
/// the frame number (<see cref="SequenceRender.StillPath"/>), checkpointed and recorded like a video's output.
|
||||
/// </summary>
|
||||
private static async Task<TargetOutcome> StillAsync(JobContext context, SequenceRender render, (int Index, ExportTarget Target) entry, int frame,
|
||||
Sequence sequence, ExportSettings export, SequencePaths folder, OutputNames names, List<int> done,
|
||||
Func<int, ExportTarget, RenderResult, ValueTask> record)
|
||||
{
|
||||
var (index, target) = entry;
|
||||
try
|
||||
{
|
||||
var result = await render.RenderStillAsync(
|
||||
target,
|
||||
frame,
|
||||
setup => names.Reserve(taken => SequenceRender.StillPath(export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), frame, taken)),
|
||||
path => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total),
|
||||
context.ReportAsync,
|
||||
context.Cancellation).ConfigureAwait(false);
|
||||
await record(index, target, result).ConfigureAwait(false);
|
||||
return new TargetOutcome(target, result, null);
|
||||
}
|
||||
catch (Exception ex) when (!(ex is OperationCanceledException && context.Cancellation.IsCancellationRequested))
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("processing", $"The still of frame {frame + 1} of {sequence.DisplayTitle} failed", ex);
|
||||
return new TargetOutcome(target, null, SequenceRender.Reason(ex));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings of the project version a job names without embedding them (owner review 2, R8); null when it names none.
|
||||
/// </summary>
|
||||
|
||||
@@ -44,6 +44,34 @@ public static class ProcessingJobs
|
||||
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Render"/> of one frame saved as an image (owner review 1, R8, "Save frame"): frame
|
||||
/// <paramref name="frameIndex"/> of the sequence (its photo <paramref name="photoSha256"/> wins when both are given and the
|
||||
/// frames moved since) with <paramref name="codec"/>, one of <see cref="RenderRules.StillCodecs"/>, at the output size of
|
||||
/// <paramref name="export"/>, with every correction and no playback. <paramref name="project"/> embeds the settings to
|
||||
/// render, as <see cref="Render"/>. The job needs settings format <see cref="RenderRules.StillFormat"/>, so an older node,
|
||||
/// which would render the whole video, never claims it.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="codec"/> is not a still codec, or <paramref name="frameIndex"/> is negative.</exception>
|
||||
public static ArchiveJobRequest Still(Sequence sequence, ExportSettings export, VideoCodec codec, int frameIndex, string? photoSha256, int sourceWidth,
|
||||
int sourceHeight, ProjectSettings? project = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
if (!RenderRules.StillCodecs.Contains(codec)) throw new ArgumentOutOfRangeException(nameof(codec), codec, "Not a still codec.");
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(frameIndex);
|
||||
var still = export with { Batch = [], Playback = null, Overrides = export.Overrides with { Codec = CodecName(codec), Container = null } };
|
||||
var parameters = Parameters(still, sourceWidth, sourceHeight, project?.ToJson(), false, project ?? ReadSettings(sequence.SettingsJson));
|
||||
parameters = parameters with
|
||||
{
|
||||
StillFrame = frameIndex,
|
||||
StillPhoto = string.IsNullOrEmpty(photoSha256) ? null : photoSha256.ToLowerInvariant(),
|
||||
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, RenderRules.StillFormat),
|
||||
};
|
||||
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
|
||||
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Render"/> of a project version (owner review 2, R8) on the sequence's home: the version's portable
|
||||
/// settings, placed on the sequence's frames by the render, with <paramref name="export"/> as their export section; the
|
||||
@@ -125,10 +153,19 @@ public static class ProcessingJobs
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, RequiredFormat(settings, 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
|
||||
@@ -138,8 +175,8 @@ public static class ProcessingJobs
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
return BatchPresets(export).Select(id => ExportResolver.Resolve(BatchExport(export, id))).Prepend(ExportResolver.Resolve(export))
|
||||
.Max(resolved => RequiredFormat(settings, resolved, sourceWidth, sourceHeight));
|
||||
return BatchPresets(export).Select(id => BatchExport(export, id)).Prepend(export)
|
||||
.Max(each => RequiredFormat(settings with { Export = each }, ExportResolver.Resolve(each), sourceWidth, sourceHeight));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -182,9 +219,12 @@ public static class ProcessingJobs
|
||||
.Where(id => !id.Equals(main, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>A batch preset rendered with its own values, named and placed like the export it belongs to.</summary>
|
||||
/// <summary>
|
||||
/// A batch preset rendered with its own values, named, placed and played like the export it belongs to: its playback
|
||||
/// (owner review 1, R8: direction, loops, fades, hold) lives in the export, so every batch preset inherits it.
|
||||
/// </summary>
|
||||
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
|
||||
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
|
||||
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder, Playback = export.Playback };
|
||||
|
||||
/// <param name="settings">The settings rendered, for the output size and the format (else read from <paramref name="settingsJson"/>); unknown, the preset's size.</param>
|
||||
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies,
|
||||
@@ -194,7 +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);
|
||||
var format = settings is null ? ProjectSettings.BaseVersion : RequiredFormat(settings, resolved, sourceWidth, sourceHeight);
|
||||
// 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
|
||||
: 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);
|
||||
}
|
||||
|
||||
@@ -98,13 +98,14 @@ internal sealed class SequenceRender : IAsyncDisposable
|
||||
outcomes.Add(new TargetOutcome(target, null, Reason(ex)));
|
||||
continue;
|
||||
}
|
||||
if (setup.Encoder.IsReady && setup.Plan.Frames.Count > 0) ready.Add((index, target, setup));
|
||||
if (setup.Encoder.IsReady && setup.Program.Count > 0) ready.Add((index, target, setup));
|
||||
else outcomes.Add(new TargetOutcome(target, null, Reason(setup)));
|
||||
}
|
||||
if (ready.Count == 0) return outcomes;
|
||||
|
||||
var preparing = ready[0].Setup.NeedsPreparation ? ready[0].Setup.Plan.IncludedFrames.Count : 0;
|
||||
var total = preparing + ready.Sum(r => (long)r.Setup.Plan.Frames.Count);
|
||||
// Rendered pictures are counted in the output program's entries (loops, a boomerang and fades add to the plan's).
|
||||
var total = preparing + ready.Sum(r => (long)r.Setup.Program.Count);
|
||||
var stage = Loc.L("Export.Job.Preparing");
|
||||
var chain = new ProgressChain(progress);
|
||||
var corrections = await RenderPreparation.PrepareAsync(Input, _options, Stage(chain, 0, preparing, total, stage), cancellationToken).ConfigureAwait(false);
|
||||
@@ -119,7 +120,7 @@ internal sealed class SequenceRender : IAsyncDisposable
|
||||
try
|
||||
{
|
||||
var result = await Pipeline(target.Export).RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
|
||||
Stage(chain, done, setup.Plan.Frames.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
|
||||
Stage(chain, done, setup.Program.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
|
||||
await chain.FlushAsync().ConfigureAwait(false);
|
||||
await finished(index, target, result).ConfigureAwait(false);
|
||||
outcomes.Add(new TargetOutcome(target, result, null));
|
||||
@@ -129,11 +130,77 @@ internal sealed class SequenceRender : IAsyncDisposable
|
||||
Core.Diagnostics.Log.Warning("processing", $"Render of {target.PresetName} to {output} failed", ex);
|
||||
outcomes.Add(new TargetOutcome(target, null, Reason(ex)));
|
||||
}
|
||||
done += setup.Plan.Frames.Count;
|
||||
done += setup.Program.Count;
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves frame <paramref name="frameIndex"/> as one image ("Save frame", owner review 1, R8): the sequence prepared whole
|
||||
/// as for a video (so its exposure, colour and stabilisation corrections are the ones the video gives that frame), then
|
||||
/// that frame rendered by the pipeline's still path (<see cref="RenderTarget.StillFrame"/>) at the export's output size
|
||||
/// with every correction and the look, without stacking, interpolation, motion blur or playback, through the image
|
||||
/// encoder of <paramref name="target"/>'s codec (PNG, JPEG or TIFF 16-bit). The encoder writes a temporary name and
|
||||
/// renames it once complete, so a cancelled or failed still leaves nothing behind.
|
||||
/// </summary>
|
||||
/// <param name="name">The output path of the still from its setup.</param>
|
||||
/// <param name="starting">Runs with that path before anything is written (checkpoints).</param>
|
||||
/// <exception cref="RenderException">The frame is not one of the sequence's, or no encoder writes the codec.</exception>
|
||||
public async Task<RenderResult> RenderStillAsync(ExportTarget target, int frameIndex, Func<RenderSetup, string> name, Func<string, ValueTask> starting,
|
||||
Func<long, long, string?, ValueTask> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
var pipeline = Pipeline(target.Export);
|
||||
var setup = pipeline.Setup(Input, new RenderTarget(target.Export, ExportNaming.FallbackName, frameIndex), _options);
|
||||
if (!setup.Encoder.IsReady)
|
||||
{
|
||||
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
|
||||
throw new RenderException(notice.Key, $"No encoder can save {target.Export.Codec} here ({setup.Encoder.Status})", notice.Args);
|
||||
}
|
||||
var output = name(setup);
|
||||
await starting(output).ConfigureAwait(false);
|
||||
var chain = new ProgressChain(progress);
|
||||
var preparing = setup.NeedsPreparation ? setup.Plan.IncludedFrames.Count : 0;
|
||||
var total = preparing + 1L;
|
||||
// The corrections of the whole sequence, indexed by source frame: the frame gets what the video gives it.
|
||||
var corrections = await RenderPreparation.PrepareAsync(Input, _options, Stage(chain, 0, preparing, total, Loc.L("Export.Job.Preparing")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await chain.FlushAsync().ConfigureAwait(false);
|
||||
var result = await pipeline.RenderAsync(Input, corrections, new RenderTarget(target.Export, output, frameIndex), _options,
|
||||
Stage(chain, preparing, 1, total, target.PresetName), cancellationToken).ConfigureAwait(false);
|
||||
await chain.FlushAsync().ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path of a still of frame <paramref name="frameIndex"/> (0-based) in <paramref name="folder"/> (or the export's own
|
||||
/// folder): <see cref="ExportNaming.StillPath(ExportSettings, string, ExportNameContext, int, Func{string, bool}?)"/>,
|
||||
/// "2026-09-28 Harbour sunset - PNG - 0124.png"; " (2)" and so on when taken.
|
||||
/// </summary>
|
||||
public static string StillPath(ExportSettings export, string folder, ExportNameContext context, int frameIndex, Func<string, bool>? taken = null) =>
|
||||
ExportNaming.StillPath(export, folder, context, frameIndex, taken);
|
||||
|
||||
/// <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 (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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
if (photoSha256 is { Length: > 0 } sha)
|
||||
{
|
||||
for (var i = 0; i < frames.Frames.Count; i++)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Values of the output name tokens: the shoot date and title of the sequence, the codec and size the encoder will use.</summary>
|
||||
public static ExportNameContext NameContext(Sequence sequence, ExportTarget target, RenderSetup setup) => new()
|
||||
{
|
||||
@@ -166,7 +233,7 @@ internal sealed class SequenceRender : IAsyncDisposable
|
||||
|
||||
private static string Reason(RenderSetup setup)
|
||||
{
|
||||
if (setup.Plan.Frames.Count == 0) return Loc.L("Export.Render.NoFrames");
|
||||
if (setup.Program.Count == 0) return Loc.L("Export.Render.NoFrames");
|
||||
var notice = setup.Encoder.Notices.LastOrDefault() ?? new EncoderNotice(EncoderNotices.NoEncoder, setup.Encoder.Settings.Codec.ToString());
|
||||
return Loc.L(notice.Key, [.. notice.Args]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// The verified copies of renders in videos folders (owner review 1, R9; <c>render_copies</c>). There is no link to
|
||||
/// <c>renders</c>: the copy of a server render downloaded to a PC is recorded too, and a copy outlives its render.
|
||||
/// </summary>
|
||||
public sealed class RenderCopyRepository
|
||||
{
|
||||
private const string Columns = "id, render_id, path, sha256, bytes, copied_at, copied_by";
|
||||
|
||||
private readonly DbAccess _db;
|
||||
|
||||
internal RenderCopyRepository(DbAccess db) => _db = db;
|
||||
|
||||
public Task<int> InsertAsync(RenderCopy copy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
return _db.ExecuteAsync($"INSERT INTO render_copies ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
[copy.Id, copy.RenderId, copy.Path, copy.Sha256, copy.Bytes, copy.CopiedAt, copy.CopiedBy], cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The copies of a render, oldest first.</summary>
|
||||
public Task<IReadOnlyList<RenderCopy>> ListByRenderAsync(Guid renderId, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM render_copies WHERE render_id = $1 ORDER BY copied_at, id", [renderId], Map, cancellationToken);
|
||||
|
||||
/// <summary>The copies of each of <paramref name="renderIds"/>, oldest first; a render without copies is left out.</summary>
|
||||
public async Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> ListByRendersAsync(IReadOnlyCollection<Guid> renderIds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renderIds);
|
||||
var copies = new Dictionary<Guid, IReadOnlyList<RenderCopy>>();
|
||||
// In chunks, so the statement stays within every dialect's parameter limit.
|
||||
foreach (var chunk in renderIds.Distinct().Chunk(200))
|
||||
{
|
||||
var p = new SqlParameters();
|
||||
var list = string.Join(", ", chunk.Select(id => p.Add(id)));
|
||||
var rows = await _db.ListAsync($"SELECT {Columns} FROM render_copies WHERE render_id IN ({list}) ORDER BY copied_at, id", p.ToArray(), Map,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
foreach (var group in rows.GroupBy(c => c.RenderId)) copies[group.Key] = [.. group];
|
||||
}
|
||||
return copies;
|
||||
}
|
||||
|
||||
private static RenderCopy Map(DbRow r) => new()
|
||||
{
|
||||
Id = r.GetGuid(0),
|
||||
RenderId = r.GetGuid(1),
|
||||
Path = r.GetString(2),
|
||||
Sha256 = r.GetStringOrNull(3),
|
||||
Bytes = r.GetInt64(4),
|
||||
CopiedAt = r.GetDateTimeOffset(5),
|
||||
CopiedBy = r.GetStringOrNull(6),
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
@@ -7,7 +9,7 @@ public sealed class RenderRepository
|
||||
{
|
||||
private const string Columns =
|
||||
"id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by, project_id, " +
|
||||
"project_version_id";
|
||||
"project_version_id, sha256, kind";
|
||||
|
||||
private const string RecountSql =
|
||||
"UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1";
|
||||
@@ -20,11 +22,11 @@ public sealed class RenderRepository
|
||||
_db.InTransactionAsync(async session =>
|
||||
{
|
||||
await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
|
||||
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)",
|
||||
[
|
||||
render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec,
|
||||
render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy, render.ProjectId,
|
||||
render.ProjectVersionId,
|
||||
render.ProjectVersionId, render.Sha256, render.Kind,
|
||||
], cancellationToken).ConfigureAwait(false);
|
||||
return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
@@ -36,6 +38,80 @@ public sealed class RenderRepository
|
||||
public Task<IReadOnlyList<Render>> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM renders WHERE sequence_id = $1 ORDER BY created DESC, id DESC", [sequenceId], Map, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// One page of every render of the index matching <paramref name="query"/> (the videos library, owner review 1, R9), in
|
||||
/// its order (<see cref="VideoSorts"/>: newest first unless asked), with the number of renders matching on every page.
|
||||
/// Text matches the sequence's search text, the preset name or the output path (any case).
|
||||
/// </summary>
|
||||
/// <exception cref="FormatException">The cursor is not one of this listing in this order.</exception>
|
||||
public Task<(IReadOnlyList<Render> Items, string? Next, long Total)> ListPageAsync(VideoQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var p = new SqlParameters();
|
||||
var where = Filter(query, p);
|
||||
var count = new SqlParameters();
|
||||
var countWhere = Filter(query, count);
|
||||
var sort = VideoSorts.All.FirstOrDefault(s => string.Equals(s, query.Sort, StringComparison.OrdinalIgnoreCase)) ?? VideoSorts.Newest;
|
||||
var scope = "videos:" + sort;
|
||||
var limit = Math.Clamp(query.Limit, 1, VideoQuery.MaxLimit);
|
||||
long offset = 0;
|
||||
string order;
|
||||
switch (sort)
|
||||
{
|
||||
case VideoSorts.Title:
|
||||
// By title, then newest: paged by position (a title is no key a cursor keeps well).
|
||||
if (query.Cursor is not null && Cursor.Decode(scope, query.Cursor).Value is long skip) offset = skip;
|
||||
order = "ORDER BY lower(coalesce(s.title, '')) ASC, r.created DESC, r.id DESC";
|
||||
break;
|
||||
default:
|
||||
{
|
||||
var (column, descending) = sort switch
|
||||
{
|
||||
VideoSorts.Oldest => ("r.created", false),
|
||||
VideoSorts.Largest => ("r.bytes", true),
|
||||
_ => ("r.created", true),
|
||||
};
|
||||
if (query.Cursor is not null)
|
||||
{
|
||||
var (value, id) = Cursor.Decode(scope, query.Cursor);
|
||||
where.Add(Cursor.After(column, "r.id", descending, value, id, p.Add));
|
||||
}
|
||||
var direction = descending ? "DESC" : "ASC";
|
||||
order = $"ORDER BY {column} {direction}, r.id {direction}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
var columns = string.Join(", ", Columns.Split(", ").Select(c => "r." + c));
|
||||
var sql = $"SELECT {columns} FROM renders r JOIN sequences s ON s.id = r.sequence_id{Where(where)} {order} LIMIT {p.Add(limit + 1)}"
|
||||
+ (offset > 0 ? $" OFFSET {p.Add(offset)}" : string.Empty);
|
||||
var countSql = $"SELECT count(*) FROM renders r JOIN sequences s ON s.id = r.sequence_id{Where(countWhere)}";
|
||||
return _db.RunAsync(async session =>
|
||||
{
|
||||
var rows = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false);
|
||||
var total = await session.ScalarAsync<long>(countSql, count.ToArray(), cancellationToken).ConfigureAwait(false);
|
||||
string? next = null;
|
||||
if (rows.Count > limit)
|
||||
{
|
||||
rows.RemoveAt(limit);
|
||||
var last = rows[^1];
|
||||
next = sort switch
|
||||
{
|
||||
VideoSorts.Title => Cursor.Encode(scope, offset + limit, last.Id),
|
||||
VideoSorts.Largest => Cursor.Encode(scope, last.Bytes, last.Id),
|
||||
_ => Cursor.Encode(scope, last.Created, last.Id),
|
||||
};
|
||||
}
|
||||
return ((IReadOnlyList<Render>)rows, next, total);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Records the SHA-256 of a render hashed later than it was recorded (owner review 1, R9: renders of before migration 0010).</summary>
|
||||
public Task<int> SetSha256Async(Guid id, string sha256, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(sha256);
|
||||
return _db.ExecuteAsync("UPDATE renders SET sha256 = $2 WHERE id = $1", [id, sha256.ToLowerInvariant()], cancellationToken);
|
||||
}
|
||||
|
||||
public Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
_db.InTransactionAsync(async session =>
|
||||
{
|
||||
@@ -93,6 +169,48 @@ public sealed class RenderRepository
|
||||
if (_db.Sql.IsPostgres) await SequenceRepository.LockAsync(session, sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The conditions of a videos query on <c>renders r JOIN sequences s</c>.</summary>
|
||||
private static List<string> Filter(VideoQuery query, SqlParameters p)
|
||||
{
|
||||
var where = new List<string>();
|
||||
if (query.SequenceId is { } sequence) where.Add($"r.sequence_id = {p.Add(sequence)}");
|
||||
if (!string.IsNullOrWhiteSpace(query.Codec)) where.Add($"lower(r.codec) = {p.Add(query.Codec.Trim().ToLowerInvariant())}");
|
||||
if (query.Year is { } year and > 0 and < 10000)
|
||||
{
|
||||
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…). 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 {ImageCodec})");
|
||||
break;
|
||||
case RenderKind.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)}");
|
||||
break;
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(query.Text))
|
||||
{
|
||||
var pattern = p.Add(SqlDialect.ContainsPattern(query.Text.Trim().ToLowerInvariant()));
|
||||
where.Add($"(s.search_text LIKE {pattern} ESCAPE '\\' OR lower(r.preset_name) LIKE {pattern} ESCAPE '\\' OR lower(r.output_path) LIKE {pattern} ESCAPE '\\')");
|
||||
}
|
||||
return where;
|
||||
}
|
||||
|
||||
private static string Where(List<string> conditions) => conditions.Count == 0 ? string.Empty : " WHERE " + string.Join(" AND ", conditions);
|
||||
|
||||
private static Render Map(DbRow r) => new()
|
||||
{
|
||||
Id = r.GetGuid(0),
|
||||
@@ -110,5 +228,7 @@ public sealed class RenderRepository
|
||||
ProducedBy = r.GetStringOrNull(12),
|
||||
ProjectId = r.GetGuidOrNull(13),
|
||||
ProjectVersionId = r.GetGuidOrNull(14),
|
||||
Sha256 = r.GetStringOrNull(15),
|
||||
Kind = r.GetStringOrNull(16),
|
||||
};
|
||||
}
|
||||
@@ -467,7 +467,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
{
|
||||
var sha = await ChronosClient.HashFileAsync(file, ct).ConfigureAwait(false);
|
||||
await remote.UploadRenderAsync(link.RemoteId, file, new RenderUploadRequest(render.Id, Path.GetFileName(file), new FileInfo(file).Length, sha,
|
||||
render.PresetName, render.Codec, render.Width, render.Height, render.Fps, render.DurationSeconds, render.ProducedBy), ct).ConfigureAwait(false);
|
||||
render.PresetName, render.Codec, render.Width, render.Height, render.Fps, render.DurationSeconds, render.ProducedBy, Kind: render.Kind), ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -499,7 +499,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
foreach (var render in wanted)
|
||||
{
|
||||
var (part, name) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
|
||||
var (part, name, sha) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
|
||||
var filed = await FileRenderAsync(sync.Archives, db, local, paths, part, name, new Render
|
||||
{
|
||||
Id = render.Id,
|
||||
@@ -513,6 +513,9 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
DurationSeconds = render.DurationSeconds,
|
||||
Created = render.Created,
|
||||
ProducedBy = render.ProducedBy,
|
||||
// As it arrived (checked against the server's when it records one), so a copy here is verified against it.
|
||||
Sha256 = sha,
|
||||
Kind = render.Kind,
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (filed is null) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
@@ -562,23 +565,37 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
return (string?)relative;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>A render's file in staging (resumed with Range; started over once if the partial copy no longer fits) and the name the server gives it.</summary>
|
||||
private static async Task<(string Part, string Name)> FetchRenderAsync(ISyncRemote remote, RenderDto render, string staging, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// A render's file in staging (resumed with Range; started over once if the partial copy no longer fits), the name the
|
||||
/// server gives it and its SHA-256 as it arrived (owner review 1, R9: copies and restores are verified against it). A
|
||||
/// file that does not match the SHA-256 the server records is fetched again once from the start, then refused.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The file arrived twice unlike the server's SHA-256 (<c>Errors.Sync.Hash</c>).</exception>
|
||||
private static async Task<(string Part, string Name, string Sha256)> FetchRenderAsync(ISyncRemote remote, RenderDto render, string staging,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var part = Path.Combine(staging, render.Id.ToString("N") + ".part");
|
||||
var expected = render.Sha256 is { Length: > 0 } recorded ? recorded.ToLowerInvariant() : null;
|
||||
var hashFailures = 0;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
string? name;
|
||||
try
|
||||
{
|
||||
string? name;
|
||||
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||||
name = await remote.DownloadRenderAsync(render.Id, file, cancellationToken).ConfigureAwait(false);
|
||||
return (part, SafeFileName(name) ?? render.Id.ToString("N"));
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
|
||||
{
|
||||
File.Delete(part);
|
||||
continue;
|
||||
}
|
||||
var fileName = SafeFileName(name) ?? render.Id.ToString("N");
|
||||
var sha = await ChronosClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false);
|
||||
if (expected is null || sha == expected) return (part, fileName, sha);
|
||||
// A partial copy resumed onto other bytes, or damage on the way: once more from the start, then refused.
|
||||
File.Delete(part);
|
||||
if (++hashFailures == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", fileName));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// What the videos library lists (owner review 1, R9): every member optional, combined with "and". The values are those of
|
||||
/// <c>GET /api/v1/videos</c> (<see cref="VideoQueryDto"/>).
|
||||
/// </summary>
|
||||
public sealed record VideoQuery
|
||||
{
|
||||
/// <summary>The most videos a page holds.</summary>
|
||||
public const int MaxLimit = 500;
|
||||
|
||||
/// <summary>Text in the sequence title, the preset name or the file name (any case).</summary>
|
||||
public string? Text { get; init; }
|
||||
|
||||
/// <summary><see cref="RenderKind.Video"/>, <see cref="RenderKind.Still"/> or <see cref="RenderKind.Sequence"/>; null for every kind.</summary>
|
||||
public string? Kind { get; init; }
|
||||
|
||||
/// <summary>A codec name as recorded (<c>h264</c>, <c>hevc</c>, <c>pngsequence</c>…); null for every codec.</summary>
|
||||
public string? Codec { get; init; }
|
||||
|
||||
/// <summary>The year the render was made (UTC).</summary>
|
||||
public int? Year { get; init; }
|
||||
|
||||
/// <summary>The renders of one sequence.</summary>
|
||||
public Guid? SequenceId { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="VideoSorts"/>; null for newest first.</summary>
|
||||
public string? Sort { get; init; }
|
||||
|
||||
/// <summary>The <see cref="VideoPage.Next"/> of the previous page; null for the first.</summary>
|
||||
public string? Cursor { get; init; }
|
||||
|
||||
/// <summary>Videos per page, 1..<see cref="MaxLimit"/>.</summary>
|
||||
public int Limit { get; init; } = 100;
|
||||
|
||||
/// <summary>The query of an API request (its limit clamped, the default when none is given).</summary>
|
||||
public static VideoQuery From(VideoQueryDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
return new VideoQuery
|
||||
{
|
||||
Text = dto.Q,
|
||||
Kind = dto.Kind,
|
||||
Codec = dto.Codec,
|
||||
Year = dto.Year,
|
||||
SequenceId = dto.Sequence,
|
||||
Sort = dto.Sort,
|
||||
Cursor = dto.Cursor,
|
||||
Limit = dto.Limit is { } limit ? Math.Clamp(limit, 1, MaxLimit) : 100,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A render as the videos library shows it: the render, its sequence and project, where its file is, and its copies.</summary>
|
||||
public sealed record VideoItem
|
||||
{
|
||||
public required Render Render { get; init; }
|
||||
|
||||
/// <summary>The display title of the render's sequence.</summary>
|
||||
public required string SequenceTitle { get; init; }
|
||||
|
||||
/// <summary>When the sequence's first photo was taken; null when unknown.</summary>
|
||||
public DateTime? SequenceFirstCapture { get; init; }
|
||||
|
||||
/// <summary>The project rendered (owner review 2, R8); null for a render of the sequence's settings.</summary>
|
||||
public string? ProjectName { get; init; }
|
||||
|
||||
/// <summary>The number of the project version rendered; null with <see cref="ProjectName"/>.</summary>
|
||||
public int? ProjectVersionNumber { get; init; }
|
||||
|
||||
/// <summary>Absolute path of the render's file (or folder, for an image sequence) on this host.</summary>
|
||||
public required string FullPath { get; init; }
|
||||
|
||||
/// <summary>The file is not at <see cref="FullPath"/>: shown as Missing, and a delete removes only its row.</summary>
|
||||
public bool Missing { get; init; }
|
||||
|
||||
/// <summary>Its verified copies in videos folders, oldest first.</summary>
|
||||
public IReadOnlyList<RenderCopy> Copies { get; init; } = [];
|
||||
|
||||
/// <summary>The library kind (<see cref="RenderKind.Of(Render)"/>).</summary>
|
||||
public string Kind => RenderKind.Of(Render);
|
||||
|
||||
/// <summary><see cref="VideoStates.Ok"/> or <see cref="VideoStates.Missing"/>.</summary>
|
||||
public string State => Missing ? VideoStates.Missing : VideoStates.Ok;
|
||||
|
||||
/// <summary>The file (or folder) name.</summary>
|
||||
public string FileName => Path.GetFileName(FullPath.TrimEnd('/', '\\'));
|
||||
}
|
||||
|
||||
/// <summary>One page of the videos library; <see cref="Next"/> is the cursor of the next page, null on the last one.</summary>
|
||||
/// <param name="Total">Videos matching the query on every page; null when not counted.</param>
|
||||
public sealed record VideoPage(IReadOnlyList<VideoItem> Items, string? Next, long? Total = null)
|
||||
{
|
||||
public static VideoPage Empty { get; } = new([], null, 0);
|
||||
}
|
||||
|
||||
/// <summary>A render a delete leaves where it is: <see cref="Reason"/> is one of <see cref="VideoBlockReasons"/>.</summary>
|
||||
/// <param name="Video">The render, when it exists.</param>
|
||||
public sealed record VideoBlocked(Guid RenderId, string Reason, VideoItem? Video = null);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of deleting renders into the trash (decision 17): the renders that go (a missing one only loses its row), the
|
||||
/// renders left where they are, and the plan's fingerprint, which the delete itself must give back. Copies in videos
|
||||
/// folders are never touched.
|
||||
/// </summary>
|
||||
public sealed record VideoDeletePlan(IReadOnlyList<VideoItem> Items, IReadOnlyList<VideoBlocked> Blocked, string Fingerprint)
|
||||
{
|
||||
/// <summary>The bytes that move into the trash (missing files count nothing).</summary>
|
||||
public long Bytes => Items.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
|
||||
}
|
||||
|
||||
/// <summary>What a delete did: the renders moved into the trash (or, missing, whose rows went), those left, and the trash entries made.</summary>
|
||||
/// <param name="TrashEntries">The names of the entries made (<see cref="VideoTrashNames"/>), each restorable.</param>
|
||||
public sealed record VideoDeleteResult(IReadOnlyList<VideoItem> Deleted, IReadOnlyList<VideoBlocked> Blocked, IReadOnlyList<string> TrashEntries);
|
||||
|
||||
/// <summary>
|
||||
/// The parameters of a <see cref="JobKind.VideoCopy"/> job (decision 16): the renders to copy into <see cref="Folder"/>,
|
||||
/// each hash-verified before it takes its name (a free one, " (2)" on a collision), the render never touched.
|
||||
/// </summary>
|
||||
/// <param name="RenderIds">The renders, in the order they are copied.</param>
|
||||
/// <param name="Folder">The videos folder (absolute), checked again when the job runs.</param>
|
||||
/// <param name="FromServer">On the desktop: the renders are the signed-in server's, downloaded into the folder.</param>
|
||||
/// <param name="RequestedBy">The user (server) or PC (desktop) recorded as <see cref="RenderCopy.CopiedBy"/>.</param>
|
||||
/// <param name="Server">With <paramref name="FromServer"/>: the server the renders are downloaded from (its address as the
|
||||
/// desktop's connections name it, <see cref="Sync.ISyncConnector.ConnectAsync"/>).</param>
|
||||
/// <param name="SequenceIds">With <paramref name="FromServer"/>: the server's sequence of each render, in the order of
|
||||
/// <paramref name="RenderIds"/>; its manifest gives the SHA-256 a download is verified against.</param>
|
||||
public sealed record VideoCopyParameters(IReadOnlyList<Guid> RenderIds, string Folder, bool FromServer = false, string? RequestedBy = null,
|
||||
string? Server = null, IReadOnlyList<Guid>? SequenceIds = null)
|
||||
{
|
||||
public string ToJson() => JsonSerializer.Serialize(this, VideoJson.Default.VideoCopyParameters);
|
||||
|
||||
/// <summary>The parameters of a job; null when it has none that read.</summary>
|
||||
public static VideoCopyParameters? Read(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, VideoJson.Default.VideoCopyParameters) is { RenderIds: not null, Folder.Length: > 0 } parameters ? parameters : null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The error codes of the videos library (<see cref="VideoLibraryException.Code"/>), the same as the server's API errors:
|
||||
/// each has a server message <c>Server.Error.<Code></c> and a desktop message <c>Errors.Videos.*</c>.
|
||||
/// </summary>
|
||||
public static class VideoErrors
|
||||
{
|
||||
/// <summary>No videos folder is set (409).</summary>
|
||||
public const string FolderUnset = "videos_folder_unset";
|
||||
|
||||
/// <summary>The videos folder lies inside an archive root or the workspace (422).</summary>
|
||||
public const string FolderInvalid = "videos_folder_invalid";
|
||||
|
||||
/// <summary>The plan of a delete changed since it was made (409; nothing moved).</summary>
|
||||
public const string PlanChanged = "plan_changed";
|
||||
|
||||
/// <summary>A copy, or a trashed video being restored, does not match its render's SHA-256.</summary>
|
||||
public const string HashMismatch = "trash_hash_mismatch";
|
||||
|
||||
/// <summary>Not enough free space in the videos folder (507).</summary>
|
||||
public const string NoSpace = "videos_no_space";
|
||||
|
||||
/// <summary>A trashed video's sequence is not in the library: restore the sequence first (409).</summary>
|
||||
public const string SequenceGone = "sequence_gone";
|
||||
|
||||
/// <summary>A send, an upload or a copy of the render is running (409).</summary>
|
||||
public const string Busy = "video_busy";
|
||||
}
|
||||
|
||||
/// <summary>A videos library operation refused with one of <see cref="VideoErrors"/>; nothing was changed.</summary>
|
||||
public sealed class VideoLibraryException(string code, string message) : InvalidOperationException(message)
|
||||
{
|
||||
public string Code { get; } = code;
|
||||
}
|
||||
|
||||
/// <summary>The names of the videos trash entries (decision 17): <c>videos-<render id>-<UTC ticks></c>, listed as kind "videos".</summary>
|
||||
public static class VideoTrashNames
|
||||
{
|
||||
/// <summary>The prefix of every videos entry name.</summary>
|
||||
public const string Prefix = "videos-";
|
||||
|
||||
/// <summary>The folder of the videos area inside an archive's trash, which holds the entries and their records.</summary>
|
||||
public const string FolderName = "videos";
|
||||
|
||||
/// <summary>The entry name of render <paramref name="renderId"/> deleted at <paramref name="deletedAt"/>.</summary>
|
||||
public static string EntryName(Guid renderId, DateTimeOffset deletedAt) =>
|
||||
Prefix + renderId.ToString("D") + "-" + deletedAt.UtcTicks.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> is a videos entry name (and nothing else: no path, no other entry's name).</summary>
|
||||
public static bool IsEntryName(string? name) => TryParse(name, out _, out _);
|
||||
|
||||
/// <summary>The render id and the UTC ticks of a videos entry name; false for any other name.</summary>
|
||||
public static bool TryParse(string? name, out Guid renderId, out long ticks)
|
||||
{
|
||||
renderId = Guid.Empty;
|
||||
ticks = 0;
|
||||
if (name is null || !name.StartsWith(Prefix, StringComparison.Ordinal)) return false;
|
||||
var rest = name.AsSpan(Prefix.Length);
|
||||
// A "D" guid is 36 characters; then "-" and the ticks.
|
||||
return rest.Length > 37 && rest[36] == '-' && Guid.TryParseExact(rest[..36], "D", out renderId)
|
||||
&& long.TryParse(rest[37..], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out ticks);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The videos library of one index (owner review 1, R9): every render of its archives in one list, deleted into the trash
|
||||
/// and restored by id, and copied hash-verified into a videos folder. The desktop's Videos section and the server's
|
||||
/// <c>/api/v1/videos</c> endpoints use it; <see cref="Archiving.ArchiveService.Videos"/> is the instance of an archive engine.
|
||||
/// </summary>
|
||||
public interface IVideoLibrary
|
||||
{
|
||||
/// <summary>False for the groundwork stub (<see cref="NotImplementedVideoLibrary"/>): callers show no library then.</summary>
|
||||
bool IsAvailable { get; }
|
||||
|
||||
/// <summary>One page of the renders matching <paramref name="query"/>, each with its copies and whether its file is there.</summary>
|
||||
Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes <paramref name="renderIds"/> as planned: each file into <c>.chronos/trash/videos/</c> of its archive with a
|
||||
/// record, its row removed and its sequence's render count recounted; a missing file loses only its row.
|
||||
/// </summary>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.PlanChanged"/>: <paramref name="fingerprint"/> is not the plan's now; nothing moved.</exception>
|
||||
Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Brings a videos trash entry of archive <paramref name="archiveId"/> back: the file re-hashed against its record, moved
|
||||
/// back (to a free name when its own is taken) and its row inserted again with the same render id.
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.HashMismatch"/> or <see cref="VideoErrors.SequenceGone"/>; nothing moved.</exception>
|
||||
Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder (<see cref="VideoErrors.FolderUnset"/> or
|
||||
/// <see cref="VideoErrors.FolderInvalid"/>); null when it can.
|
||||
/// </summary>
|
||||
string? FolderProblem(string? folder);
|
||||
|
||||
/// <summary>The <see cref="JobKind.VideoCopy"/> job copying <paramref name="parameters"/>' renders; enqueue it on the host's engine.</summary>
|
||||
/// <exception cref="VideoLibraryException">The folder cannot be the videos folder (<see cref="FolderProblem"/>).</exception>
|
||||
ArchiveJobRequest CopyJob(VideoCopyParameters parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The videos library until its parcel lands (phase 5 groundwork): lists nothing, finds nothing, and refuses every change
|
||||
/// with <see cref="NotImplementedException"/>; registered so the server and the desktop compile against
|
||||
/// <see cref="IVideoLibrary"/>.
|
||||
/// </summary>
|
||||
public sealed class NotImplementedVideoLibrary : IVideoLibrary
|
||||
{
|
||||
public static NotImplementedVideoLibrary Instance { get; } = new();
|
||||
|
||||
public bool IsAvailable => false;
|
||||
|
||||
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(VideoPage.Empty);
|
||||
|
||||
public Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult<VideoItem?>(null);
|
||||
|
||||
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
|
||||
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
|
||||
public Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
|
||||
public string? FolderProblem(string? folder) => string.IsNullOrWhiteSpace(folder) ? VideoErrors.FolderUnset : null;
|
||||
|
||||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters) => throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(VideoCopyParameters))]
|
||||
internal sealed partial class VideoJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,243 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.VideoCopy"/> (owner review 1, R9, decision 16): copies renders into the videos folder, on the desktop
|
||||
/// and on the server. The folder is checked again first, and the free space for every render still to copy, so a copy that
|
||||
/// cannot fit fails before it writes anything. Each render is written as <c>.incoming-<id>.part</c> in the folder and
|
||||
/// flushed, hashed and compared with the render's SHA-256 (the render hashed first when it never was, and remembered; an
|
||||
/// image sequence's folder file by file against its own files), then renamed without overwriting to its own name or a free
|
||||
/// " (2)" one, and recorded in <c>render_copies</c>. A copy that does not match is deleted and that render fails; the
|
||||
/// render itself is never touched. On the desktop a server's render (<see cref="VideoCopyParameters.FromServer"/>) is
|
||||
/// downloaded into the part file and checked against the SHA-256 its server's manifest gives. Checkpoint:
|
||||
/// <c>done:<n></c>, the renders done; leftovers of an interrupted copy are removed before it starts again.
|
||||
/// </summary>
|
||||
internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary library) : IJobHandler
|
||||
{
|
||||
private const string Prefix = "done:";
|
||||
|
||||
public JobKind Kind => JobKind.VideoCopy;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var parameters = VideoCopyParameters.Read(context.Job.ParametersJson) ?? throw new InvalidDataException(Loc.L("Errors.Render.Parameters"));
|
||||
if (await library.FolderProblemAsync(parameters.Folder, ct).ConfigureAwait(false) is { } problem) throw VideoLibrary.Refusal(problem);
|
||||
var folder = parameters.Folder;
|
||||
Directory.CreateDirectory(folder);
|
||||
var ids = parameters.RenderIds;
|
||||
var start = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal)
|
||||
&& int.TryParse(checkpoint.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var done)
|
||||
? int.Min(done, ids.Count)
|
||||
: 0;
|
||||
foreach (var id in ids.Skip(start)) Remove(VideosFolder.PartPath(folder, id));
|
||||
await context.ReportAsync(start, ids.Count, Loc.L("Videos.Job.Copying")).ConfigureAwait(false);
|
||||
|
||||
using var remote = parameters.FromServer ? await ConnectAsync(parameters, ct).ConfigureAwait(false) : null;
|
||||
var sources = new List<Source?>(ids.Count);
|
||||
for (var i = 0; i < ids.Count; i++)
|
||||
sources.Add(i < start ? null : await SourceAsync(context, parameters, remote, i, ct).ConfigureAwait(false));
|
||||
// Every render still to copy must fit before anything is written.
|
||||
var needed = sources.Where(s => s is not null).Sum(s => s!.Bytes);
|
||||
if (VideosFolder.FreeBytes(folder, library.FreeSpace) is { } free && free < needed)
|
||||
throw new VideoLibraryException(VideoErrors.NoSpace, Loc.L("Errors.Videos.NoSpace", Megabytes(needed - free)));
|
||||
|
||||
var failed = 0;
|
||||
for (var i = start; i < ids.Count; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (sources[i] is not { } source)
|
||||
{
|
||||
failed++;
|
||||
}
|
||||
else if (!await CopyAsync(context, parameters, remote, source, ct).ConfigureAwait(false))
|
||||
{
|
||||
failed++;
|
||||
}
|
||||
await context.CheckpointAsync(Prefix + (i + 1).ToString(CultureInfo.InvariantCulture), i + 1, ids.Count).ConfigureAwait(false);
|
||||
}
|
||||
if (failed > 0) throw new InvalidOperationException(Loc.L("Errors.Render.Failed", failed, ids.Count - start));
|
||||
}
|
||||
|
||||
/// <summary>What one render's copy reads: its id, name, size, and the SHA-256 it is verified against (null: an image sequence).</summary>
|
||||
/// <param name="Path">The render's file or folder on this host; null for a server's render.</param>
|
||||
/// <param name="Sequence">The server's sequence of a server's render.</param>
|
||||
private sealed record Source(Guid RenderId, string Name, string? Path, bool IsFolder, long Bytes, string? Sha256, Guid? Sequence);
|
||||
|
||||
/// <summary>The render at <paramref name="index"/> as it is now; null (logged) when it is gone or its file is missing.</summary>
|
||||
private async Task<Source?> SourceAsync(JobContext context, VideoCopyParameters parameters, ISyncRemote? remote, int index, CancellationToken ct)
|
||||
{
|
||||
var id = parameters.RenderIds[index];
|
||||
if (remote is not null)
|
||||
{
|
||||
var sequence = parameters.SequenceIds is { } sequences && index < sequences.Count ? sequences[index] : (Guid?)null;
|
||||
var render = sequence is { } s ? (await remote.GetManifestAsync(s, ct).ConfigureAwait(false)).Renders.FirstOrDefault(r => r.Id == id) : null;
|
||||
if (render is null)
|
||||
{
|
||||
context.Log(Loc.L("Videos.Log.Missing", id.ToString("D")));
|
||||
return null;
|
||||
}
|
||||
// Named by the server as it downloads.
|
||||
return new Source(id, id.ToString("N"), null, false, render.Bytes, render.Sha256, sequence);
|
||||
}
|
||||
if (await library.GetAsync(id, ct).ConfigureAwait(false) is not { } item || item.Missing)
|
||||
{
|
||||
context.Log(Loc.L("Videos.Log.Missing", (await library.GetAsync(id, ct).ConfigureAwait(false))?.FileName ?? id.ToString("D")));
|
||||
return null;
|
||||
}
|
||||
var folder = Directory.Exists(item.FullPath);
|
||||
string? sha = null;
|
||||
if (!folder)
|
||||
{
|
||||
sha = item.Render.Sha256;
|
||||
if (sha is null)
|
||||
{
|
||||
// A render of before migration 0010: hashed now, and remembered.
|
||||
await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false);
|
||||
sha = await ContentHash.Sha256Async(item.FullPath, cancellationToken: ct).ConfigureAwait(false);
|
||||
await db.Renders.SetSha256Async(id, sha, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
var bytes = folder ? new DirectoryInfo(item.FullPath).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length) : new FileInfo(item.FullPath).Length;
|
||||
return new Source(id, item.FileName, item.FullPath, folder, bytes, sha, null);
|
||||
}
|
||||
|
||||
/// <summary>Copies one render, verified, under a free name, and records the copy; false (logged) when the copy did not match.</summary>
|
||||
private async Task<bool> CopyAsync(JobContext context, VideoCopyParameters parameters, ISyncRemote? remote, Source source, CancellationToken ct)
|
||||
{
|
||||
var folder = parameters.Folder;
|
||||
var part = VideosFolder.PartPath(folder, source.RenderId);
|
||||
Remove(part);
|
||||
string? sha;
|
||||
try
|
||||
{
|
||||
if (remote is not null)
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
var given = await remote.DownloadRenderAsync(source.RenderId, file, ct).ConfigureAwait(false);
|
||||
file.Flush(flushToDisk: true);
|
||||
source = source with { Name = SyncTransfers.SafeFileName(given) ?? source.Name };
|
||||
}
|
||||
sha = await Verified(part, source.Sha256, context, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (source.IsFolder)
|
||||
{
|
||||
// An image sequence: each file copied and compared with its own.
|
||||
foreach (var file in Directory.EnumerateFiles(source.Path!, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var target = Path.Combine(part, Path.GetRelativePath(source.Path!, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
await VideoTrash.CopyFileAsync(file, target, ct).ConfigureAwait(false);
|
||||
var expected = await ContentHash.Sha256Async(file, cancellationToken: ct).ConfigureAwait(false);
|
||||
if (await Verified(target, expected, context, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
Mismatch(context, source, part);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Directory.CreateDirectory(part);
|
||||
sha = null;
|
||||
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The copy takes its name (never overwriting: another free name when one appeared meanwhile) and is recorded.</summary>
|
||||
private async Task Commit(JobContext context, VideoCopyParameters parameters, Source source, string part, string? sha)
|
||||
{
|
||||
string target;
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
target = VideosFolder.FreeName(parameters.Folder, source.Name, source.IsFolder);
|
||||
try
|
||||
{
|
||||
if (source.IsFolder) Directory.Move(part, target);
|
||||
else File.Move(part, target, overwrite: false);
|
||||
break;
|
||||
}
|
||||
catch (IOException) when (attempt < 5 && (File.Exists(target) || Directory.Exists(target)))
|
||||
{
|
||||
// Taken between the look and the move: the next free name.
|
||||
}
|
||||
}
|
||||
var bytes = source.IsFolder ? new DirectoryInfo(target).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length) : new FileInfo(target).Length;
|
||||
await db.RenderCopies.InsertAsync(new RenderCopy
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
RenderId = source.RenderId,
|
||||
Path = target,
|
||||
Sha256 = sha,
|
||||
Bytes = bytes,
|
||||
CopiedAt = DateTimeOffset.UtcNow,
|
||||
CopiedBy = parameters.RequestedBy,
|
||||
}, CancellationToken.None).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Videos.Log.Copied", source.Name, target));
|
||||
Log.Info("videos", $"Render {source.RenderId} copied to {target} ({bytes} bytes, verified)");
|
||||
}
|
||||
|
||||
/// <summary>The SHA-256 of the copy at <paramref name="path"/> when it matches <paramref name="expected"/> (any, when none is known); null otherwise.</summary>
|
||||
private static async Task<string?> Verified(string path, string? expected, JobContext context, CancellationToken ct)
|
||||
{
|
||||
await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false);
|
||||
var sha = await ContentHash.Sha256Async(path, cancellationToken: ct).ConfigureAwait(false);
|
||||
return expected is null || string.Equals(sha, expected, StringComparison.OrdinalIgnoreCase) ? sha : null;
|
||||
}
|
||||
|
||||
private static void Mismatch(JobContext context, Source source, string part)
|
||||
{
|
||||
Remove(part);
|
||||
context.Log(Loc.L("Videos.Log.Mismatch", source.Name));
|
||||
Log.Warning("videos", $"The copy of render {source.RenderId} did not match it; the copy was removed");
|
||||
}
|
||||
|
||||
private async Task<ISyncRemote> ConnectAsync(VideoCopyParameters parameters, CancellationToken ct)
|
||||
{
|
||||
if (library.Servers is not { } servers || parameters.Server is not { Length: > 0 } server
|
||||
|| await servers.ConnectAsync(server, ct).ConfigureAwait(false) is not { } remote)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked"));
|
||||
return remote;
|
||||
}
|
||||
|
||||
private static string Megabytes(long bytes) => Housekeeping.CleanupSteps.Megabytes(bytes);
|
||||
|
||||
private static void Remove(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
|
||||
else if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"{path} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// The videos library of one index (owner review 1, R9): every render of its archives in one list, newest first unless
|
||||
/// asked, each with its sequence, its project, whether its file is there and its copies; deleted into its archive's trash
|
||||
/// after a dry run whose fingerprint the delete gives back (decision 17), restored by id (decision 18), and copied
|
||||
/// hash-verified into a videos folder by a <see cref="JobKind.VideoCopy"/> job (decision 16). The renders themselves are
|
||||
/// never changed, and copies in a videos folder are never touched.
|
||||
/// </summary>
|
||||
public sealed class VideoLibrary : IVideoLibrary
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
|
||||
internal VideoLibrary(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
Trash = new VideoTrash(db, writer);
|
||||
}
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
/// <summary>
|
||||
/// Folders a videos folder may not lie in besides the archive roots (decision 15): the desktop's workspace. Asked each
|
||||
/// time a folder is checked.
|
||||
/// </summary>
|
||||
public Func<IReadOnlyList<string>>? ProtectedFolders { get; set; }
|
||||
|
||||
/// <summary>The desktop's signed-in servers: a copy of a server's renders (<see cref="VideoCopyParameters.FromServer"/>) downloads through them.</summary>
|
||||
public ISyncConnector? Servers { get; set; }
|
||||
|
||||
/// <summary>How the host measures free space under a folder; null: the folder's drive.</summary>
|
||||
public Func<string, long?>? FreeSpace => _writer.Options.FreeSpace;
|
||||
|
||||
internal VideoTrash Trash { get; }
|
||||
|
||||
public async Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var (renders, next, total) = await _db.Renders.ListPageAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
return new VideoPage(await ItemsAsync(renders, cancellationToken).ConfigureAwait(false), next, total);
|
||||
}
|
||||
|
||||
public async Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) =>
|
||||
await _db.Renders.GetAsync(renderId, cancellationToken).ConfigureAwait(false) is { } render
|
||||
? (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);
|
||||
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
|
||||
var items = new List<VideoItem>();
|
||||
var blocked = new List<VideoBlocked>();
|
||||
foreach (var id in renderIds.Distinct())
|
||||
{
|
||||
if (await GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item) blocked.Add(new VideoBlocked(id, VideoBlockReasons.NotFound));
|
||||
else if (busy.Contains(id)) blocked.Add(new VideoBlocked(id, VideoBlockReasons.Busy, item));
|
||||
else items.Add(item);
|
||||
}
|
||||
return new VideoDeletePlan(items, blocked, Fingerprint(items, blocked));
|
||||
}
|
||||
|
||||
public async Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renderIds);
|
||||
var plan = await PlanDeleteAsync(renderIds, cancellationToken).ConfigureAwait(false);
|
||||
if (!string.Equals(plan.Fingerprint, fingerprint, StringComparison.Ordinal))
|
||||
throw new VideoLibraryException(VideoErrors.PlanChanged, Loc.L("Errors.Videos.Fingerprint"));
|
||||
var deleted = new List<VideoItem>();
|
||||
var entries = new List<string>();
|
||||
var archives = new Dictionary<Guid, Archive?>();
|
||||
foreach (var item in plan.Items)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var archive = await ArchiveOfAsync(archives, item.Render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (archive is null)
|
||||
{
|
||||
// The sequence left the index since the plan: so did its renders.
|
||||
continue;
|
||||
}
|
||||
if (await Trash.DeleteAsync(archive, item.Render, deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry.Name);
|
||||
deleted.Add(item);
|
||||
}
|
||||
return new VideoDeleteResult(deleted, plan.Blocked, entries);
|
||||
}
|
||||
|
||||
public async Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId));
|
||||
return await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Settles the deletes into the trash a crash interrupted in <paramref name="archive"/> (<see cref="VideoTrash.RecoverAsync"/>).</summary>
|
||||
public Task<int> RecoverAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
return Trash.RecoverAsync(archive, cancellationToken);
|
||||
}
|
||||
|
||||
public string? FolderProblem(string? folder)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
// Asked from the UI thread and the server's endpoints alike: the roots are read off any synchronisation context.
|
||||
var roots = Task.Run(() => _db.Archives.ListAsync()).GetAwaiter().GetResult().Select(a => a.RootPath);
|
||||
return VideosFolder.Problem(folder, [.. roots, .. ProtectedFolders?.Invoke() ?? []]);
|
||||
}
|
||||
|
||||
/// <summary><see cref="FolderProblem"/> without blocking: what the copy job checks again when it runs.</summary>
|
||||
internal async Task<string?> FolderProblemAsync(string? folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var roots = (await _db.Archives.ListAsync(cancellationToken).ConfigureAwait(false)).Select(a => a.RootPath);
|
||||
return VideosFolder.Problem(folder, [.. roots, .. ProtectedFolders?.Invoke() ?? []]);
|
||||
}
|
||||
|
||||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
if (FolderProblem(parameters.Folder) is { } problem) throw Refusal(problem);
|
||||
if (parameters.RenderIds.Count == 0) throw new ArgumentException("No render to copy.", nameof(parameters));
|
||||
var ids = parameters.RenderIds.Distinct().ToList();
|
||||
var folder = VideosFolder.Normalize(parameters.Folder);
|
||||
return new ArchiveJobRequest(JobKind.VideoCopy, ids, Loc.L("Videos.Target.Copy", ids.Count.ToString(Loc.Culture)),
|
||||
(parameters with { RenderIds = ids, Folder = folder }).ToJson(), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>The exception of a videos folder that cannot be used, with its localised message.</summary>
|
||||
internal static VideoLibraryException Refusal(string code) => new(code, Loc.L(code == VideoErrors.FolderUnset ? "Errors.Videos.FolderUnset" : "Errors.Videos.FolderInsideArchive"));
|
||||
|
||||
/// <summary>
|
||||
/// The fingerprint of a delete plan: SHA-256 of each render's id, path, size, creation and whether its file is there, and
|
||||
/// of each render left where it is with why, in id order. Another render, a render moved, grown, gone or busy since gives
|
||||
/// another fingerprint.
|
||||
/// </summary>
|
||||
internal static string Fingerprint(IEnumerable<VideoItem> items, IEnumerable<VideoBlocked> blocked)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
foreach (var item in items.OrderBy(i => i.Render.Id))
|
||||
{
|
||||
var r = item.Render;
|
||||
text.Append(CultureInfo.InvariantCulture, $"{r.Id:N}|{r.OutputPath}|{r.Bytes}|{r.Created.UtcTicks}|{(item.Missing ? "missing" : "ok")}\n");
|
||||
}
|
||||
foreach (var block in blocked.OrderBy(b => b.RenderId)) text.Append(CultureInfo.InvariantCulture, $"{block.RenderId:N}|blocked|{block.Reason}\n");
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
|
||||
/// <summary>The renders a running or paused job holds: those a copy works on (its targets are render ids).</summary>
|
||||
private async Task<HashSet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
foreach (var hold in await _db.Jobs.ListHoldsAsync(null, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (hold.Kind == JobKind.VideoCopy) busy.UnionWith(hold.TargetIds);
|
||||
}
|
||||
return busy;
|
||||
}
|
||||
|
||||
/// <summary>The library items of <paramref name="renders"/>: each with its sequence, project, file state and copies, in their order.</summary>
|
||||
private async Task<IReadOnlyList<VideoItem>> ItemsAsync(IReadOnlyList<Render> renders, CancellationToken cancellationToken)
|
||||
{
|
||||
if (renders.Count == 0) return [];
|
||||
var copies = await _db.RenderCopies.ListByRendersAsync([.. renders.Select(r => r.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var sequences = new Dictionary<Guid, Sequence?>();
|
||||
var archives = new Dictionary<Guid, Archive?>();
|
||||
var projects = new Dictionary<Guid, string?>();
|
||||
var versions = new Dictionary<Guid, int?>();
|
||||
var items = new List<VideoItem>(renders.Count);
|
||||
foreach (var render in renders)
|
||||
{
|
||||
if (!sequences.TryGetValue(render.SequenceId, out var sequence))
|
||||
sequences[render.SequenceId] = sequence = await _db.Sequences.GetAsync(render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (sequence is null) continue;
|
||||
if (!archives.TryGetValue(sequence.ArchiveId, out var archive))
|
||||
archives[sequence.ArchiveId] = archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
|
||||
string? projectName = null;
|
||||
if (render.ProjectId is { } projectId && !projects.TryGetValue(projectId, out projectName))
|
||||
projects[projectId] = projectName = (await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false))?.Name;
|
||||
int? number = null;
|
||||
if (render.ProjectVersionId is { } versionId && !versions.TryGetValue(versionId, out number))
|
||||
versions[versionId] = number = (await _db.Projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false))?.Number;
|
||||
var full = archive is null || Path.IsPathRooted(render.OutputPath) ? render.OutputPath : SyncService.RenderFile(archive, render);
|
||||
items.Add(new VideoItem
|
||||
{
|
||||
Render = render,
|
||||
SequenceTitle = sequence.DisplayTitle,
|
||||
SequenceFirstCapture = sequence.FirstCapture,
|
||||
ProjectName = projectName,
|
||||
ProjectVersionNumber = projectName is null ? null : number,
|
||||
FullPath = full,
|
||||
Missing = !File.Exists(full) && !Directory.Exists(full),
|
||||
Copies = copies.TryGetValue(render.Id, out var made) ? made : [],
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private async Task<Archive?> ArchiveOfAsync(Dictionary<Guid, Archive?> known, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } sequence) return null;
|
||||
if (!known.TryGetValue(sequence.ArchiveId, out var archive))
|
||||
known[sequence.ArchiveId] = archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
|
||||
return archive;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>One file of a trashed image sequence, as it was when it went: its path inside the folder, size and SHA-256.</summary>
|
||||
internal sealed record VideoTrashFile(string Path, long Size, string Sha256);
|
||||
|
||||
/// <summary>
|
||||
/// What the trash keeps next to a deleted render (decision 17): the render's row, where its file was, the SHA-256 it is
|
||||
/// restored against (each file's, for an image sequence's folder), its sequence, and who deleted it when.
|
||||
/// </summary>
|
||||
/// <param name="Name">The file (or folder) name inside the entry's folder: the render's own name.</param>
|
||||
/// <param name="OriginalPath">The absolute path the render was at.</param>
|
||||
/// <param name="SequenceFolder">The sequence's archive-relative folder at deletion: a restore follows a Reorganize since.</param>
|
||||
internal sealed record VideoTrashRecord(Render Render, string Name, string OriginalPath, Guid ArchiveId, Guid SequenceId, string SequenceTitle,
|
||||
string SequenceFolder, string? Sha256, IReadOnlyList<VideoTrashFile>? Files, int FileCount, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
|
||||
/// <summary>
|
||||
/// The videos area of an archive's trash (owner review 1, R9, decisions 17 and 18): <c>.chronos/trash/videos/</c>, which
|
||||
/// holds a folder per deleted render (<c><render id>-<UTC ticks></c>, the entry name without its
|
||||
/// <see cref="VideoTrashNames.Prefix"/>) with the render's file or folder inside, and its record next to it. A delete runs
|
||||
/// under the sequence's lease: the record is written first under a pending name (the journal, never listed), then the file
|
||||
/// moves (renamed on its volume; copied, verified and deleted from another one), then the row goes and the record takes its
|
||||
/// name. A delete a crash interrupted is settled by <see cref="RecoverAsync"/>: completed when the file reached the
|
||||
/// trash, undone otherwise. Records live under <c>trash/videos/</c>, so an older Chronos never reads one as a sequence's.
|
||||
/// </summary>
|
||||
internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
private const string RecordExtension = ".json";
|
||||
|
||||
/// <summary>The suffix of a record whose delete is under way: the journal a crash leaves.</summary>
|
||||
internal const string PendingSuffix = ".pending";
|
||||
|
||||
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; }
|
||||
|
||||
/// <summary>Tests: stop a delete right after its file moved, as a crash would (the journal stays).</summary>
|
||||
internal bool CrashAfterMove { get; set; }
|
||||
|
||||
/// <summary>The videos area of an archive's trash.</summary>
|
||||
public static string Directory(ArchivePaths archive) => Path.Combine(SequenceTrash.TrashDirectory(archive), VideoTrashNames.FolderName);
|
||||
|
||||
/// <summary>The entry's folder and record on disk.</summary>
|
||||
internal static (string Folder, string Record) Location(ArchivePaths paths, string name)
|
||||
{
|
||||
var folder = Path.Combine(Directory(paths), DiskName(name));
|
||||
return (folder, folder + RecordExtension);
|
||||
}
|
||||
|
||||
/// <summary>The videos entries of an archive's trash (records whose folder is gone, or whose delete is under way, left out).</summary>
|
||||
internal static IReadOnlyList<TrashEntry> List(Archive archive, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = Directory(new ArchivePaths(archive.RootPath));
|
||||
if (!System.IO.Directory.Exists(folder)) return [];
|
||||
var entries = new List<TrashEntry>();
|
||||
foreach (var path in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!path.EndsWith(RecordExtension, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var disk = Path.GetFileNameWithoutExtension(path);
|
||||
if (!System.IO.Directory.Exists(Path.Combine(folder, disk)) || ReadRecord(path) is not { } record) continue;
|
||||
entries.Add(Entry(archive.Id, VideoTrashNames.Prefix + disk, record));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>A videos entry as the trash lists it, read from its record now; null when it is not one or cannot be read.</summary>
|
||||
internal static TrashEntry? ReadListed(ArchivePaths paths, Guid archiveId, string name) =>
|
||||
VideoTrashNames.IsEntryName(name) && ReadRecord(Location(paths, name).Record) is { } record ? Entry(archiveId, name, record) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Moves <paramref name="render"/>'s file into the trash with its record, and removes its row (its sequence's render count
|
||||
/// recounted); a render whose file is missing loses only its row. Returns the entry made; null when only the row went
|
||||
/// (or the render was gone already).
|
||||
/// </summary>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer holds the sequence.</exception>
|
||||
internal async Task<TrashEntry?> DeleteAsync(Archive archive, Render render, string? deletedBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var sequence = await db.Sequences.GetAsync(render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await db.Renders.GetAsync(render.Id, cancellationToken).ConfigureAwait(false) is not { } row) return null;
|
||||
var source = Sync.SyncService.RenderFile(archive, row);
|
||||
var isFile = File.Exists(source);
|
||||
if (!isFile && !System.IO.Directory.Exists(source))
|
||||
{
|
||||
await db.Renders.DeleteAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
Log.Info("videos", $"Render {row.Id} ({row.OutputPath}) removed from the index: its file is missing");
|
||||
return null;
|
||||
}
|
||||
string? sha = null;
|
||||
IReadOnlyList<VideoTrashFile>? files = null;
|
||||
long bytes;
|
||||
if (isFile)
|
||||
{
|
||||
// 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
|
||||
{
|
||||
files = await HashFolderAsync(source, cancellationToken).ConfigureAwait(false);
|
||||
bytes = files.Sum(f => f.Size);
|
||||
}
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var name = VideoTrashNames.EntryName(row.Id, now);
|
||||
var (entryFolder, recordPath) = Location(paths, name);
|
||||
var fileName = Path.GetFileName(source.TrimEnd('/', '\\'));
|
||||
var record = new VideoTrashRecord(row with { Sha256 = sha ?? row.Sha256 }, fileName, source, archive.Id, row.SequenceId,
|
||||
sequence?.DisplayTitle ?? fileName, sequence?.Folder ?? string.Empty, sha, files, files?.Count ?? 1, bytes, now, deletedBy);
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), writer.Options.Owner, writer.Options.LeaseWait,
|
||||
writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
System.IO.Directory.CreateDirectory(entryFolder);
|
||||
// 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
|
||||
{
|
||||
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 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 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)");
|
||||
return Entry(archive.Id, name, record);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a videos entry back: its file re-hashed against its record (refused on a mismatch), its sequence in the index
|
||||
/// (refused otherwise: restore the sequence first), then moved back where it was (into the sequence's folder as it is now
|
||||
/// after a Reorganize; a free name when its own is taken) and its row inserted again with the same render id.
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.HashMismatch"/> or <see cref="VideoErrors.SequenceGone"/>; nothing moved.</exception>
|
||||
/// <exception cref="InvalidOperationException">The index holds a render of that id already; nothing moved.</exception>
|
||||
internal async Task<Render> RestoreAsync(Archive archive, string name, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (!VideoTrashNames.IsEntryName(name)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var (entryFolder, recordPath) = Location(paths, name);
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), writer.Options.Owner, writer.Options.LeaseWait,
|
||||
writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var trashed = Path.Combine(entryFolder, record.Name);
|
||||
if (!File.Exists(trashed) && !System.IO.Directory.Exists(trashed)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
if (await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
throw new InvalidOperationException(Loc.L("Server.Error.RenderExists"));
|
||||
var sequence = await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new VideoLibraryException(VideoErrors.SequenceGone, Loc.L("Errors.Videos.SequenceGone", record.SequenceTitle));
|
||||
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))
|
||||
{
|
||||
// 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();
|
||||
removed = await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
|
||||
restored = record.Render with { SequenceId = sequence.Id, OutputPath = Stored(paths, target), Sha256 = record.Sha256 };
|
||||
try
|
||||
{
|
||||
await db.Renders.InsertAsync(restored, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("videos", $"{target} could not be indexed again; it goes back into the trash", ex);
|
||||
// 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);
|
||||
if (removed) RemoveEmpty(entryFolder);
|
||||
Log.Info("videos", $"{name} restored to {restored.OutputPath}");
|
||||
return restored;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the deletes a crash interrupted in <paramref name="archive"/>'s trash (their pending records): a delete whose
|
||||
/// file reached the trash is completed (the row goes, the record takes its name), any other is undone (what was copied
|
||||
/// goes, the render stays where it is). Each runs under its sequence's lease when the index still holds the sequence.
|
||||
/// </summary>
|
||||
internal async Task<int> RecoverAsync(Archive archive, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var folder = Directory(paths);
|
||||
if (!System.IO.Directory.Exists(folder) || ArchiveVolume.Probe(paths) != ArchiveAvailability.Online) return 0;
|
||||
var settled = 0;
|
||||
foreach (var pending in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension + PendingSuffix).ToList())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var recordPath = pending[..^PendingSuffix.Length];
|
||||
var entryFolder = recordPath[..^RecordExtension.Length];
|
||||
if (ReadRecord(pending) is not { } record)
|
||||
{
|
||||
Log.Warning("videos", $"The pending trash record {pending} cannot be read; it stays");
|
||||
continue;
|
||||
}
|
||||
var sequence = await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!File.Exists(pending)) continue;
|
||||
var target = Path.Combine(entryFolder, record.Name);
|
||||
if (File.Exists(target) || System.IO.Directory.Exists(target))
|
||||
{
|
||||
// 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 (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");
|
||||
}
|
||||
else
|
||||
{
|
||||
// The file never reached the trash: what was copied goes, and the render stays as it is.
|
||||
Undo(target, entryFolder, recordPath);
|
||||
Log.Info("videos", $"An interrupted delete of {record.OriginalPath} was undone");
|
||||
}
|
||||
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).
|
||||
/// </summary>
|
||||
internal static async Task<IReadOnlyList<VideoTrashFile>> HashFolderAsync(string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var files = new List<VideoTrashFile>();
|
||||
foreach (var file in System.IO.Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
|
||||
{
|
||||
var sha = await ContentHash.Sha256Async(file, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
files.Add(new VideoTrashFile(Path.GetRelativePath(folder, file).Replace('\\', '/'), new FileInfo(file).Length, sha));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// <summary>Whether the file or folder at <paramref name="path"/> holds what <paramref name="record"/> says, re-hashed now.</summary>
|
||||
private static async Task<bool> MatchesAsync(string path, VideoTrashRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
if (record.Files is { } expected)
|
||||
{
|
||||
if (!System.IO.Directory.Exists(path)) return false;
|
||||
var actual = await HashFolderAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
return actual.Count == expected.Count && actual.Zip(expected).All(p =>
|
||||
p.First.Path == p.Second.Path && p.First.Size == p.Second.Size && string.Equals(p.First.Sha256, p.Second.Sha256, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
if (!File.Exists(path)) return false;
|
||||
if (record.Sha256 is null) return true;
|
||||
var sha = await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
return string.Equals(sha, record.Sha256, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <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 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>
|
||||
/// <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))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (folder) System.IO.Directory.Move(from, to);
|
||||
else File.Move(from, to, overwrite: false);
|
||||
return true;
|
||||
}
|
||||
catch (IOException) when (folder && !System.IO.Directory.Exists(to) && System.IO.Directory.Exists(from))
|
||||
{
|
||||
// Another mount on the same root (Linux), or a file of the folder held open (Windows): copied instead.
|
||||
}
|
||||
}
|
||||
var part = to + PartSuffix;
|
||||
try
|
||||
{
|
||||
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)) 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies a file, flushed to the disk.</summary>
|
||||
internal static async Task CopyFileAsync(string source, string target, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var from = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
await using var to = new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20, FileOptions.Asynchronous);
|
||||
await from.CopyToAsync(to, cancellationToken).ConfigureAwait(false);
|
||||
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 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;
|
||||
if (Path.IsPathRooted(stored)) full = stored;
|
||||
else
|
||||
{
|
||||
var from = record.SequenceFolder;
|
||||
var rebased = from.Length > 0 && from != sequence.Folder && stored.StartsWith(from + "/", StringComparison.Ordinal)
|
||||
? (sequence.Folder.Length == 0 ? stored[(from.Length + 1)..] : sequence.Folder + stored[from.Length..])
|
||||
: stored;
|
||||
full = paths.FromRelative(rebased);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Archive-relative for outputs inside the archive (as renders are recorded), absolute otherwise.</summary>
|
||||
internal static string Stored(ArchivePaths paths, string output)
|
||||
{
|
||||
var relative = paths.ToRelative(output);
|
||||
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
|
||||
}
|
||||
|
||||
private static bool SameVolume(string a, string b) =>
|
||||
string.Equals(Path.GetPathRoot(Path.GetFullPath(a)), Path.GetPathRoot(Path.GetFullPath(b)), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Removes what a delete that did not complete left in the trash: the part copy, the entry's folder and its journal.</summary>
|
||||
private static void Undo(string target, string entryFolder, string recordPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeletePath(target + PartSuffix);
|
||||
RemoveEmpty(entryFolder);
|
||||
File.Delete(recordPath + PendingSuffix);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"What an unfinished delete left in {entryFolder} could not be removed; the next start settles it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Lists an entry whose delete completed: its record takes its own name. A failure (logged) is settled by the next <see cref="RecoverAsync"/>.</summary>
|
||||
private static void Publish(string recordPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(recordPath + PendingSuffix, recordPath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"Trash record {recordPath} keeps its pending name; the next start lists it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RemoveEmpty(string folder)
|
||||
{
|
||||
if (System.IO.Directory.Exists(folder) && !System.IO.Directory.EnumerateFileSystemEntries(folder).Any()) System.IO.Directory.Delete(folder);
|
||||
}
|
||||
|
||||
private static void DeletePath(string path)
|
||||
{
|
||||
if (System.IO.Directory.Exists(path)) SequenceTrash.Erase(path);
|
||||
else if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
|
||||
/// <summary>The folder name of an entry: its name without <see cref="VideoTrashNames.Prefix"/>, never a path.</summary>
|
||||
private static string DiskName(string name) =>
|
||||
Path.GetFileName(name.StartsWith(VideoTrashNames.Prefix, StringComparison.Ordinal) ? name[VideoTrashNames.Prefix.Length..] : name);
|
||||
|
||||
/// <summary>
|
||||
/// A videos entry as the trash lists it: titled by its sequence, with the path the render was deleted from (its file
|
||||
/// name last, which the panel's restore message and the desktop's row show).
|
||||
/// </summary>
|
||||
private static TrashEntry Entry(Guid archiveId, string name, VideoTrashRecord record)
|
||||
{
|
||||
var stored = record.Render.OutputPath.Replace('\\', '/').TrimEnd('/');
|
||||
var title = string.IsNullOrWhiteSpace(record.SequenceTitle) ? record.Name : record.SequenceTitle;
|
||||
return new TrashEntry(archiveId, name, record.SequenceId, title, stored, 0, record.FileCount, record.Bytes,
|
||||
record.DeletedAt, record.DeletedBy, TrashKind.Videos);
|
||||
}
|
||||
|
||||
private static VideoTrashRecord? ReadRecord(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), VideoTrashJson.Default.VideoTrashRecord) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"Trash record {path} is unreadable", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
IgnoreReadOnlyProperties = true)]
|
||||
[JsonSerializable(typeof(VideoTrashRecord))]
|
||||
internal sealed partial class VideoTrashJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// The videos folder (owner review 1, R9, decision 15): a flat folder outside every archive and the workspace that renders
|
||||
/// are copied into, each under its own name or, when that is taken, "name (2)", "name (3)"… (the export naming rule). A
|
||||
/// copy is written as <c>.incoming-<render id>.part</c> first and takes its name only once verified.
|
||||
/// </summary>
|
||||
public static class VideosFolder
|
||||
{
|
||||
/// <summary>The prefix of a copy being written; never a name a finished copy takes.</summary>
|
||||
public const string PartPrefix = ".incoming-";
|
||||
|
||||
/// <summary>The suffix of a copy being written.</summary>
|
||||
public const string PartSuffix = ".part";
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder: <see cref="VideoErrors.FolderUnset"/> when blank,
|
||||
/// <see cref="VideoErrors.FolderInvalid"/> when it is not an absolute path or lies inside (or is) one of
|
||||
/// <paramref name="protectedRoots"/> (the archive roots, the workspace); null when it can.
|
||||
/// </summary>
|
||||
public static string? Problem(string? folder, IEnumerable<string?> protectedRoots)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(protectedRoots);
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(folder)) return VideoErrors.FolderInvalid;
|
||||
full = Normalize(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
foreach (var root in protectedRoots)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||
if (IsInside(full, Normalize(root))) return VideoErrors.FolderInvalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="path"/> is <paramref name="root"/> or lies below it (both full and normalised).</summary>
|
||||
internal static bool IsInside(string path, string root)
|
||||
{
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
if (string.Equals(path, root, comparison)) return true;
|
||||
var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar;
|
||||
return path.StartsWith(prefix, comparison);
|
||||
}
|
||||
|
||||
/// <summary>The full path without a trailing separator (a drive or file-system root keeps its own).</summary>
|
||||
internal static string Normalize(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
var trimmed = full.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return trimmed.Length == 0 || trimmed.EndsWith(':') ? full : trimmed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path a copy named <paramref name="fileName"/> takes in <paramref name="folder"/>: the name itself when free, else
|
||||
/// "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>
|
||||
/// <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);
|
||||
var name = Path.GetFileName(fileName);
|
||||
var (stem, extension) = isFolder ? (name, string.Empty) : (Path.GetFileNameWithoutExtension(name), Path.GetExtension(name));
|
||||
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) && taken?.Invoke(candidate) != true) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the copy of render <paramref name="renderId"/> is written in <paramref name="folder"/> until it is verified.</summary>
|
||||
public static string PartPath(string folder, Guid renderId) => Path.Combine(folder, PartPrefix + renderId.ToString("N") + PartSuffix);
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes of the volume of <paramref name="folder"/>: what <paramref name="measure"/> says (a host's own measure,
|
||||
/// tests), else the drive's; null when unknown.
|
||||
/// </summary>
|
||||
public static long? FreeBytes(string folder, Func<string, long?>? measure = null)
|
||||
{
|
||||
if (measure?.Invoke(folder) is { } measured) return measured;
|
||||
try
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetFullPath(folder));
|
||||
return string.IsNullOrEmpty(root) ? null : new DriveInfo(root).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,13 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
var exports = project.ExportsDirectory;
|
||||
Directory.CreateDirectory(exports);
|
||||
using var names = new OutputNames();
|
||||
var all = RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
|
||||
// A still saves one frame through the job's preset alone: a batch is a video's.
|
||||
var all = render.IsStill
|
||||
? [new ExportTarget(ExportResolver.Resolve(projectSettings.Export), render.PresetName)]
|
||||
: RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
|
||||
var still = render.IsStill
|
||||
? SequenceRender.StillIndex(frames, render.StillFrame, render.StillPhoto) ?? throw new InvalidOperationException(Loc.L("Export.Render.StillMissing"))
|
||||
: -1;
|
||||
var resume = RenderCheckpoint.Parse(context.Checkpoint);
|
||||
var done = resume.Done.ToList();
|
||||
var ledger = project.ReadRenders();
|
||||
@@ -90,34 +96,67 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
try
|
||||
{
|
||||
await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null);
|
||||
outcomes = await renderer.RenderAllAsync(
|
||||
targets,
|
||||
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
|
||||
name => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name)))),
|
||||
(index, path) =>
|
||||
// A name the ledger holds is taken too (an output sent home and deleted here keeps its entry).
|
||||
bool Taken(Func<string, bool> taken, string name) => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name));
|
||||
ValueTask Starting(int index, string path)
|
||||
{
|
||||
writing = path;
|
||||
return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
|
||||
}
|
||||
async ValueTask Record(int index, ExportTarget target, RenderResult result)
|
||||
{
|
||||
// The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
|
||||
var id = RenderJobHandler.RenderId(context.Job.Id, index);
|
||||
var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
|
||||
if (render.IsStill) entry = entry with { Fps = 0, DurationSeconds = 0, Kind = RenderKind.Still };
|
||||
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
writing = path;
|
||||
return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
|
||||
},
|
||||
async (index, target, result) =>
|
||||
ledger = project.ReadRenders().With(entry);
|
||||
project.WriteRenders(ledger);
|
||||
}
|
||||
done.Add(index);
|
||||
if (!recorded.Contains(id)) recorded.Add(id);
|
||||
writing = null;
|
||||
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
|
||||
context.Log(render.IsStill
|
||||
? Loc.L("Export.Log.StillSaved", (still + 1).ToString(Loc.Culture), Path.GetFileName(result.OutputPath))
|
||||
: Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
|
||||
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
|
||||
}
|
||||
|
||||
if (render.IsStill)
|
||||
{
|
||||
var (index, target) = targets[0];
|
||||
try
|
||||
{
|
||||
// The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
|
||||
var id = RenderJobHandler.RenderId(context.Job.Id, index);
|
||||
var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
|
||||
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
ledger = project.ReadRenders().With(entry);
|
||||
project.WriteRenders(ledger);
|
||||
}
|
||||
done.Add(index);
|
||||
if (!recorded.Contains(id)) recorded.Add(id);
|
||||
writing = null;
|
||||
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
|
||||
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
|
||||
},
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
var result = await renderer.RenderStillAsync(
|
||||
target,
|
||||
still,
|
||||
setup => names.Reserve(taken => SequenceRender.StillPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup), still,
|
||||
name => Taken(taken, name))),
|
||||
path => Starting(index, path),
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
await Record(index, target, result).ConfigureAwait(false);
|
||||
outcomes = [new TargetOutcome(target, result, null)];
|
||||
}
|
||||
catch (Exception ex) when (!(ex is OperationCanceledException && cancellation.IsCancellationRequested))
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("workspace", $"The still of frame {still + 1} of {sequence.DisplayTitle} failed", ex);
|
||||
outcomes = [new TargetOutcome(target, null, SequenceRender.Reason(ex))];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
outcomes = await renderer.RenderAllAsync(
|
||||
targets,
|
||||
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
|
||||
name => Taken(taken, name))),
|
||||
Starting,
|
||||
Record,
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
}
|
||||
if (renderer.StandIns.Count > 0)
|
||||
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", renderer.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ namespace Chronos.Data.Workspaces;
|
||||
/// <param name="State"><see cref="Pending"/>, <see cref="SentState"/> or <see cref="Failed"/> (a later Chronos may write others: read as pending).</param>
|
||||
/// <param name="Sent">When the home took it; null until then.</param>
|
||||
/// <param name="Error">Why the last send failed (one localized sentence); null otherwise.</param>
|
||||
/// <param name="Kind">The render's kind (<see cref="RenderKind"/>): <c>still</c> for a saved frame, null for a video or an image sequence.</param>
|
||||
public sealed record WorkspaceRenderEntry(
|
||||
Guid RenderId,
|
||||
Guid JobId,
|
||||
@@ -43,7 +44,8 @@ public sealed record WorkspaceRenderEntry(
|
||||
DateTimeOffset Rendered,
|
||||
string State = WorkspaceRenderEntry.Pending,
|
||||
DateTimeOffset? Sent = null,
|
||||
string? Error = null)
|
||||
string? Error = null,
|
||||
string? Kind = null)
|
||||
{
|
||||
/// <summary>Written, not at the home yet.</summary>
|
||||
public const string Pending = "pending";
|
||||
|
||||
@@ -286,6 +286,9 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
ProducedBy = options.Processing.ProducedBy,
|
||||
ProjectId = entry.ProjectId,
|
||||
ProjectVersionId = entry.ProjectVersionId,
|
||||
// A file's hash is the file's own (an image sequence's ledger hash is of its listing, not a render's).
|
||||
Sha256 = folder ? null : entry.Sha256.ToLowerInvariant(),
|
||||
Kind = entry.Kind,
|
||||
}, ct).ConfigureAwait(false);
|
||||
return filed is not null ? true : throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
}
|
||||
@@ -329,7 +332,7 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
{
|
||||
var name = SyncTransfers.SafeFileName(Path.GetFileName(entry.File)) ?? entry.RenderId.ToString("N");
|
||||
var request = new RenderUploadRequest(entry.RenderId, name, entry.Size, entry.Sha256.ToLowerInvariant(), entry.PresetName, entry.Codec, entry.Width, entry.Height,
|
||||
entry.Fps, entry.DurationSeconds, options.Processing.ProducedBy, entry.ProjectId, entry.ProjectVersionId);
|
||||
entry.Fps, entry.DurationSeconds, options.Processing.ProducedBy, entry.ProjectId, entry.ProjectVersionId, entry.Kind);
|
||||
try
|
||||
{
|
||||
if (await remote.UploadRenderAsync(sequenceId, file, request, ct).ConfigureAwait(false) is not { } filed) return false;
|
||||
|
||||
@@ -17,6 +17,9 @@ namespace Chronos.Protocol;
|
||||
/// server runs in a container, whose listening ports the template fixes: they are then locked, named in
|
||||
/// <see cref="Locked"/> with the variable <c>DOTNET_RUNNING_IN_CONTAINER</c> unless one of their own fixes them. The
|
||||
/// members added since are last and optional, so clients and panels of the shape before them keep working.
|
||||
/// <see cref="VideosPath"/> (owner review 1, R9) is the folder "Copy to videos folder" copies renders into (the Docker
|
||||
/// <c>/videos</c> volume), locked by <c>CHRONOS_VIDEOS_PATH</c> (<see cref="LockedBy"/> key <c>VideosPath</c>); null in a
|
||||
/// response when none is set, which disables copying; in a request, null keeps it as it is and an empty text clears it.
|
||||
/// </summary>
|
||||
public sealed record ServerSettingsDto(
|
||||
string ServerName,
|
||||
@@ -42,7 +45,8 @@ public sealed record ServerSettingsDto(
|
||||
bool ProxyWarning,
|
||||
int? PublicHttpPort = null,
|
||||
int? PublicHttpsPort = null,
|
||||
bool InContainer = false);
|
||||
bool InContainer = false,
|
||||
string? VideosPath = null);
|
||||
|
||||
/// <summary>
|
||||
/// The log settings of <see cref="ServerSettingsDto"/> (owner review 2, R11): the least severe level of the files and of the
|
||||
|
||||
@@ -423,6 +423,42 @@ public sealed class ChronosClient : IDisposable
|
||||
return Convert.ToHexStringLower(hash);
|
||||
}
|
||||
|
||||
// ---------------- Videos (owner review 1, R9; servers with the "videos" capability) ----------------
|
||||
|
||||
/// <summary>One page of the server's videos matching <paramref name="query"/> (every video, newest first, when null).</summary>
|
||||
public Task<VideoPageDto> ListVideosAsync(VideoQueryDto? query = null, CancellationToken ct = default)
|
||||
{
|
||||
var q = query ?? new VideoQueryDto();
|
||||
var invariant = System.Globalization.CultureInfo.InvariantCulture;
|
||||
var parts = string.Concat(Q("q", q.Q), Q("kind", q.Kind), Q("codec", q.Codec), Q("year", q.Year?.ToString(invariant)), Q("sequence", q.Sequence?.ToString()),
|
||||
Q("sort", q.Sort), Q("cursor", q.Cursor), Q("limit", q.Limit?.ToString(invariant)));
|
||||
return GetAsync(parts.Length == 0 ? "api/v1/videos" : "api/v1/videos?" + parts[1..], ProtocolJson.Default.VideoPageDto, ct);
|
||||
}
|
||||
|
||||
/// <summary>One video of the server; a render it does not have is a 404 <see cref="ChronosApiException"/>.</summary>
|
||||
public Task<VideoDto> GetVideoAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/videos/{id}", ProtocolJson.Default.VideoDto, ct);
|
||||
|
||||
/// <summary>The dry run of deleting <paramref name="ids"/> into the trash: what goes, what stays and the plan's fingerprint; nothing moves.</summary>
|
||||
public Task<VideoDeletePlanDto> PlanDeleteVideosAsync(IReadOnlyList<Guid> ids, CancellationToken ct = default) =>
|
||||
SendAsync(HttpMethod.Post, "api/v1/videos/delete", new VideoDeleteRequest(ids, true), ProtocolJson.Default.VideoDeleteRequest,
|
||||
ProtocolJson.Default.VideoDeletePlanDto, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes <paramref name="ids"/> into the trash as planned (<paramref name="fingerprint"/> from
|
||||
/// <see cref="PlanDeleteVideosAsync"/>); a plan that changed since is a 409 <c>plan_changed</c>
|
||||
/// <see cref="ChronosApiException"/> and nothing moves.
|
||||
/// </summary>
|
||||
public Task<VideoDeletePlanDto> DeleteVideosAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken ct = default) =>
|
||||
SendAsync(HttpMethod.Post, "api/v1/videos/delete", new VideoDeleteRequest(ids, false, fingerprint), ProtocolJson.Default.VideoDeleteRequest,
|
||||
ProtocolJson.Default.VideoDeletePlanDto, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Queues the copy of <paramref name="ids"/> into the server's videos folder (a <c>video-copy</c> job); a server without a
|
||||
/// videos folder answers 409 <c>videos_folder_unset</c> (<see cref="ChronosApiException"/>).
|
||||
/// </summary>
|
||||
public Task<VideoCopyResultDto> CopyVideosAsync(IReadOnlyList<Guid> ids, CancellationToken ct = default) =>
|
||||
SendAsync(HttpMethod.Post, "api/v1/videos/copy", new VideoCopyRequest(ids), ProtocolJson.Default.VideoCopyRequest, ProtocolJson.Default.VideoCopyResultDto, ct);
|
||||
|
||||
// ---------------- Jobs and render nodes ----------------
|
||||
|
||||
public Task<Page<JobDto>> ListJobsAsync(string? state = null, string? cursor = null, CancellationToken ct = default) =>
|
||||
|
||||
@@ -36,6 +36,12 @@ public static class ServerCapabilities
|
||||
/// <c>projectChanged</c> event, renders of a project version. A server without it knows only the sequence's settings.
|
||||
/// </summary>
|
||||
public const string Projects = "projects";
|
||||
|
||||
/// <summary>
|
||||
/// The server keeps a videos library (owner review 1, R9): <c>/api/v1/videos</c> lists, deletes into the trash and copies
|
||||
/// its renders into its videos folder. Without it a client lists only its own videos.
|
||||
/// </summary>
|
||||
public const string Videos = "videos";
|
||||
}
|
||||
|
||||
/// <summary><c>GET /health</c>.</summary>
|
||||
|
||||
@@ -68,14 +68,31 @@ public sealed record JobPriorityRequest(string Priority);
|
||||
/// format, at least 2 when the chosen proportions change a fixed preset's size); 1 in a job of an older server. A hint for
|
||||
/// routing: a node recomputes it from the settings it claims.
|
||||
/// </param>
|
||||
/// <param name="StillFrame">
|
||||
/// A still job (owner review 1, R8, "Save frame"): the 0-based index of the sequence's frame saved as one image with
|
||||
/// <paramref name="Codec"/> (<c>pngsequence</c>, <c>jpegsequence</c> or <c>tiff16sequence</c>) at the export's output size,
|
||||
/// with every correction and no playback; null for a video. Such a job needs settings format 3
|
||||
/// (<paramref name="RequiredSettingsFormat"/>), so an older node, which would render the whole video, never claims it.
|
||||
/// </param>
|
||||
/// <param name="StillPhoto">
|
||||
/// The SHA-256 of the still's photo: the identity that wins over <paramref name="StillFrame"/> when both are given and the
|
||||
/// frames moved since (photos inserted before it); null when the photo is not hashed yet.
|
||||
/// </param>
|
||||
public sealed record RenderJobParameters(string PresetName, string PresetJson, string Codec, int Width, int Height, bool UseProxies, string? SettingsJson,
|
||||
Guid? ProjectId = null, Guid? ProjectVersionId = null, int RequiredSettingsFormat = 1);
|
||||
Guid? ProjectId = null, Guid? ProjectVersionId = null, int RequiredSettingsFormat = 1, int? StillFrame = null, string? StillPhoto = null)
|
||||
{
|
||||
/// <summary>The job saves one frame as an image (<see cref="StillFrame"/> or <see cref="StillPhoto"/> set).</summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public bool IsStill => StillFrame is not null || StillPhoto is not null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/nodes/{id}/jobs/{jobId}/result</c>: the finished output a node is about to upload in chunks. A
|
||||
/// <c>result/complete</c> that cannot file it for now answers 503 <c>sequence_busy</c>, <c>archive_offline</c> or
|
||||
/// <c>folder_moved</c> (another index moved the sequence's folder; the server's next scan finds it); the upload and the
|
||||
/// job stay the node's, to be completed again.
|
||||
/// <see cref="Kind"/> (owner review 1, R9): <c>still</c> for a still job's image, null for a video or an image sequence;
|
||||
/// appended, so an earlier node sends none and an earlier server ignores it.
|
||||
/// </summary>
|
||||
public sealed record RenderResultRequest(
|
||||
string FileName,
|
||||
@@ -86,7 +103,8 @@ public sealed record RenderResultRequest(
|
||||
int Width,
|
||||
int Height,
|
||||
double Fps,
|
||||
double DurationSeconds);
|
||||
double DurationSeconds,
|
||||
string? Kind = null);
|
||||
|
||||
/// <summary><c>POST /api/v1/nodes/{id}/jobs/{jobId}/failed</c>: the node could not render the job.</summary>
|
||||
public sealed record NodeJobFailure(string Error);
|
||||
@@ -100,4 +100,10 @@ namespace Chronos.Protocol;
|
||||
[JsonSerializable(typeof(ProjectPushResultDto))]
|
||||
[JsonSerializable(typeof(ProjectFramesDto))]
|
||||
[JsonSerializable(typeof(ProjectFramesStampDto))]
|
||||
[JsonSerializable(typeof(VideoDto))]
|
||||
[JsonSerializable(typeof(VideoPageDto))]
|
||||
[JsonSerializable(typeof(VideoDeleteRequest))]
|
||||
[JsonSerializable(typeof(VideoDeletePlanDto))]
|
||||
[JsonSerializable(typeof(VideoCopyRequest))]
|
||||
[JsonSerializable(typeof(VideoCopyResultDto))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -116,6 +116,11 @@ public sealed record ProxySpec(int LongEdge, int Quality);
|
||||
/// before phase 5c.
|
||||
/// </param>
|
||||
/// <param name="ProjectVersionId">The project version rendered; null when none is named (see <paramref name="ProjectId"/>).</param>
|
||||
/// <param name="Sha256">
|
||||
/// Lower-case hex SHA-256 of a single-file render (owner review 1, R9); null for an image sequence, for a render not hashed
|
||||
/// yet (recorded before the server's migration 0010) and from earlier servers.
|
||||
/// </param>
|
||||
/// <param name="Kind">The render's kind as recorded: <c>still</c>, or null for a video or an image sequence (told apart by <paramref name="Codec"/>).</param>
|
||||
public sealed record RenderDto(
|
||||
Guid Id,
|
||||
string PresetName,
|
||||
@@ -128,7 +133,9 @@ public sealed record RenderDto(
|
||||
DateTimeOffset Created,
|
||||
string? ProducedBy,
|
||||
Guid? ProjectId = null,
|
||||
Guid? ProjectVersionId = null);
|
||||
Guid? ProjectVersionId = null,
|
||||
string? Sha256 = null,
|
||||
string? Kind = null);
|
||||
|
||||
/// <summary>Aggregates for the archive dashboard and the admin panel.</summary>
|
||||
/// <param name="FreeBytes">Free bytes of the space volume: the server's space path when one is set, else the archive's volume.</param>
|
||||
|
||||
@@ -49,7 +49,8 @@ public sealed record CardImportReport(Guid ImportId, string Card, string State,
|
||||
/// A render a workspace made on a client (phase 5c) names the project and version it was rendered from
|
||||
/// (<see cref="ProjectId"/>, <see cref="ProjectVersionId"/>): the server records them with the render once it checked that
|
||||
/// the project is the sequence's and the version the project's (422 <c>project_mismatch</c> otherwise). Both are optional
|
||||
/// and appended: a request of an earlier client has neither, and an earlier server ignores them.
|
||||
/// and appended: a request of an earlier client has neither, and an earlier server ignores them. <see cref="Kind"/> (owner
|
||||
/// review 1, R9) is the render's kind (<c>still</c>, or null for a video or an image sequence), appended the same way.
|
||||
/// </summary>
|
||||
public sealed record RenderUploadRequest(
|
||||
Guid RenderId,
|
||||
@@ -64,4 +65,5 @@ public sealed record RenderUploadRequest(
|
||||
double DurationSeconds,
|
||||
string? ProducedBy,
|
||||
Guid? ProjectId = null,
|
||||
Guid? ProjectVersionId = null);
|
||||
Guid? ProjectVersionId = null,
|
||||
string? Kind = null);
|
||||
@@ -0,0 +1,132 @@
|
||||
namespace Chronos.Protocol;
|
||||
|
||||
// The videos library (owner review 1, R9): every render of the server in one list, on servers with the "videos" capability
|
||||
// (ServerCapabilities.Videos). Read lists and plays, Delete moves renders into the archive's trash (restored through
|
||||
// /archive/trash), Edit copies them into the server's videos folder; the panel and the desktop's Videos section use these.
|
||||
|
||||
/// <summary>A verified copy of a video in a videos folder (<see cref="VideoDto.Copies"/>).</summary>
|
||||
/// <param name="Path">Absolute path of the copy on the host that made it.</param>
|
||||
public sealed record VideoCopyDto(string Path, DateTimeOffset CopiedAt);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/videos</c>, <c>GET /api/v1/videos/{id}</c>: a render with the members of <see cref="RenderDto"/>, its
|
||||
/// sequence and project, whether its file is there, and its copies. The file itself is <c>GET /api/v1/renders/{id}/file</c>
|
||||
/// (Range requests served, so a browser's <c><video></c> seeks).
|
||||
/// </summary>
|
||||
/// <param name="Kind">The library kind, never null: <c>video</c>, <c>still</c> or <c>sequence</c> (an image-sequence folder),
|
||||
/// or a newer server's kind as it is (<see cref="RenderDto.Kind"/> holds the kind as recorded).</param>
|
||||
/// <param name="SequenceTitle">The display title of the render's sequence.</param>
|
||||
/// <param name="SequenceFirstCapture">When its first photo was taken; null when unknown.</param>
|
||||
/// <param name="ProjectName">The project rendered (owner review 2, R8); null for a render of the sequence's settings.</param>
|
||||
/// <param name="ProjectVersionNumber">The number of the project version rendered; null with <paramref name="ProjectName"/>.</param>
|
||||
/// <param name="State"><c>ok</c>, or <c>missing</c> when its file is not where it was recorded (delete then removes only the entry).</param>
|
||||
/// <param name="FileName">The file (or folder) name, for display and downloads.</param>
|
||||
public sealed record VideoDto(
|
||||
Guid Id,
|
||||
Guid SequenceId,
|
||||
string PresetName,
|
||||
string? Codec,
|
||||
int Width,
|
||||
int Height,
|
||||
double Fps,
|
||||
double DurationSeconds,
|
||||
long Bytes,
|
||||
DateTimeOffset Created,
|
||||
string? ProducedBy,
|
||||
Guid? ProjectId,
|
||||
Guid? ProjectVersionId,
|
||||
string? Sha256,
|
||||
string Kind,
|
||||
string SequenceTitle,
|
||||
DateTime? SequenceFirstCapture,
|
||||
string? ProjectName,
|
||||
int? ProjectVersionNumber,
|
||||
string State,
|
||||
IReadOnlyList<VideoCopyDto> Copies,
|
||||
string? FileName = null);
|
||||
|
||||
/// <summary>The values of <see cref="VideoDto.State"/>.</summary>
|
||||
public static class VideoStates
|
||||
{
|
||||
public const string Ok = "ok";
|
||||
|
||||
/// <summary>The render's file is not where it was recorded.</summary>
|
||||
public const string Missing = "missing";
|
||||
}
|
||||
|
||||
/// <summary>The <c>sort</c> values of <c>GET /api/v1/videos</c> (and of the desktop's Videos section).</summary>
|
||||
public static class VideoSorts
|
||||
{
|
||||
/// <summary>Newest first (the default).</summary>
|
||||
public const string Newest = "newest";
|
||||
|
||||
public const string Oldest = "oldest";
|
||||
|
||||
/// <summary>Largest first.</summary>
|
||||
public const string Largest = "largest";
|
||||
|
||||
/// <summary>By sequence title, then newest first.</summary>
|
||||
public const string Title = "title";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } = [Newest, Oldest, Largest, Title];
|
||||
}
|
||||
|
||||
/// <summary>One page of <c>GET /api/v1/videos</c>; <see cref="Next"/> is the cursor of the next page, null on the last one.</summary>
|
||||
/// <param name="Total">Videos matching the filters on every page; null when the server does not count them.</param>
|
||||
public sealed record VideoPageDto(IReadOnlyList<VideoDto> Items, string? Next, long? Total = null);
|
||||
|
||||
/// <summary>
|
||||
/// The query of <c>GET /api/v1/videos</c> (<see cref="Client.ChronosClient.ListVideosAsync"/>); every member optional.
|
||||
/// </summary>
|
||||
/// <param name="Q">Text in the sequence title, the preset name or the file name.</param>
|
||||
/// <param name="Kind"><c>video</c>, <c>still</c> or <c>sequence</c>.</param>
|
||||
/// <param name="Codec">A codec name as recorded (<c>h264</c>, <c>hevc</c>, <c>pngsequence</c>…).</param>
|
||||
/// <param name="Year">The year the render was made (UTC).</param>
|
||||
/// <param name="Sequence">The videos of one sequence.</param>
|
||||
/// <param name="Sort">One of <see cref="VideoSorts"/>; null for newest first.</param>
|
||||
/// <param name="Cursor">The <see cref="VideoPageDto.Next"/> of the previous page.</param>
|
||||
/// <param name="Limit">Videos per page, 1–500 (the server's default when null).</param>
|
||||
public sealed record VideoQueryDto(string? Q = null, string? Kind = null, string? Codec = null, int? Year = null, Guid? Sequence = null,
|
||||
string? Sort = null, string? Cursor = null, int? Limit = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/videos/delete</c>: move these renders into the archive's trash. With <see cref="DryRun"/> the server
|
||||
/// answers the plan (<see cref="VideoDeletePlanDto"/>) and moves nothing; the delete itself must send the plan's
|
||||
/// <see cref="Fingerprint"/> back, or the server answers 409 <c>plan_changed</c> and moves nothing.
|
||||
/// </summary>
|
||||
public sealed record VideoDeleteRequest(IReadOnlyList<Guid> Ids, bool DryRun, string? Fingerprint = null);
|
||||
|
||||
/// <summary>A render of a delete plan: what goes, and whether only its entry goes (its file is missing).</summary>
|
||||
public sealed record VideoDeleteItemDto(Guid Id, Guid SequenceId, string SequenceTitle, string? FileName, long Bytes, bool Missing);
|
||||
|
||||
/// <summary>
|
||||
/// A render a delete leaves where it is: <see cref="Reason"/> <c>busy</c> (a send, an upload or a copy of it is running) or
|
||||
/// <c>not_found</c> (no such render).
|
||||
/// </summary>
|
||||
public sealed record VideoBlockedDto(Guid Id, string Reason);
|
||||
|
||||
/// <summary>The values of <see cref="VideoBlockedDto.Reason"/>.</summary>
|
||||
public static class VideoBlockReasons
|
||||
{
|
||||
public const string Busy = "busy";
|
||||
|
||||
public const string NotFound = "not_found";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The answer of <c>POST /api/v1/videos/delete</c>: the renders that go (or went) to the trash, their bytes, the renders left
|
||||
/// where they are, and the plan's fingerprint. Copies in the videos folder are never touched. After the delete itself
|
||||
/// (<see cref="DryRun"/> false) <see cref="TrashEntries"/> names the trash entries made, each restorable with
|
||||
/// <c>POST /api/v1/archive/trash/{name}/restore</c>.
|
||||
/// </summary>
|
||||
public sealed record VideoDeletePlanDto(IReadOnlyList<VideoDeleteItemDto> Items, long Bytes, IReadOnlyList<VideoBlockedDto> Blocked, string Fingerprint,
|
||||
bool DryRun, IReadOnlyList<string>? TrashEntries = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/videos/copy</c>: copy these renders into the server's videos folder as one <c>video-copy</c> job; 409
|
||||
/// <c>videos_folder_unset</c> when the server has none.
|
||||
/// </summary>
|
||||
public sealed record VideoCopyRequest(IReadOnlyList<Guid> Ids);
|
||||
|
||||
/// <summary>The answer of <c>POST /api/v1/videos/copy</c> (202): the <c>video-copy</c> job queued.</summary>
|
||||
public sealed record VideoCopyResultDto(Guid JobId);
|
||||
@@ -386,7 +386,7 @@ textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize
|
||||
.frame-badge { position: absolute; top: 4px; inset-inline-end: 4px; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 11px; background: var(--on-photo); color: #fff; }
|
||||
.frame-badge.hero { color: var(--sun); }
|
||||
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content max-content max-content; }
|
||||
/* A sequence's projects (owner review 2, R8) and, under one opened, its versions. Their table sits in a wrapper, a grid item
|
||||
of the panel: it may be narrower than the table, so the table's columns fit (fitColumns) instead of the panel scrolling. */
|
||||
.panel > .table-host { min-width: 0; }
|
||||
@@ -417,6 +417,24 @@ dialog.viewer .buttons { grid-column: 1 / -1; }
|
||||
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
|
||||
}
|
||||
|
||||
/* Videos (owner review 1, R9; pages/videos.js): the Library's cards and rows with their own columns (title and preset,
|
||||
kind, format, duration, size, date, hash, state), a missing file dimmed, and the player: the photo viewer's layout with
|
||||
a <video> or an image on its stage, or a sentence when the browser cannot play the file. */
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(160px, 2fr) max-content max-content max-content max-content max-content minmax(0, max-content) minmax(60px, max-content); }
|
||||
.video-items .missing .thumb { opacity: .45; }
|
||||
.video-items .seq-card .info .num { font-size: 12px; color: var(--text-muted); }
|
||||
.viewer-stage video { display: block; max-width: 100%; max-height: 72vh; }
|
||||
.viewer-stage .player-note { margin: 0; padding: 24px; color: #fff; text-align: center; }
|
||||
dialog.player .viewer-head .ellipsis { flex: 0 1 auto; }
|
||||
@media (max-width: 1200px) {
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(140px, 2fr) max-content max-content max-content max-content minmax(60px, max-content); }
|
||||
.video-items .col-hash, .video-items .col-date { display: none; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.seq-items.rows.video-items { grid-template-columns: max-content 64px minmax(120px, 1fr) max-content minmax(60px, max-content); }
|
||||
.video-items .col-kind, .video-items .col-format, .video-items .col-duration { display: none; }
|
||||
}
|
||||
|
||||
/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
|
||||
dialog.dialog.upload { width: 640px; }
|
||||
.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
|
||||
|
||||
@@ -6,8 +6,9 @@ import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } fro
|
||||
|
||||
const app = document.getElementById("app");
|
||||
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). The Library
|
||||
// manages sequences and photos without editing them (owner review 2, R6).
|
||||
const topPages = ["dashboard", "library", "users", "archive", "jobs", "logs"];
|
||||
// manages sequences and photos without editing them (owner review 2, R6); Videos lists every render after it (owner
|
||||
// review 1, R9).
|
||||
const topPages = ["dashboard", "library", "videos", "users", "archive", "jobs", "logs"];
|
||||
const bottomPages = ["settings"];
|
||||
const pages = [...topPages, ...bottomPages];
|
||||
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
|
||||
|
||||
@@ -29,4 +29,10 @@ export const icons = {
|
||||
hero: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
image: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
warning: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
videos: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.5 6.5 L9.5 9 L5.5 11.5 Z" fill="currentColor"/><path d="M3.0 4 H11.0 A1.5 1.5 0 0 1 12.5 5.5 V12.5 A1.5 1.5 0 0 1 11.0 14 H3.0 A1.5 1.5 0 0 1 1.5 12.5 V5.5 A1.5 1.5 0 0 1 3.0 4 Z M4.5 1.5 H13 A1.5 1.5 0 0 1 14.5 3 V11.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
play: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4.5 2.8 L13 8 L4.5 13.2 Z" fill="currentColor"/></svg>`,
|
||||
copyToFolder: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H13.5 A1 1 0 0 1 14.5 5.5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z M8 6.5 V11 M6 9 L8 11 L10 9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
stillFrame: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5.5 H9.5 A0.5 0.5 0 0 1 10 6.0 V10.0 A0.5 0.5 0 0 1 9.5 10.5 H6.5 A0.5 0.5 0 0 1 6 10.0 V6.0 A0.5 0.5 0 0 1 6.5 5.5 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M4.5 2.5 V13.5 M11.5 2.5 V13.5 M1.5 6 H4.5 M1.5 10 H4.5 M11.5 6 H14.5 M11.5 10 H14.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
fade: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 12 L13 4 V12 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
boomerang: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 5 H11 A3 3 0 0 1 11 11 H3 M5 8.8 L2.8 11 L5 13.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
};
|
||||
@@ -1,12 +1,14 @@
|
||||
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
|
||||
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, its projects (R8: listed,
|
||||
// renamed and deleted, projects.js), the originals and the renders to download. Nothing here edits the video: its settings,
|
||||
// its projects' versions and its renders are the desktop editor's.
|
||||
// renamed and deleted, projects.js), the originals and the renders to download, with their kind and hash and a link to
|
||||
// this sequence's videos on the Videos page (owner review 1, R9). Nothing here edits the video: its settings, its projects'
|
||||
// versions and its renders are the desktop editor's.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js";
|
||||
import { projectsSection } from "./projects.js";
|
||||
import { videoKind, kindText, shortHash } from "../videos.js";
|
||||
|
||||
const FRAME_PAGE = 500;
|
||||
/** Deleting more photos than this asks for their number to be typed. */
|
||||
@@ -87,7 +89,8 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
<div id="projects" class="table-host"></div>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="renders-title">
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2>
|
||||
<a class="btn small" href="#/videos?sequence=${attr(encodeURIComponent(id))}" data-i18n="Admin.Videos.AllVideos" data-i18n-title="Admin.Videos.AllVideos.Tip"></a></div>
|
||||
<div id="renders"></div>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
@@ -435,15 +438,19 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
|
||||
host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
|
||||
<div class="table renders" role="table" aria-labelledby="renders-title">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" data-i18n="Admin.Videos.Column.Kind"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Videos.Column.Hash"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div role="rowgroup">${renders.map((r) => `
|
||||
<div class="row" role="row" data-key="${attr(r.id)}">
|
||||
<span class="ellipsis" role="cell" dir="auto" title="${attr(r.producedBy ?? "")}">${escapeHtml(r.presetName)}</span>
|
||||
<span class="num nowrap" role="cell" dir="ltr">${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(clock(r.durationSeconds))}</span>
|
||||
<span class="nowrap" role="cell">${escapeHtml(kindText(videoKind(r)))}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(videoKind(r) === "still" ? "—" : clock(r.durationSeconds))}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(r.bytes))}</span>
|
||||
<span class="mono muted nowrap" role="cell" dir="ltr" title="${attr(r.sha256 ?? "")}">${escapeHtml(shortHash(r.sha256))}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(r.created))}</span>
|
||||
<span class="row-actions" role="cell"><a class="btn small" href="/api/v1/renders/${encodeURIComponent(r.id)}/file" download
|
||||
data-i18n-title="Admin.Sequence.Render.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Render.Download"></span></a></span>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// The archive's trash on the panel (owner review 2, R6; #/library?view=trash, reached from the Library and the Archive):
|
||||
// deleted sequences and photos deleted from sequences, each restorable; emptying it is the panel's only erase of user
|
||||
// files, so it measures the trash first (dry run), names what goes, asks for the word "empty" to be typed and sends the
|
||||
// plan's fingerprint, which the server's job checks again before it erases anything.
|
||||
// deleted sequences, photos deleted from sequences and videos deleted from the Videos page (owner review 1, R9), each
|
||||
// restorable; emptying it is the panel's only erase of user files, so it measures the trash first (dry run), names what
|
||||
// goes, asks for the word "empty" to be typed and sends the plan's fingerprint, which the server's job checks again before
|
||||
// it erases anything.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
@@ -73,7 +74,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
<span class="nowrap" role="cell">${escapeHtml(kindLabel(e.kind))}</span>
|
||||
<span class="stack" role="cell"><strong class="ellipsis" dir="auto" title="${attr(e.title)}">${escapeHtml(e.title)}</strong>
|
||||
<small dir="ltr" class="mono" title="${attr(e.folder)}">${escapeHtml(e.folder)}</small></span>
|
||||
<span class="num end" role="cell">${formatNumber(e.photos)}</span>
|
||||
<span class="num end" role="cell">${e.kind === "videos" ? "—" : formatNumber(e.photos)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(e.bytes))}</span>
|
||||
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
|
||||
@@ -105,7 +106,9 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
return;
|
||||
}
|
||||
// A replaced entry (owner review 2, R7) swaps back: its originals take their conversions' place, which go to the trash.
|
||||
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
// A video goes back into its sequence's folder after its hash matched its record (the server refuses it otherwise).
|
||||
const lines = [result.kind === "videos" ? t("Admin.Trash.RestoredVideo", videoFile(entry), entry.title)
|
||||
: result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos)
|
||||
: result.kind === "replaced" ? plural("Admin.Trash.RestoredOriginals", result.photos, entry.title)
|
||||
: plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
|
||||
@@ -218,11 +221,21 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
|
||||
await load();
|
||||
}
|
||||
|
||||
/** What Restore does to an entry of this kind: a sequence's folder back, photos back, or originals back in place of their conversions. */
|
||||
/**
|
||||
* What Restore does to an entry of this kind: a sequence's folder back, photos back, originals back in place of their
|
||||
* conversions, or a video back into its sequence.
|
||||
*/
|
||||
function restoreTip(kind) {
|
||||
return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip" : "Admin.Trash.RestorePhotos.Tip";
|
||||
return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip"
|
||||
: kind === "videos" ? "Admin.Trash.RestoreVideos.Tip" : "Admin.Trash.RestorePhotos.Tip";
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced"
|
||||
: kind === "videos" ? "Admin.Trash.Kind.Videos" : "Admin.Trash.Kind.Photos");
|
||||
}
|
||||
|
||||
/** A video entry's file name: the last part of the path it was deleted from (its folder). */
|
||||
function videoFile(entry) {
|
||||
return String(entry.folder ?? "").split(/[\\/]/).filter(Boolean).pop() ?? entry.title;
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
// in a container the listening ports are the container's, read-only. Client address is what to type in the Uploader and
|
||||
// in Chronos: this host as the browser reached it, on the HTTPS port this page came through (else the public HTTPS port;
|
||||
// the proxy's address in TLS mode proxy). When that port is not the saved one, a button fills it in; saving a public HTTPS
|
||||
// port other than the page's asks first, as the HTTPS redirect follows it at once.
|
||||
// port other than the page's asks first, as the HTTPS redirect follows it at once. Videos folder (owner review 1, R9) is
|
||||
// where the Videos page's Copy to folder puts renders: read-only when CHRONOS_VIDEOS_PATH fixes it, empty turns copying off.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, confirmDialog, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel } from "../jobs.js";
|
||||
@@ -82,6 +83,7 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
|
||||
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
${text("videosPath", settings.videosPath, 'dir="ltr" spellcheck="false" autocomplete="off"')}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="jobs-title">
|
||||
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
|
||||
@@ -214,6 +216,17 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The videos folder to send (owner review 1, R9): null keeps it (locked by CHRONOS_VIDEOS_PATH, or not changed), an empty
|
||||
* text clears it and turns copying off, else the folder, which the server checks (not inside the archive).
|
||||
*/
|
||||
function videosPath() {
|
||||
const input = root.querySelector('[name="videosPath"]');
|
||||
if (!input || input.disabled) return null;
|
||||
const next = input.value.trim();
|
||||
return next === (settings.videosPath ?? "") ? null : next;
|
||||
}
|
||||
|
||||
async function save(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
@@ -259,6 +272,7 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
tlsMode: String(value("tlsMode", settings.tlsMode)),
|
||||
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
|
||||
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
|
||||
videosPath: videosPath(),
|
||||
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
|
||||
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
|
||||
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
// Videos (owner review 1, R9; decision 22): every render of the server in one list (GET /api/v1/videos), as cards or
|
||||
// rows, with the filters in the address (#/videos?sequence=<id> is a sequence's "All videos"). The panel manages and never
|
||||
// edits (owner review 2, R6): it plays a render in the browser, downloads it, copies it hash-verified into the server's
|
||||
// videos folder (a video-copy job) and deletes it into the archive's trash after a dry run that names what goes, whose
|
||||
// fingerprint the delete sends back. Restoring goes through Library › Trash. Nothing here renders or changes a project.
|
||||
import { t, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, routeParams, redraw } from "../ui.js";
|
||||
import { icons } from "../icons.js";
|
||||
import { lazyImage, watchImages, Selection, selectableGrid, listed, JOB_ENDED } from "./library/shared.js";
|
||||
|
||||
const VIEW_KEY = "chronos.admin.videos.view";
|
||||
const PAGE = 100;
|
||||
/** The most a refresh reads back in one request (VideoQuery.MaxLimit). */
|
||||
const MAX_PAGE = 500;
|
||||
const KINDS = ["video", "still", "sequence"];
|
||||
const SORTS = ["newest", "oldest", "largest", "title"];
|
||||
const FILTERS = ["q", "kind", "codec", "year", "sequence", "sort"];
|
||||
/** Permissions bits (Chronos.Core.Model.Permissions): copying needs Edit, deleting Delete. */
|
||||
const EDIT = 4;
|
||||
const DELETE = 8;
|
||||
/** File types a browser plays in a <video> element, and those it shows as an image (stills, GIF, APNG). */
|
||||
const VIDEO_TYPES = new Set(["mp4", "m4v", "mov", "webm"]);
|
||||
const IMAGE_TYPES = new Set(["png", "apng", "jpg", "jpeg", "gif", "webp"]);
|
||||
const CODECS = { h264: "H.264", hevc: "HEVC", av1: "AV1", mjpeg: "MJPEG", gif: "GIF", apng: "APNG" };
|
||||
|
||||
export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
const params = routeParams();
|
||||
const filters = Object.fromEntries(FILTERS.map((f) => [f, params.get(f) ?? ""]));
|
||||
if (!SORTS.includes(filters.sort)) filters.sort = "newest";
|
||||
if (!KINDS.includes(filters.kind)) filters.kind = "";
|
||||
let view = storedView();
|
||||
let rows = [];
|
||||
let cursor = null;
|
||||
let total = null;
|
||||
let generation = 0;
|
||||
let refreshTimer = null;
|
||||
/** Codecs and years of the videos seen on this page, offered by their menus (the API has no facets for them). */
|
||||
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). */
|
||||
let folder = null;
|
||||
api.get("/api/v1/server/settings").then((s) => {
|
||||
folder = s.videosPath ?? "";
|
||||
if (root.isConnected) drawMass();
|
||||
}, () => {});
|
||||
|
||||
actions.innerHTML = `
|
||||
<a class="btn" href="#/library?view=trash" data-i18n-title="Admin.Videos.Trash.Tip">${icons.trash}<span data-i18n="Admin.Library.Trash"></span></a>
|
||||
<button class="btn icon" id="refresh" data-i18n-title="Admin.Library.Refresh.Tip">${icons.refresh}</button>`;
|
||||
applyStrings(actions);
|
||||
actions.querySelector("#refresh").addEventListener("click", () => load());
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="toolbar" role="search">
|
||||
<input class="input search" type="search" id="q" dir="auto" value="${attr(filters.q)}" data-i18n-placeholder="Admin.Videos.Search"
|
||||
data-i18n-title="Admin.Videos.Search.Tip" aria-label="${attr(t("Admin.Videos.Search"))}">
|
||||
<select class="input small" id="kind" data-i18n-title="Admin.Videos.Kind.Tip" aria-label="${attr(t("Admin.Videos.Kind"))}"></select>
|
||||
<select class="input small" id="codec" data-i18n-title="Admin.Videos.Codec.Tip" aria-label="${attr(t("Admin.Videos.Codec"))}"></select>
|
||||
<select class="input small" id="year" data-i18n-title="Admin.Videos.Year.Tip" aria-label="${attr(t("Admin.Videos.Year"))}"></select>
|
||||
<select class="input small" id="sort" data-i18n-title="Admin.Videos.Sort.Tip" aria-label="${attr(t("Admin.Videos.Sort"))}">${SORTS.map((s) =>
|
||||
`<option value="${s}" ${s === filters.sort ? "selected" : ""}>${escapeHtml(t(`Admin.Videos.Sort.${cap(s)}`))}</option>`).join("")}</select>
|
||||
<span class="inline" id="sequence-filter"></span>
|
||||
<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip" hidden></button>
|
||||
<span class="spacer"></span>
|
||||
<div class="segmented" role="group" aria-label="${attr(t("Admin.Library.View"))}">
|
||||
<button class="btn icon" data-view="cards" aria-pressed="${view === "cards"}" data-i18n-title="Admin.Videos.View.Cards.Tip"
|
||||
aria-label="${attr(t("Admin.Videos.View.Cards"))}">${icons.grid}</button>
|
||||
<button class="btn icon" data-view="list" aria-pressed="${view === "list"}" data-i18n-title="Admin.Videos.View.List.Tip"
|
||||
aria-label="${attr(t("Admin.Videos.View.List"))}">${icons.list}</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="panel flush library" aria-label="${attr(t("Admin.Videos.Title"))}">
|
||||
<div id="items"></div>
|
||||
<div class="table-foot" id="foot" hidden><span class="muted" id="shown"></span><span class="spacer"></span>
|
||||
<button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
|
||||
</section>
|
||||
<div class="mass-bar" id="mass" role="toolbar" aria-label="${attr(t("Admin.Library.Selection"))}" hidden></div>`;
|
||||
applyStrings(root);
|
||||
const itemsHost = root.querySelector("#items");
|
||||
const mass = root.querySelector("#mass");
|
||||
|
||||
let searchTimer = null;
|
||||
root.querySelector("#q").addEventListener("input", (e) => {
|
||||
clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(() => setFilter("q", e.target.value.trim()), 300);
|
||||
});
|
||||
for (const f of ["kind", "codec", "year", "sort"]) root.querySelector(`#${f}`).addEventListener("change", (e) => setFilter(f, e.target.value));
|
||||
root.querySelector("#clear").addEventListener("click", clearFilters);
|
||||
root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
|
||||
view = b.dataset.view;
|
||||
root.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
|
||||
try {
|
||||
localStorage.setItem(VIEW_KEY, view);
|
||||
} catch {
|
||||
// Only this page keeps the view then.
|
||||
}
|
||||
draw();
|
||||
}));
|
||||
root.querySelector("#more").addEventListener("click", () => load(true));
|
||||
|
||||
const grid = selectableGrid(itemsHost, {
|
||||
selection,
|
||||
order: () => rows.map((v) => v.id),
|
||||
open: (key) => play(rows.find((v) => v.id === key)),
|
||||
onChange: syncSelection,
|
||||
});
|
||||
|
||||
function setFilter(name, value) {
|
||||
if (filters[name] === value) return;
|
||||
filters[name] = value;
|
||||
writeAddress();
|
||||
selection.clear();
|
||||
load();
|
||||
}
|
||||
|
||||
function clearFilters() {
|
||||
for (const f of FILTERS) filters[f] = f === "sort" ? filters.sort : "";
|
||||
root.querySelector("#q").value = "";
|
||||
writeAddress();
|
||||
selection.clear();
|
||||
load();
|
||||
root.querySelector("#q").focus();
|
||||
}
|
||||
|
||||
/** The address keeps the filters (no hashchange: the page stays), so a reload or a link shows the same list. */
|
||||
function writeAddress() {
|
||||
const query = new URLSearchParams(Object.entries(filters).filter(([k, v]) => v && !(k === "sort" && v === "newest")));
|
||||
history.replaceState(null, "", `#/videos${query.size ? `?${query}` : ""}`);
|
||||
}
|
||||
|
||||
function isFiltered() {
|
||||
return FILTERS.some((f) => f !== "sort" && filters[f]);
|
||||
}
|
||||
|
||||
function listQuery(limit, after) {
|
||||
const p = new URLSearchParams({ limit: String(limit) });
|
||||
for (const f of ["q", "kind", "codec", "year", "sequence"]) if (filters[f]) p.set(f, filters[f]);
|
||||
if (filters.sort !== "newest") p.set("sort", filters.sort);
|
||||
if (after) p.set("cursor", after);
|
||||
return `/api/v1/videos?${p}`;
|
||||
}
|
||||
|
||||
async function load(more = false) {
|
||||
const mine = ++generation;
|
||||
let page;
|
||||
try {
|
||||
page = await api.get(listQuery(PAGE, more ? cursor : null));
|
||||
} catch (err) {
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
toast(errorText(err), true);
|
||||
if (!more && rows.length === 0) draw();
|
||||
return;
|
||||
}
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
cursor = page.next ?? null;
|
||||
if (!more) total = page.total ?? null;
|
||||
learn(page.items);
|
||||
if (more) {
|
||||
rows = rows.concat(page.items);
|
||||
itemsHost.insertAdjacentHTML("beforeend", page.items.map(itemHtml).join(""));
|
||||
watchImages(itemsHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
} else {
|
||||
rows = page.items;
|
||||
draw();
|
||||
}
|
||||
drawFilters();
|
||||
drawFoot();
|
||||
}
|
||||
|
||||
/** The videos shown again (a job ended, a sequence changed), as many as are shown; the selection keeps those still there. */
|
||||
async function refreshVisible() {
|
||||
const mine = ++generation;
|
||||
const wanted = Math.max(rows.length, PAGE);
|
||||
let items = [];
|
||||
let after = null;
|
||||
let counted = total;
|
||||
try {
|
||||
do {
|
||||
const page = await api.get(listQuery(Math.min(wanted - items.length, MAX_PAGE), after));
|
||||
if (items.length === 0) counted = page.total ?? null;
|
||||
items = items.concat(page.items);
|
||||
after = page.next ?? null;
|
||||
} while (after && items.length < wanted);
|
||||
} catch {
|
||||
// The next event or Refresh tries again.
|
||||
return;
|
||||
}
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
rows = items;
|
||||
cursor = after;
|
||||
total = counted;
|
||||
learn(rows);
|
||||
const known = new Set(rows.map((v) => v.id));
|
||||
selection.set([...selection.ids].filter((id) => known.has(id)));
|
||||
const focused = itemsHost.contains(document.activeElement);
|
||||
draw();
|
||||
grid.restore(focused);
|
||||
drawFilters();
|
||||
drawFoot();
|
||||
}
|
||||
|
||||
function refreshSoon(delay) {
|
||||
clearTimeout(refreshTimer);
|
||||
refreshTimer = setTimeout(() => {
|
||||
if (root.isConnected) refreshVisible();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function learn(items) {
|
||||
for (const v of items) {
|
||||
if (v.codec) codecs.add(v.codec.toLowerCase());
|
||||
years.add(String(new Date(v.created).getUTCFullYear()));
|
||||
}
|
||||
}
|
||||
|
||||
function drawFilters() {
|
||||
const option = (value, label, chosen) => `<option value="${attr(value)}" ${value === chosen ? "selected" : ""}>${escapeHtml(label)}</option>`;
|
||||
// A value of the address no video shown has stays in its menu, so the filter shows what the list does.
|
||||
const withChosen = (set, chosen) => [...new Set([...set, ...(chosen ? [chosen] : [])])].sort();
|
||||
root.querySelector("#kind").innerHTML = option("", t("Admin.Videos.Kind.All"), filters.kind) +
|
||||
KINDS.map((k) => option(k, t(`Admin.Videos.Kind.${cap(k)}`), filters.kind)).join("");
|
||||
root.querySelector("#codec").innerHTML = option("", t("Admin.Videos.Codec.All"), filters.codec) +
|
||||
withChosen(codecs, filters.codec).map((c) => option(c, codecLabel(c), filters.codec)).join("");
|
||||
root.querySelector("#year").innerHTML = option("", t("Admin.Videos.Year.All"), filters.year) +
|
||||
withChosen(years, filters.year).reverse().map((y) => option(y, y, filters.year)).join("");
|
||||
root.querySelectorAll(".toolbar select").forEach((s) => s.classList.toggle("active", s.id !== "sort" && s.value !== ""));
|
||||
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 ?? 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>
|
||||
<button class="btn icon small subtle" id="clear-sequence" data-i18n-title="Admin.Videos.Sequence.Clear.Tip"
|
||||
aria-label="${attr(t("Admin.Videos.Sequence.Clear.Tip"))}">${icons.close}</button>` : "";
|
||||
applyStrings(chip);
|
||||
chip.querySelector("#clear-sequence")?.addEventListener("click", () => setFilter("sequence", ""));
|
||||
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");
|
||||
itemsHost.setAttribute("aria-multiselectable", "true");
|
||||
itemsHost.setAttribute("aria-label", t("Admin.Videos.Title"));
|
||||
if (rows.length === 0) {
|
||||
itemsHost.removeAttribute("role");
|
||||
itemsHost.removeAttribute("aria-multiselectable");
|
||||
itemsHost.innerHTML = emptyState("Admin.Videos.Empty", isFiltered()
|
||||
? `<button class="btn small" id="clear-empty" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>` : "");
|
||||
applyStrings(itemsHost);
|
||||
itemsHost.querySelector("#clear-empty")?.addEventListener("click", clearFilters);
|
||||
syncSelection();
|
||||
return;
|
||||
}
|
||||
const head = view === "list" ? `<div class="seq-head" aria-hidden="true"><span></span><span></span>
|
||||
<span data-i18n="Admin.Videos.Column.Title"></span><span class="col-kind" data-i18n="Admin.Videos.Column.Kind"></span>
|
||||
<span class="col-format" data-i18n="Admin.Videos.Column.Format"></span><span class="end col-duration" data-i18n="Admin.Videos.Column.Duration"></span>
|
||||
<span class="end col-bytes" data-i18n="Admin.Videos.Column.Size"></span><span class="col-date" data-i18n="Admin.Videos.Column.Date"></span>
|
||||
<span class="col-hash" data-i18n="Admin.Videos.Column.Hash"></span><span data-i18n="Admin.Videos.Column.State"></span></div>` : "";
|
||||
itemsHost.innerHTML = head + rows.map(itemHtml).join("");
|
||||
applyStrings(itemsHost);
|
||||
watchImages(itemsHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
function itemHtml(v) {
|
||||
const kind = videoKind(v);
|
||||
const format = formatText(v);
|
||||
const length = kind === "still" ? "" : clock(v.durationSeconds);
|
||||
const label = [v.sequenceTitle, v.presetName, format, length, formatBytes(v.bytes)].filter(Boolean).join(" · ");
|
||||
const check = `<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Videos.Select.Tip"))}">`;
|
||||
const thumb = lazyImage(posterUrl(v));
|
||||
const missing = v.state === "missing" ? " missing" : "";
|
||||
if (view === "list") {
|
||||
return `<div class="seq-row${missing}" role="option" data-key="${attr(v.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Videos.Play.Tip"))}">
|
||||
${check}${thumb}
|
||||
<span class="stack"><strong class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</strong>
|
||||
<small dir="auto">${escapeHtml(presetText(v))}</small></span>
|
||||
<span class="nowrap col-kind">${escapeHtml(kindText(kind))}</span>
|
||||
<span class="num nowrap col-format" dir="ltr">${escapeHtml(format)}</span>
|
||||
<span class="num end nowrap col-duration">${escapeHtml(length || "—")}</span>
|
||||
<span class="num end nowrap col-bytes">${escapeHtml(formatBytes(v.bytes))}</span>
|
||||
<span class="muted nowrap col-date">${escapeHtml(formatDateTime(v.created))}</span>
|
||||
<span class="mono muted nowrap col-hash" dir="ltr" title="${attr(v.sha256 ?? "")}">${escapeHtml(shortHash(v.sha256))}</span>
|
||||
<span class="chips-row">${stateChips(v)}</span>
|
||||
</div>`;
|
||||
}
|
||||
return `<div class="seq-card${missing}" role="option" data-key="${attr(v.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Videos.Play.Tip"))}">
|
||||
${thumb}${check}
|
||||
<span class="count num" aria-hidden="true">${escapeHtml(length || kindText(kind))}</span>
|
||||
<span class="info"><strong class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</strong>
|
||||
<span class="facts ellipsis" dir="auto">${escapeHtml(presetText(v))}</span>
|
||||
<span class="facts ellipsis num" dir="ltr">${escapeHtml([format, formatBytes(v.bytes)].join(" · "))}</span>
|
||||
<span class="facts ellipsis">${escapeHtml(formatDateTime(v.created))}</span>
|
||||
<span class="chips-row">${stateChips(v)}</span></span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function drawFoot() {
|
||||
const known = total ?? rows.length;
|
||||
root.querySelector("#foot").hidden = rows.length === 0 || (!cursor && rows.length >= known);
|
||||
root.querySelector("#more").hidden = !cursor;
|
||||
root.querySelector("#shown").textContent = t("Admin.Library.Shown", formatNumber(rows.length), total === null ? "…" : formatNumber(total));
|
||||
}
|
||||
|
||||
function syncSelection() {
|
||||
itemsHost.querySelectorAll('[role="option"]').forEach((el) => {
|
||||
const on = selection.has(el.dataset.key);
|
||||
el.setAttribute("aria-selected", String(on));
|
||||
const box = el.querySelector("[data-check]");
|
||||
if (box) box.checked = on;
|
||||
});
|
||||
itemsHost.classList.toggle("selecting", selection.size > 0);
|
||||
drawMass();
|
||||
}
|
||||
|
||||
/** The selection's actions: Play and Download for one video, Copy to folder and Delete… for any number. */
|
||||
function drawMass() {
|
||||
const n = selection.size;
|
||||
if (n === 0) {
|
||||
mass.hidden = true;
|
||||
mass.innerHTML = "";
|
||||
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;
|
||||
redraw(mass, () => {
|
||||
mass.innerHTML = `
|
||||
<strong class="nowrap" role="status">${escapeHtml(t("Admin.Videos.Selected", formatNumber(n)))}</strong>
|
||||
${n < rows.length ? `<button class="btn small subtle" id="mass-all" data-mass="all" data-i18n="Admin.Sequence.SelectAll" data-i18n-title="Admin.Videos.SelectAll.Tip"></button>` : ""}
|
||||
<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="${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"
|
||||
data-i18n-title="${deleteWhy ?? "Admin.Videos.Delete.Tip"}" ${deleteWhy ? "disabled" : ""}></button>
|
||||
<button class="btn small icon subtle" id="mass-clear" data-mass="clear" data-i18n-title="Admin.Library.ClearSelection.Tip">${icons.close}</button>`;
|
||||
applyStrings(mass);
|
||||
});
|
||||
mass.querySelectorAll("[data-mass]").forEach((b) => b.addEventListener("click", () => massAction(b.dataset.mass, b)));
|
||||
}
|
||||
|
||||
async function massAction(action, button) {
|
||||
const [only] = selection.ids;
|
||||
switch (action) {
|
||||
case "clear":
|
||||
selection.clear();
|
||||
syncSelection();
|
||||
return grid.restore(true);
|
||||
case "all":
|
||||
selection.set(rows.map((v) => v.id));
|
||||
return syncSelection();
|
||||
case "play":
|
||||
return play(rows.find((v) => v.id === only));
|
||||
case "download":
|
||||
return download(rows.find((v) => v.id === only));
|
||||
}
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (action === "copy") await copyVideos([...selection.ids]);
|
||||
else if (action === "delete") await deleteVideos([...selection.ids]);
|
||||
} finally {
|
||||
if (button.isConnected) drawMass();
|
||||
}
|
||||
}
|
||||
|
||||
function download(v) {
|
||||
if (!v || downloadBlock(v)) return;
|
||||
const a = document.createElement("a");
|
||||
a.href = fileUrl(v);
|
||||
a.download = v.fileName ?? "";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
|
||||
/** One video-copy job for the selection; the server checks every copy against its render's hash. */
|
||||
async function copyVideos(ids) {
|
||||
let result;
|
||||
try {
|
||||
result = await api.post("/api/v1/videos/copy", { ids });
|
||||
} catch (err) {
|
||||
// videos_folder_unset: the folder went since the page read it; Copy says why from now on.
|
||||
if (err.code === "videos_folder_unset") folder = "";
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
toast(t("Admin.Videos.Copy.Queued", formatNumber(ids.length)), false,
|
||||
{ label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(result.jobId)}` });
|
||||
}
|
||||
|
||||
/**
|
||||
* The dry run (what goes, its bytes, what stays and why), the confirmation saying the videos folder's copies stay, then
|
||||
* the move into the trash with the plan's fingerprint: a plan that changed meanwhile (409 plan_changed) moves nothing.
|
||||
*/
|
||||
async function deleteVideos(ids) {
|
||||
let plan;
|
||||
try {
|
||||
plan = await api.post("/api/v1/videos/delete", { ids, dryRun: true, fingerprint: null });
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
const known = new Map(rows.map((v) => [v.id, v]));
|
||||
const name = (id) => {
|
||||
const v = known.get(id);
|
||||
return v ? `${v.sequenceTitle} · ${v.fileName ?? v.presetName}` : id;
|
||||
};
|
||||
const blocked = plan.blocked.map((b) => t("Admin.Library.BlockedItem", name(b.id), blockedText(b.reason)));
|
||||
if (plan.items.length === 0) {
|
||||
toast(blocked.join(" · ") || t("Admin.Videos.Empty"), true);
|
||||
return;
|
||||
}
|
||||
const going = plan.items.map((i) => i.missing
|
||||
? t("Admin.Library.BlockedItem", `${i.sequenceTitle} · ${i.fileName ?? "—"}`, t("Admin.Videos.Delete.Missing"))
|
||||
: t("Admin.Trash.PlanItem", i.sequenceTitle, i.fileName ?? "—", formatBytes(i.bytes)));
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Videos.Delete.Title"),
|
||||
body: [t("Admin.Videos.Delete.Summary", formatNumber(plan.items.length), formatBytes(plan.bytes)),
|
||||
plan.blocked.length > 0 ? t("Admin.Videos.Delete.Blocked", formatNumber(plan.blocked.length)) : "",
|
||||
t("Admin.Videos.Delete.CopiesStay")].filter(Boolean).join(" "),
|
||||
// Those that stay first, with their reasons; the summary counts what goes.
|
||||
list: listed([...blocked, ...going]),
|
||||
confirm: t("Admin.Videos.Delete.Confirm"),
|
||||
confirmTip: t("Admin.Videos.Delete.Confirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
let result;
|
||||
try {
|
||||
result = await api.post("/api/v1/videos/delete", { ids, dryRun: false, fingerprint: plan.fingerprint });
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
if (err.code === "plan_changed") await load();
|
||||
return;
|
||||
}
|
||||
toast(t("Admin.Videos.Delete.Done", formatNumber(result.items.length)), false,
|
||||
{ label: t("Admin.Library.Trash"), tip: t("Admin.Videos.Trash.Tip"), href: "#/library?view=trash" });
|
||||
selection.clear();
|
||||
await load();
|
||||
}
|
||||
|
||||
/**
|
||||
* The player: a <video> with its controls for MP4, MOV and WebM (the session cookie authorises its range requests), an
|
||||
* image for stills, GIF and APNG, else (or when the browser cannot decode it) a sentence and the download. Esc closes.
|
||||
*/
|
||||
function play(v) {
|
||||
if (!v) return;
|
||||
const opener = document.activeElement;
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog viewer player";
|
||||
dialog.setAttribute("aria-labelledby", "player-title");
|
||||
const type = fileType(v);
|
||||
const media = v.state === "missing" ? "" : VIDEO_TYPES.has(type) ? `<video controls autoplay preload="metadata" src="${attr(fileUrl(v))}"></video>`
|
||||
: IMAGE_TYPES.has(type) ? `<img alt="${attr(v.fileName ?? "")}" src="${attr(fileUrl(v))}">` : "";
|
||||
const fact = (key, value, ltr = false) => value ? `<div><dt data-i18n="${key}"></dt><dd ${ltr ? 'dir="ltr" class="mono"' : 'dir="auto"'}>${escapeHtml(value)}</dd></div>` : "";
|
||||
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>
|
||||
${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>
|
||||
<dl class="viewer-meta">${[
|
||||
fact("Admin.Videos.Column.Preset", presetText(v)),
|
||||
fact("Admin.Videos.Column.Kind", kindText(videoKind(v))),
|
||||
fact("Admin.Videos.Column.Format", formatText(v), true),
|
||||
fact("Admin.Videos.Column.Duration", videoKind(v) === "still" ? "" : clock(v.durationSeconds), true),
|
||||
fact("Admin.Videos.Column.Size", formatBytes(v.bytes)),
|
||||
fact("Admin.Videos.Column.Date", formatDateTime(v.created)),
|
||||
fact("Admin.Videos.Column.Hash", v.sha256 ?? "", true),
|
||||
fact("Admin.Videos.State.Copied", (v.copies ?? []).map((c) => c.path).join("\n"), true),
|
||||
].join("")}</dl>`;
|
||||
applyStrings(dialog);
|
||||
document.body.appendChild(dialog);
|
||||
const shown = dialog.querySelector("video, img");
|
||||
// A file the browser cannot decode (HEVC without its decoder, a TIFF still) says so, and the download stays.
|
||||
shown?.addEventListener("error", () => {
|
||||
shown.remove();
|
||||
dialog.querySelector(".player-note").hidden = false;
|
||||
});
|
||||
dialog.querySelector("[data-close]").addEventListener("click", () => dialog.close());
|
||||
dialog.addEventListener("close", () => {
|
||||
const video = dialog.querySelector("video");
|
||||
if (video) {
|
||||
// Stops the playback and its range requests at once.
|
||||
video.pause();
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
}
|
||||
dialog.remove();
|
||||
const item = itemsHost.querySelector(`[data-key="${CSS.escape(v.id)}"]`);
|
||||
(item ?? opener)?.focus?.();
|
||||
});
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
// A copy that ended adds its copies, a render job adds videos, a deletion or a restore elsewhere takes them away.
|
||||
onEvent((e) => {
|
||||
if (e.type === "jobState" && JOB_ENDED.has(e.state)) refreshSoon(1500);
|
||||
else if (e.type === "sequenceChanged") refreshSoon(800);
|
||||
else if (e.type === "reconnected") refreshSoon(0);
|
||||
});
|
||||
drawFilters();
|
||||
await load();
|
||||
}
|
||||
|
||||
/** The library kind of a render, as RenderKind.Of: its kind when recorded, else sequence for an image-sequence codec, else video. */
|
||||
export function videoKind(v) {
|
||||
if (v.kind) return v.kind;
|
||||
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");
|
||||
if (kind === "sequence") return t("Admin.Videos.Kind.Sequence.Label");
|
||||
if (kind === "video") return t("Admin.Videos.Kind.Video.Label");
|
||||
return kind;
|
||||
}
|
||||
|
||||
/** "H.264", "HEVC", "PNG" for pngsequence, as users know them. */
|
||||
export function codecLabel(codec) {
|
||||
const c = String(codec ?? "").toLowerCase();
|
||||
if (!c) return "";
|
||||
if (CODECS[c]) return CODECS[c];
|
||||
return (c.endsWith("sequence") ? c.slice(0, -"sequence".length) : c).toUpperCase();
|
||||
}
|
||||
|
||||
/** The first twelve hex digits of a hash (the whole one in the tooltip); a dash when it is not hashed yet. */
|
||||
export function shortHash(sha256) {
|
||||
return sha256 ? sha256.slice(0, 12) : "—";
|
||||
}
|
||||
|
||||
function formatText(v) {
|
||||
const parts = [`${v.width} × ${v.height}`];
|
||||
if (v.codec) parts.push(codecLabel(v.codec));
|
||||
if (videoKind(v) !== "still" && v.fps > 0) parts.push(`${formatNumber(Math.round(v.fps * 100) / 100)} fps`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
function presetText(v) {
|
||||
return v.projectName ? `${v.presetName} · ${v.projectName}${v.projectVersionNumber ? ` v${v.projectVersionNumber}` : ""}` : v.presetName;
|
||||
}
|
||||
|
||||
function stateChips(v) {
|
||||
const chips = [];
|
||||
if (v.state === "missing") chips.push(`<span class="st warn" title="${attr(t("Admin.Videos.State.Missing.Tip"))}"><span aria-hidden="true">▲</span> ${escapeHtml(t("Admin.Videos.State.Missing"))}</span>`);
|
||||
const copies = v.copies ?? [];
|
||||
if (copies.length > 0) {
|
||||
chips.push(`<span class="st ok" title="${attr(t("Admin.Videos.State.Copied.Tip", copies.map((c) => c.path).join(", ")))}"><span aria-hidden="true">✓</span> ${escapeHtml(t("Admin.Videos.State.Copied"))}</span>`);
|
||||
}
|
||||
return chips.join("");
|
||||
}
|
||||
|
||||
function blockedText(reason) {
|
||||
if (reason === "busy") return t("Admin.Videos.Blocked.Busy");
|
||||
if (reason === "not_found") return t("Admin.Videos.Blocked.NotFound");
|
||||
return reason;
|
||||
}
|
||||
|
||||
function fileUrl(v) {
|
||||
return `/api/v1/renders/${encodeURIComponent(v.id)}/file`;
|
||||
}
|
||||
|
||||
/** A still the browser shows is its own poster; anything else shows its sequence's cover. */
|
||||
function posterUrl(v) {
|
||||
if (videoKind(v) === "still" && v.state !== "missing" && IMAGE_TYPES.has(fileType(v))) return fileUrl(v);
|
||||
return `/api/v1/sequences/${encodeURIComponent(v.sequenceId)}/thumb`;
|
||||
}
|
||||
|
||||
function fileType(v) {
|
||||
const name = String(v.fileName ?? "");
|
||||
const dot = name.lastIndexOf(".");
|
||||
return dot < 0 ? "" : name.slice(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
/** A video length as 1:05 or 1:02:05. */
|
||||
function clock(seconds) {
|
||||
const s = Math.max(0, Math.round(seconds ?? 0));
|
||||
const hh = Math.floor(s / 3600);
|
||||
const mm = Math.floor((s % 3600) / 60);
|
||||
const ss = String(s % 60).padStart(2, "0");
|
||||
return hh > 0 ? `${hh}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function storedView() {
|
||||
try {
|
||||
return localStorage.getItem(VIEW_KEY) === "list" ? "list" : "cards";
|
||||
} catch {
|
||||
return "cards";
|
||||
}
|
||||
}
|
||||
|
||||
function cap(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public static class Dto
|
||||
f.FocalLength, f.Orientation, f.Width, f.Height, f.Format.ToString().ToLowerInvariant(), (long)f.Flags, f.PreviewWidth, f.PreviewHeight);
|
||||
|
||||
public static RenderDto Render(Render r) => new(r.Id, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId);
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, r.Kind);
|
||||
|
||||
public static JobDto Job(Job j) => new(
|
||||
j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone,
|
||||
|
||||
@@ -107,7 +107,7 @@ public sealed class ServerState
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects];
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects, ServerCapabilities.Videos];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
@@ -15,7 +16,7 @@ namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
|
||||
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
|
||||
/// deleted sequences, photos deleted from sequences and deleted videos (owner review 1, R9) —, restoring one, and emptying it: a dry run that measures the
|
||||
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
|
||||
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
|
||||
/// </summary>
|
||||
@@ -29,8 +30,11 @@ public static partial class TrashEndpoints
|
||||
trash.MapPost("/empty", EmptyAsync);
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
|
||||
/// <summary>
|
||||
/// Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>, or a videos entry
|
||||
/// <c>videos-<render id>-<ticks></c>, owner review 1, R9): never a path.
|
||||
/// </summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && (EntryName().IsMatch(name) || VideoTrashNames.IsEntryName(name));
|
||||
|
||||
public static TrashEntryDto Entry(TrashEntry e) =>
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt, e.ConversionDeleted);
|
||||
@@ -55,9 +59,11 @@ public static partial class TrashEndpoints
|
||||
/// a sequence, <c>frames</c> for photos.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, AuditLog audit, EventHub events,
|
||||
IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
|
||||
if (VideoTrashNames.IsEntryName(name)) return await RestoreVideoAsync(context, caller, name, db, archive, VideoEndpoints.Library(videos, archives, db), audit, events, lifetime);
|
||||
TrashRestoreResult result;
|
||||
try
|
||||
{
|
||||
@@ -107,6 +113,49 @@ public static partial class TrashEndpoints
|
||||
result.Kept.Count == 0 ? null : string.Join(" ", KeptPhoto.Sentences(result.Kept, culture))), ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a deleted video back (owner review 1, R9, decision 18): the trashed file re-hashed against its record, moved back
|
||||
/// into its sequence's folder (a free name when its own is taken) and its entry recorded again with the same render id.
|
||||
/// 404 <c>not_found</c> (<c>trash_entry</c>); 409 <c>sequence_gone</c> (restore the sequence first), <c>sequence_busy</c>,
|
||||
/// <c>folder_in_use</c>; 422 <c>trash_hash_mismatch</c> (it stays in the trash); 503 <c>archive_offline</c>. Publishes
|
||||
/// <c>sequenceChanged</c> (<c>renders</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreVideoAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
IVideoLibrary library, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!library.IsAvailable) return ApiErrors.NotFound(context, "trash_entry");
|
||||
Render render;
|
||||
try
|
||||
{
|
||||
render = await library.RestoreAsync(archive.Id, name, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "trash_entry");
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return VideoEndpoints.Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Offline(context);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "trash_restored", "render", render.Id.ToString(), $"{name} · {Path.GetFileName(render.OutputPath.TrimEnd('/', '\\'))}");
|
||||
if (await db.Sequences.GetAsync(render.SequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(new TrashRestoreDto(name, TrashKind.Videos.ToString().ToLowerInvariant(), render.SequenceId, 1, [], NewSequence: false),
|
||||
ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>The code of why a photo stayed in the trash (<see cref="TrashRestoreDto.KeptReasons"/>).</summary>
|
||||
private static string ReasonCode(KeptReason reason) => reason switch
|
||||
{
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/videos</c> (owner review 1, R9; capability <see cref="ServerCapabilities.Videos"/>): every render of the
|
||||
/// server in one list, read by anyone who may read; deleting renders into the archive's trash (Delete), always a dry run
|
||||
/// first whose fingerprint the delete itself must give back, and restored through <c>/archive/trash/{name}/restore</c>;
|
||||
/// and copying them, hash-verified, into the server's videos folder as one <c>video-copy</c> job (Edit). The files
|
||||
/// themselves are <c>GET /api/v1/renders/{id}/file</c>. Deletes and copies are audited (<c>videos_deleted</c>,
|
||||
/// <c>videos_copied</c>). The panel manages and never edits (owner review 2, R6): nothing here changes a project or starts a render.
|
||||
/// </summary>
|
||||
public static class VideoEndpoints
|
||||
{
|
||||
/// <summary>The most renders one delete or copy names.</summary>
|
||||
public const int MaxIds = VideoQuery.MaxLimit;
|
||||
|
||||
/// <summary>Renders an audit entry names by file, the rest counted.</summary>
|
||||
private const int AuditNames = 5;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var videos = api.MapGroup("/videos").Requires(Permissions.Read);
|
||||
videos.MapGet("", ListAsync);
|
||||
videos.MapGet("/{id:guid}", GetAsync);
|
||||
videos.MapPost("/delete", DeleteAsync).Requires(Permissions.Delete);
|
||||
videos.MapPost("/copy", CopyAsync).Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>The videos library behind these endpoints: the host's, or that of an archive engine of its own (a test host that replaces the archive module).</summary>
|
||||
internal static IVideoLibrary Library(IVideoLibrary? videos, ArchiveService? archives, ChronosDatabase db) =>
|
||||
videos ?? LibraryEndpoints.Engine(archives, db).Videos;
|
||||
|
||||
public static VideoDto Video(VideoItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var r = item.Render;
|
||||
return new VideoDto(r.Id, r.SequenceId, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, item.Kind, item.SequenceTitle, item.SequenceFirstCapture, item.ProjectName, item.ProjectVersionNumber,
|
||||
item.State, [.. item.Copies.Select(c => new VideoCopyDto(c.Path, c.CopiedAt))], item.FileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One page of videos: <c>q</c> (sequence title, preset or file name), <c>kind</c> (<c>video</c>, <c>still</c>,
|
||||
/// <c>sequence</c>), <c>codec</c>, <c>year</c>, <c>sequence</c>, <c>sort</c> (<see cref="VideoSorts"/>), <c>cursor</c>,
|
||||
/// <c>limit</c> (1–500). 400 <c>invalid_filter</c> (details: the filter).
|
||||
/// </summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, string? q, string? kind, string? codec, int? year, Guid? sequence, string? sort,
|
||||
string? cursor, int? limit, ChronosDatabase db, [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos)
|
||||
{
|
||||
kind = Blank(kind)?.ToLowerInvariant();
|
||||
sort = Blank(sort)?.ToLowerInvariant();
|
||||
if (kind is not null and not (RenderKind.Video or RenderKind.Still or RenderKind.Sequence)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
|
||||
if (sort is not null && !VideoSorts.All.Contains(sort)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
if (year is < 1 or > 9999) return ApiErrors.BadRequest(context, "invalid_filter", "year");
|
||||
var query = VideoQuery.From(new VideoQueryDto(Blank(q), kind, Blank(codec), year, sequence, sort, Blank(cursor), limit));
|
||||
VideoPage page;
|
||||
try
|
||||
{
|
||||
page = await Library(videos, archives, db).ListAsync(query, context.RequestAborted);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or FormatException)
|
||||
{
|
||||
// A cursor of another listing, or one this server never gave.
|
||||
return ApiErrors.BadRequest(context, "invalid_cursor");
|
||||
}
|
||||
return Results.Json(new VideoPageDto([.. page.Items.Select(Video)], page.Next, page.Total), ProtocolJson.Default.VideoPageDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, ChronosDatabase db, [FromServices] ArchiveService? archives,
|
||||
[FromServices] IVideoLibrary? videos) =>
|
||||
await Library(videos, archives, db).GetAsync(id, context.RequestAborted) is { } item
|
||||
? Results.Json(Video(item), ProtocolJson.Default.VideoDto)
|
||||
: ApiErrors.NotFound(context, "render");
|
||||
|
||||
/// <summary>
|
||||
/// With <c>dryRun</c> the plan of moving <c>ids</c> into the archive's trash: the renders that go (one whose file is
|
||||
/// missing loses only its entry), their bytes, those left where they are (<c>busy</c>, <c>not_found</c>) and the plan's
|
||||
/// fingerprint; nothing moves. Otherwise the request carries that fingerprint and the renders move as planned, each
|
||||
/// into a trash entry (<see cref="VideoDeletePlanDto.TrashEntries"/>); copies in the videos folder are never touched.
|
||||
/// 400 <c>bad_request</c> (<c>ids</c>, <c>fingerprint</c>); 409 <c>plan_changed</c> (nothing moved), <c>video_busy</c>,
|
||||
/// <c>sequence_busy</c>, <c>folder_in_use</c>; 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c>
|
||||
/// (<c>renders</c>) for every sequence that lost a render.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, VideoDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var library = Library(videos, archives, db);
|
||||
if (!library.IsAvailable) return Unavailable(context);
|
||||
try
|
||||
{
|
||||
if (request.DryRun)
|
||||
{
|
||||
var plan = await library.PlanDeleteAsync(ids, context.RequestAborted);
|
||||
return Results.Json(new VideoDeletePlanDto([.. plan.Items.Select(Item)], plan.Bytes, [.. plan.Blocked.Select(Blocked)], plan.Fingerprint, DryRun: true),
|
||||
ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
// Files move into the trash: the delete runs to the end even if the client disconnects meanwhile.
|
||||
var result = await library.DeleteAsync(ids, request.Fingerprint, caller.User.Username, lifetime.ApplicationStopping);
|
||||
var moved = result.Deleted.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
|
||||
if (result.Deleted.Count > 0)
|
||||
{
|
||||
await audit.WriteAsync(caller, context, "videos_deleted", "videos", result.Deleted.Count == 1 ? result.Deleted[0].Render.Id.ToString() : null,
|
||||
Summary(result.Deleted.Count, moved, result.Deleted.Select(i => i.FileName)));
|
||||
}
|
||||
foreach (var sequenceId in result.Deleted.Select(i => i.Render.SequenceId).Distinct())
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
return Results.Json(new VideoDeletePlanDto([.. result.Deleted.Select(Item)], moved, [.. result.Blocked.Select(Blocked)], request.Fingerprint,
|
||||
DryRun: false, result.TrashEntries), ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file is open elsewhere: nothing of it moved.
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one <c>video-copy</c> job copying <c>ids</c> into the server's videos folder (<see cref="ServerOptions.VideosPath"/>),
|
||||
/// each copy hash-verified before it takes its name (a free one, " (2)" on a collision); the renders are never touched.
|
||||
/// 202 with the job. 400 <c>bad_request</c> (<c>ids</c>); 404 <c>not_found</c> (<c>render</c>, details); 409
|
||||
/// <c>videos_folder_unset</c>, <c>job_unavailable</c>; 422 <c>videos_folder_invalid</c> (inside the archive or the data
|
||||
/// folder); 507 <c>videos_no_space</c> (the folder's volume cannot take the renders' bytes).
|
||||
/// </summary>
|
||||
private static async Task<IResult> CopyAsync(HttpContext context, Caller caller, VideoCopyRequest request, ChronosDatabase db, ServerOptions options,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, VolumeSpace volumes, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var folder = Blank(options.VideosPath);
|
||||
var library = Library(videos, archives, db);
|
||||
if (folder is null) return ApiErrors.Conflict(context, VideoErrors.FolderUnset);
|
||||
if (!ServerSettingsStore.IsVideosFolder(folder, options) || (library.FolderProblem(folder) is { } problem && problem != VideoErrors.FolderUnset))
|
||||
return Refused(context, VideoErrors.FolderInvalid);
|
||||
var renders = new List<Render>(ids.Count);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render");
|
||||
renders.Add(render);
|
||||
}
|
||||
if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context);
|
||||
if (volumes.Measure(folder) is { } volume && volume.FreeBytes < renders.Sum(r => r.Bytes)) return Refused(context, VideoErrors.NoSpace);
|
||||
ArchiveJobRequest job;
|
||||
try
|
||||
{
|
||||
job = library.CopyJob(new VideoCopyParameters(ids, folder, FromServer: false, caller.User.Username));
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
var queued = await host.Engine.EnqueueAsync(job, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "videos_copied", "job", queued.Id.ToString(),
|
||||
Summary(renders.Count, renders.Sum(r => r.Bytes), renders.Select(r => Path.GetFileName(r.OutputPath.TrimEnd('/', '\\')))));
|
||||
return Results.Json(new VideoCopyResultDto(queued.Id), ProtocolJson.Default.VideoCopyResultDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The answer of a library refusal: its code with its status.</summary>
|
||||
internal static IResult Refused(HttpContext context, VideoLibraryException ex) => Refused(context, ex.Code);
|
||||
|
||||
private static IResult Refused(HttpContext context, string code) => ApiErrors.Result(context, code switch
|
||||
{
|
||||
VideoErrors.FolderInvalid or VideoErrors.HashMismatch => StatusCodes.Status422UnprocessableEntity,
|
||||
VideoErrors.NoSpace => StatusCodes.Status507InsufficientStorage,
|
||||
_ => StatusCodes.Status409Conflict,
|
||||
}, code);
|
||||
|
||||
/// <summary>This server's archive engine has no videos library (a build before it): nothing can be deleted or copied.</summary>
|
||||
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
|
||||
|
||||
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
|
||||
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids)
|
||||
{
|
||||
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
|
||||
return [.. ids.Distinct()];
|
||||
}
|
||||
|
||||
private static VideoDeleteItemDto Item(VideoItem item) =>
|
||||
new(item.Render.Id, item.Render.SequenceId, item.SequenceTitle, item.FileName, item.Missing ? 0 : item.Render.Bytes, item.Missing);
|
||||
|
||||
private static VideoBlockedDto Blocked(VideoBlocked blocked) => new(blocked.RenderId, blocked.Reason);
|
||||
|
||||
/// <summary>An audit entry's details: how many, their bytes, and the first file names.</summary>
|
||||
private static string Summary(int count, long bytes, IEnumerable<string> names) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{count} · {bytes} · {string.Join(", ", names.Take(AuditNames))}");
|
||||
|
||||
private static string? Blank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
||||
}
|
||||
@@ -40,6 +40,7 @@ public sealed class ServerOptions
|
||||
("CHRONOS_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("CHRONOS_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("CHRONOS_SPACE_PATH", nameof(SpacePath), (o, v) => o.SpacePath = v),
|
||||
("CHRONOS_VIDEOS_PATH", nameof(VideosPath), (o, v) => o.VideosPath = v),
|
||||
("CHRONOS_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("CHRONOS_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("CHRONOS_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
@@ -106,6 +107,14 @@ public sealed class ServerOptions
|
||||
/// </summary>
|
||||
public string? SpacePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The folder "Copy to videos folder" copies renders into, hash-verified, flat, " (2)" on a collision (owner review 1,
|
||||
/// R9; key <c>VideosPath</c>, variable <c>CHRONOS_VIDEOS_PATH</c>, which locks it). Docker: the <c>/videos</c> volume.
|
||||
/// Unset by default, which turns copying off (<c>videos_folder_unset</c>); an absolute folder outside the archive and
|
||||
/// the data folder (<see cref="ServerSettingsStore.IsVideosFolder"/>). Chronos never deletes what it copied there.
|
||||
/// </summary>
|
||||
public string? VideosPath { get; set; }
|
||||
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Chronos Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
@@ -394,6 +403,8 @@ public sealed class ServerOptions
|
||||
{
|
||||
throw new InvalidOperationException($"CHRONOS_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex);
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(VideosPath) && !Path.IsPathFullyQualified(VideosPath.Trim()))
|
||||
throw new InvalidOperationException("CHRONOS_VIDEOS_PATH must be an absolute folder, such as /videos.");
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration;
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
|
||||
/// (owner review 2, R11), and the public ports clients use (owner review 3); the listening ports, TLS and chunk size wait for
|
||||
/// (owner review 2, R11), the public ports clients use (owner review 3) and the videos folder (owner review 1, R9; checked by
|
||||
/// <see cref="IsVideosFolder"/>); the listening ports, TLS and chunk size wait for
|
||||
/// a restart. In a container the listening ports are locked: the template maps them. Job history is what the housekeeping system
|
||||
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the
|
||||
/// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there
|
||||
@@ -27,9 +28,11 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.EmptyTrash, JobKind.Convert,
|
||||
JobKind.EmptyTrash, JobKind.Convert, JobKind.VideoCopy,
|
||||
];
|
||||
|
||||
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private ServerSettingsDto? _saved;
|
||||
|
||||
@@ -52,8 +55,9 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Logs = request.Logs ?? before.Logs,
|
||||
PublicHttpPort = Public(request.PublicHttpPort, before.PublicHttpPort),
|
||||
PublicHttpsPort = Public(request.PublicHttpsPort, before.PublicHttpsPort),
|
||||
VideosPath = Videos(request.VideosPath, before.VideosPath),
|
||||
};
|
||||
if (Validate(request, before) is { } invalid) return ("invalid_setting", invalid);
|
||||
if (Validate(request, before, options) is { } invalid) return ("invalid_setting", invalid);
|
||||
lock (_gate)
|
||||
{
|
||||
var current = _saved ?? Snapshot(options, restartRequired: false);
|
||||
@@ -100,6 +104,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
// Read by LAN discovery and the admin redirect at every use: they apply at once.
|
||||
options.PublicHttpPort = request.PublicHttpPort;
|
||||
options.PublicHttpsPort = request.PublicHttpsPort;
|
||||
// Read by every copy request: it applies at once.
|
||||
options.VideosPath = request.VideosPath;
|
||||
logging.Apply(options);
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
@@ -123,7 +129,41 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer);
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer,
|
||||
string.IsNullOrWhiteSpace(o.VideosPath) ? null : o.VideosPath.Trim());
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="folder"/> may be the videos folder (owner review 1, R9): an absolute folder that is neither the
|
||||
/// archive nor the data folder nor inside either, so a copy never lands among the files the server indexes or keeps.
|
||||
/// </summary>
|
||||
public static bool IsVideosFolder(string folder, ServerOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (string.IsNullOrWhiteSpace(folder) || folder.Contains('\0', StringComparison.Ordinal) || !Path.IsPathFullyQualified(folder.Trim())) return false;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder.Trim()));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
foreach (var root in new[] { options.ArchivePath, options.DataPath })
|
||||
{
|
||||
var rootFull = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
if (string.Equals(full, rootFull, PathComparison) || full.StartsWith(rootFull + Path.DirectorySeparatorChar, PathComparison)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The videos folder as a request sets it: null keeps <paramref name="current"/>, an empty text clears it.</summary>
|
||||
private static string? Videos(string? requested, string? current) => requested switch
|
||||
{
|
||||
null => current,
|
||||
_ when string.IsNullOrWhiteSpace(requested) => null,
|
||||
_ => requested.Trim(),
|
||||
};
|
||||
|
||||
/// <summary>The listening ports, which a container's template maps (owner review 3).</summary>
|
||||
private static readonly string[] ContainerPorts = [nameof(ServerOptions.HttpPort), nameof(ServerOptions.HttpsPort)];
|
||||
@@ -177,8 +217,10 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
/// The first setting of <paramref name="r"/> out of range, or null. Listening ports are checked only when they change,
|
||||
/// so a value the panel cannot change (a container's, the test server's 0) never blocks saving the others.
|
||||
/// </summary>
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current)
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current, ServerOptions options)
|
||||
{
|
||||
// Checked when it changes, so a folder an environment variable sets never blocks saving the others.
|
||||
if (r.VideosPath is { } videos && videos != current.VideosPath && !IsVideosFolder(videos, options)) return nameof(ServerOptions.VideosPath);
|
||||
if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName);
|
||||
var portsChanged = r.HttpPort != current.HttpPort || r.HttpsPort != current.HttpsPort;
|
||||
if (portsChanged && r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort);
|
||||
@@ -244,6 +286,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Add(nameof(ServerOptions.LogRotation), Rotation(a.Logs.Rotation), Rotation(b.Logs.Rotation), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.AuditRetentionDays), a.Logs.AuditRetentionDays, b.Logs.AuditRetentionDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.DiagnosticsLogMb), a.Logs.DiagnosticsLogMb, b.Logs.DiagnosticsLogMb, v => JsonValue.Create(v));
|
||||
// A cleared videos folder is stored as null, so server.json no longer sets one.
|
||||
Add(nameof(ServerOptions.VideosPath), a.VideosPath, b.VideosPath, v => v is null ? null : JsonValue.Create(v));
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TLS_CERT CHRONOS_TLS_KEY CHRONOS_LANG
|
||||
CHRONOS_SPACE_PATH folder whose volume's free space the admin panel shows (default: the archive's); on
|
||||
Unraid the share's array view (/mnt/user0/<share>) mapped read-only to /space
|
||||
CHRONOS_VIDEOS_PATH folder "Copy to videos folder" copies renders into, hash-verified (default: none, copying
|
||||
off); in a container the /videos volume
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
|
||||
@@ -187,6 +187,7 @@ public static class ServerHost
|
||||
ProjectEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
VideoEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
|
||||
@@ -3,6 +3,7 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
@@ -37,7 +38,7 @@ public static class ArchiveModule
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
var volumes = sp.GetService<VolumeSpace>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(db, new ArchiveServiceOptions
|
||||
var service = new ArchiveService(db, new ArchiveServiceOptions
|
||||
{
|
||||
// A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3).
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
@@ -71,9 +72,14 @@ public static class ArchiveModule
|
||||
// Next to the index in the data folder, where the daily backups always went.
|
||||
BackupDirectory = Path.Combine(options.DataPath, DatabaseBackups.DirectoryName),
|
||||
});
|
||||
// A copy job checks its folder again when it runs: the data folder is refused there too, as the settings refuse it.
|
||||
service.Videos.ProtectedFolders = () => [options.DataPath];
|
||||
return service;
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
// The videos library of the archive's index (owner review 1, R9): /api/v1/videos.
|
||||
services.AddSingleton<IVideoLibrary>(sp => sp.GetRequiredService<ArchiveService>().Videos);
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 729 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user