fix: address the phase 5 review

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

Refs #21

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

No files matched your search

+8
View File
@@ -65,6 +65,14 @@ commits follow Conventional Commits (release notes are generated from them by `C
change, saying *This server's Chronos cannot read these settings; update it*.
### Fixed
- Export and Videos, found by the phase's review before any release had them: a video deleted to the trash or restored
across drives while another program holds it open is no longer lost or half-removed (the original stays whole and is
removed at the next start); a restore never lands on a name a render is writing, and a render never overwrites a
file; a video changed since it was recorded can still be restored; a playback-free export never goes to a node that
cannot read its settings; a saved frame stays a still on an older server; star trails grow again in each loop;
encoder settings Windows ignored are listed as warnings; the Videos list fits beside the player, a downloaded server
video plays from its copy, disabled actions say why, and the server panel offers no download for image sequences or
missing files.
- Visual crop, transforms and looks, found by the phase's review before any release had them (one adversarial round, 30
findings, all confirmed and fixed, and a final check that fixed one more): a render whose aspect changed after it
was posted is sized from its preset again, and a job no longer waits for a node that will never take it; settings
+5
View File
@@ -759,3 +759,8 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-05 | Owner review 1 phase 5, open questions without an answer take the plan's defaults: Q1 own section, Ctrl+4; Q2 MediaElement pane with fallback; Q3 "Render" only; Q4 preview stays forward; Q5 reverse trails in program order, boomerang disabled; Q6 loops 1–10, fades 0–30 s (slider 0–10), hold 0–60 s (slider 0–10) (`PlaybackSettings.MaxLoops/MaxFadeSeconds/MaxHoldSeconds`); Q7 PNG, JPEG, TIFF 16-bit; Q8 `<template> - 0123.<ext>`; Q9 unsent workspace renders listed read-only; Q10 no Remove copy; Q11 flat folder; Q12 `%USERPROFILE%\Videos\Chronos`, server unset; Q13 lazy hashing; Q14 copy needs Edit, delete Delete, restore ManageArchive. | Wait for the owner | The brief asks to choose the simplest safe option and continue. |
| 2026-11-05 | Phase 5 groundwork (P0) contracts beyond the plan's list: `PlaybackDirection` string constants; `ProjectSettings.PlaybackVersion`; `RenderKind` (`Of(kind, codec)`); `RenderRules.StillFormat`, `StillCodecs` and a still-aware `RequiredFormat` overload; `ProcessingJobs.Still` (working); `RenderJobParameters.IsStill`; trailing optional `Kind` on `RenderResultRequest` and `RenderUploadRequest`; `ServerSettingsDto.VideosPath` (in Protocol, where the DTO lives); `VideoQueryDto`, `VideoCopyResultDto`, `VideoStates`, `VideoSorts`, `VideoBlockReasons`; `VideoErrors`, `VideoLibraryException`, `VideoTrashNames` in Data; `TrashKind.Videos`; `ArchiveService.Videos` (the `NotImplementedVideoLibrary` stub until P2) registered as `IVideoLibrary` on the server. The capability `videos` is declared but not announced until P3 serves the API. The section's strings use `Shell.Nav.Videos` / `Tooltips.Nav.Videos` (the rail builds `Shell.Nav.<key>`), not the plan's `Shell.Section.Videos`; `Editor.Render` stays until P5 moves the header to the existing `Editor.RenderButton`; `Tooltips.Nav.Archive/Jobs/Server` keep Ctrl+4…6 until P7 shifts the shortcuts. Italian follows the repository's terms ("Renderizza", "serie", "Attività", "Modifica"). Until P1 and P2 land, format 3 is written but `OutputProgram` is forward-only and still jobs are not handled by the render job handler. | Exactly the plan's names | Every later parcel compiles against P0 without touching shared files; the names follow the code that reads them. |
| 2026-11-05 | Phase 5 integration (P8): a workspace project's *Save frame* follows its renders: with the originals on this PC a still is a `WorkspaceRender` job (into `exports/`, recorded in the ledger, sent home later, no server-format gate); with proxies only it is the home's still job (archive `Render` or server) carrying the portable settings and the project id. A render Sync fetches is hashed on arrival and compared with the server's `sha256`; a mismatch is fetched once more, then the job fails. Unused export history, batch and card strings are deleted from English and pruned from every culture; `Tooltips.Export.LoopsNA` and `Videos.Log.Trashed/Restored` stay for their pending callers. | Leave Save frame disabled in workspace projects | Both job kinds already render stills; the routing is the one renders use, so a frame never needs the originals it does not have. |
| 2026-11-05 | Phase 5 review (1): a video delete or restore that copies (across volumes) is committed once the verified copy has its name; a source that cannot be removed then (a file held open) stays whole, since a folder is renamed aside before it is erased, and a `.leftover` marker beside the trash entry lets `RecoverAsync` (and the entry's next restore) remove it after re-hashing, never over a render recorded there since. A delete always re-hashes the file under its lease and brings the row's `sha256` up to date (a warning when it changed). | Undo the whole delete when the source cannot be removed | An undo by a second copy can fail the same way; a verified copy in the trash plus a whole original loses nothing. |
| 2026-11-05 | Phase 5 review (2): a restore picks its free name treating the names this process's renders are writing (`OutputNames`) as taken, and keeps its own reserved until the move is done; encoders commit with `AtomicFile.CommitNew` (no overwrite), so a render whose name was taken by another process fails instead of replacing that file. | Overwrite as before | A restored or copied video must never be replaced by a render that picked the same name. |
| 2026-11-05 | Phase 5 review (3): render routing floors the required settings format at the format of the stored settings text (`max(Version, WrittenFormat)`), so a format-2 node never gets format-3 text even when the playback is the default; a still whose kind an older server dropped is recognised on read (image codec, fps 0, duration 0) in `RenderKind.Of` and the library's SQL filter, instead of refusing the upload. | Gate still uploads by server format | Reading it back costs nothing and keeps older servers working. |
| 2026-11-05 | Phase 5 review (4): settings the encoder refused through ICodecAPI become render warnings (`Export.Encoder.Ignored.<Setting>`) only for values the export names itself: rate control other than VBR, the quality or a given bit rate, a given keyframe interval, B-frames other than the default 2 outside Baseline. Star trails restart their stack at each loop (`ProgramEntry.Pass`). | Fail the render | The encoder's own value still makes a valid video; the warning says which choice did not apply. |
| 2026-11-05 | Phase 5 review (5): the Videos list hides Preset, Format and Date while the player pane is open; a server video downloaded to this PC plays from its copy (`IVideoLibrary.CopiesAsync`); disabled actions say why in the bar and the context menu; the admin panel disables Download for an image sequence (a folder) and a missing file, and names a filtered sequence from its own record when none of its videos is on the page. | Keep the columns and scroll | The player pane is the reason the list is narrow; the hidden facts stay in the row's tooltip and the player. |
+2
View File
@@ -1132,6 +1132,8 @@
<data name="Admin.Videos.Download" xml:space="preserve"><value>Download</value></data>
<data name="Admin.Videos.Download.Tip" xml:space="preserve"><value>Download the file</value></data>
<data name="Admin.Videos.Download.One.Tip" xml:space="preserve"><value>Select one video to download it</value></data>
<data name="Admin.Videos.Download.Folder.Tip" xml:space="preserve"><value>An image sequence is a folder: copy it to a folder instead</value></data>
<data name="Admin.Videos.Download.Missing.Tip" xml:space="preserve"><value>The file is missing on the server</value></data>
<data name="Admin.Videos.Copy" xml:space="preserve"><value>Copy to folder</value></data>
<data name="Admin.Videos.Copy.Tip" xml:space="preserve"><value>Copy into the server's videos folder, checked by hash; the original stays</value></data>
<data name="Admin.Videos.Copy.NoFolder.Tip" xml:space="preserve"><value>Set a videos folder in Settings first</value></data>
+5
View File
@@ -148,6 +148,11 @@
<data name="Export.Render.FadesShortened" xml:space="preserve"><value>The fades were longer than half of the video and were shortened to fit.</value><comment>long</comment></data>
<data name="Export.Render.DirectionUnknown" xml:space="preserve"><value>Direction “{0}” not known; the video plays forward.</value><comment>long; {0} direction as stored</comment></data>
<data name="Export.Render.BoomerangStack" xml:space="preserve"><value>A boomerang is not rendered with star trails; the video plays forward.</value><comment>long</comment></data>
<data name="Export.Encoder.Ignored.RateControl" xml:space="preserve"><value>The encoder ignored the rate control; it used its own.</value><comment>long</comment></data>
<data name="Export.Encoder.Ignored.Quality" xml:space="preserve"><value>The encoder ignored the quality; it used its own.</value><comment>long</comment></data>
<data name="Export.Encoder.Ignored.BitRate" xml:space="preserve"><value>The encoder ignored the bit rate; it used its own.</value><comment>long</comment></data>
<data name="Export.Encoder.Ignored.KeyframeInterval" xml:space="preserve"><value>The encoder ignored the keyframe interval; it used its own.</value><comment>long</comment></data>
<data name="Export.Encoder.Ignored.BFrames" xml:space="preserve"><value>The encoder ignored the B-frames; it used its own.</value><comment>long</comment></data>
<data name="Export.Log.StillSaved" xml:space="preserve"><value>Frame {0} saved as {1}</value><comment>long: job log line; {0} frame number from 1; {1} file name</comment></data>
<data name="Export.Job.Verifying" xml:space="preserve"><value>Verifying the file</value><comment>job progress stage</comment></data>
</root>
+3 -1
View File
@@ -999,7 +999,7 @@
<data name="Tooltips.Editor.RenderMenu.Recommended" xml:space="preserve"><value>The advisor's pick for this sequence</value></data>
<data name="Tooltips.Editor.RenderMenu.Recent" xml:space="preserve"><value>A preset this sequence was rendered with</value></data>
<data name="Tooltips.Editor.RenderMenu.Other" xml:space="preserve"><value>Every other preset, by group</value></data>
<data name="Tooltips.Editor.RenderMenu.Preset" xml:space="preserve"><value>Render with {0}: {1}</value><comment>{0} preset name; {1} its size, codec and frame rate</comment></data>
<data name="Tooltips.Editor.RenderMenu.Preset" xml:space="preserve"><value>Use {0} for this export: {1}; clears the Encoding changes</value><comment>{0} preset name; {1} its size, codec and frame rate</comment></data>
<data name="Tooltips.Editor.RenderMenu.Batch" xml:space="preserve"><value>Render every preset of the batch, one job each</value></data>
<data name="Tooltips.Editor.RenderMenu.BatchEmpty" xml:space="preserve"><value>Tick presets in the Export step first</value></data>
<data name="Tooltips.Editor.RenderMenu.AddToQueue" xml:space="preserve"><value>Queue the render with the selected preset and keep editing</value></data>
@@ -1073,6 +1073,8 @@
<data name="Tooltips.Videos.HereAndServer" xml:space="preserve"><value>The same render is on this PC and on the server</value></data>
<data name="Tooltips.Videos.NotSent" xml:space="preserve"><value>Rendered in the workspace, not in the library yet</value></data>
<data name="Tooltips.Videos.Select" xml:space="preserve"><value>Select the video; Ctrl and Shift add to the selection</value></data>
<data name="Tooltips.Videos.SelectOne" xml:space="preserve"><value>Select one video only to do this</value></data>
<data name="Tooltips.Videos.ServerOnly" xml:space="preserve"><value>Only on the server: not on this PC</value></data>
<data name="Tooltips.Settings.VideosFolder" xml:space="preserve"><value>Where Copy to folder puts videos; not inside the archive or the workspace</value></data>
<data name="Tooltips.Settings.VideosBrowse" xml:space="preserve"><value>Choose the videos folder</value></data>
<data name="Tooltips.Settings.VideosOpen" xml:space="preserve"><value>Open the videos folder in Explorer</value></data>
+1 -2
View File
@@ -14,7 +14,7 @@
<data name="Videos.OpenInEdit" xml:space="preserve"><value>Open in Edit</value></data>
<data name="Videos.State.Here" xml:space="preserve"><value>Here</value></data>
<data name="Videos.State.OnServer" xml:space="preserve"><value>On server</value></data>
<data name="Videos.State.HereAndServer" xml:space="preserve"><value>Here and on server</value></data>
<data name="Videos.State.HereAndServer" xml:space="preserve"><value>Here + server</value></data>
<data name="Videos.State.Copied" xml:space="preserve"><value>Copied</value></data>
<data name="Videos.State.Missing" xml:space="preserve"><value>Missing</value></data>
<data name="Videos.State.NotSent" xml:space="preserve"><value>Not sent</value></data>
@@ -45,7 +45,6 @@
<data name="Videos.Column.Size" xml:space="preserve"><value>Size</value></data>
<data name="Videos.Column.Date" xml:space="preserve"><value>Date</value></data>
<data name="Videos.Column.State" xml:space="preserve"><value>State</value></data>
<data name="Videos.Details" xml:space="preserve"><value>{0}×{1} · {2} · {3} · {4}</value><comment>invariant: width, height, codec, duration, size</comment></data>
<data name="Videos.Player.CannotPlay" xml:space="preserve"><value>Cannot play here</value></data>
<data name="Videos.Player.Close" xml:space="preserve"><value>Close player</value></data>
<data name="Videos.Delete.Title" xml:space="preserve"><value>Delete videos</value></data>
+2
View File
@@ -1124,6 +1124,8 @@
<data name="Admin.Videos.Download" xml:space="preserve"><value>Scarica</value></data>
<data name="Admin.Videos.Download.Tip" xml:space="preserve"><value>Scarica il file</value></data>
<data name="Admin.Videos.Download.One.Tip" xml:space="preserve"><value>Seleziona un video per scaricarlo</value></data>
<data name="Admin.Videos.Download.Folder.Tip" xml:space="preserve"><value>Una sequenza di immagini è una cartella: copiala in una cartella</value></data>
<data name="Admin.Videos.Download.Missing.Tip" xml:space="preserve"><value>Il file manca sul server</value></data>
<data name="Admin.Videos.Copy" xml:space="preserve"><value>Copia in cartella</value></data>
<data name="Admin.Videos.Copy.Tip" xml:space="preserve"><value>Copia nella cartella video del server, verificata con l'hash; l'originale resta</value></data>
<data name="Admin.Videos.Copy.NoFolder.Tip" xml:space="preserve"><value>Imposta prima una cartella video nelle Impostazioni</value></data>
+5
View File
@@ -134,6 +134,11 @@
<data name="Export.Render.FadesShortened" xml:space="preserve"><value>Le dissolvenze superavano metà del video e sono state accorciate.</value></data>
<data name="Export.Render.DirectionUnknown" xml:space="preserve"><value>Direzione “{0}” sconosciuta; il video va avanti.</value></data>
<data name="Export.Render.BoomerangStack" xml:space="preserve"><value>Il boomerang non si renderizza con le scie stellari; il video va avanti.</value></data>
<data name="Export.Encoder.Ignored.RateControl" xml:space="preserve"><value>L’encoder ha ignorato il controllo bitrate; ha usato il suo.</value></data>
<data name="Export.Encoder.Ignored.Quality" xml:space="preserve"><value>L’encoder ha ignorato la qualità; ha usato la sua.</value></data>
<data name="Export.Encoder.Ignored.BitRate" xml:space="preserve"><value>L’encoder ha ignorato il bitrate; ha usato il suo.</value></data>
<data name="Export.Encoder.Ignored.KeyframeInterval" xml:space="preserve"><value>L’encoder ha ignorato l’intervallo dei keyframe; ha usato il suo.</value></data>
<data name="Export.Encoder.Ignored.BFrames" xml:space="preserve"><value>L’encoder ha ignorato i B-frame; ha usato i suoi.</value></data>
<data name="Export.Log.StillSaved" xml:space="preserve"><value>Fotogramma {0} salvato come {1}</value></data>
<data name="Export.Job.Verifying" xml:space="preserve"><value>Verifica del file</value></data>
</root>
+3 -1
View File
@@ -346,7 +346,7 @@
<data name="Tooltips.Editor.RenderMenu.Batch" xml:space="preserve"><value>Renderizza ogni preset della serie, un'attività ciascuno</value></data>
<data name="Tooltips.Editor.RenderMenu.BatchEmpty" xml:space="preserve"><value>Spunta prima dei preset nel passo Esporta</value></data>
<data name="Tooltips.Editor.RenderMenu.Other" xml:space="preserve"><value>Tutti gli altri preset, per gruppo</value></data>
<data name="Tooltips.Editor.RenderMenu.Preset" xml:space="preserve"><value>Renderizza con {0}: {1}</value></data>
<data name="Tooltips.Editor.RenderMenu.Preset" xml:space="preserve"><value>Usa {0} per questo export: {1}; azzera le modifiche di Codifica</value></data>
<data name="Tooltips.Editor.RenderMenu.Recent" xml:space="preserve"><value>Un preset già usato per questa sequenza</value></data>
<data name="Tooltips.Editor.RenderMenu.Recommended" xml:space="preserve"><value>La scelta del consulente per questa sequenza</value></data>
<data name="Tooltips.Editor.RenderMenu.SaveFormat" xml:space="preserve"><value>Salva il fotogramma sotto il cursore come {0} alle dimensioni di uscita</value></data>
@@ -1055,6 +1055,8 @@
<data name="Tooltips.Videos.Refresh" xml:space="preserve"><value>Rilegge i video di questo PC, del server e dello spazio di lavoro</value></data>
<data name="Tooltips.Videos.Search" xml:space="preserve"><value>Mostra i video il cui titolo, preset o nome del file contiene questo testo</value></data>
<data name="Tooltips.Videos.Select" xml:space="preserve"><value>Seleziona il video; Ctrl e Maiusc aggiungono alla selezione</value></data>
<data name="Tooltips.Videos.SelectOne" xml:space="preserve"><value>Seleziona un solo video per farlo</value></data>
<data name="Tooltips.Videos.ServerOnly" xml:space="preserve"><value>Solo sul server: non su questo PC</value></data>
<data name="Tooltips.Videos.ServerOffline" xml:space="preserve"><value>Non connesso a un server: sono elencati solo i video di questo PC</value></data>
<data name="Tooltips.Videos.ServerOld" xml:space="preserve"><value>Il Chronos del server non ha la libreria video; aggiornalo per vederne i video</value></data>
<data name="Tooltips.Videos.ShowInFolder" xml:space="preserve"><value>Mostra il file in Esplora file</value></data>
+1 -2
View File
@@ -14,7 +14,7 @@
<data name="Videos.OpenInEdit" xml:space="preserve"><value>Apri in Modifica</value></data>
<data name="Videos.State.Here" xml:space="preserve"><value>Qui</value></data>
<data name="Videos.State.OnServer" xml:space="preserve"><value>Sul server</value></data>
<data name="Videos.State.HereAndServer" xml:space="preserve"><value>Qui e sul server</value></data>
<data name="Videos.State.HereAndServer" xml:space="preserve"><value>Qui + server</value></data>
<data name="Videos.State.Copied" xml:space="preserve"><value>Copiato</value></data>
<data name="Videos.State.Missing" xml:space="preserve"><value>Mancante</value></data>
<data name="Videos.State.NotSent" xml:space="preserve"><value>Non inviato</value></data>
@@ -45,7 +45,6 @@
<data name="Videos.Column.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Videos.Column.Date" xml:space="preserve"><value>Data</value></data>
<data name="Videos.Column.State" xml:space="preserve"><value>Stato</value></data>
<data name="Videos.Details" xml:space="preserve"><value>{0}×{1} · {2} · {3} · {4}</value></data>
<data name="Videos.Player.CannotPlay" xml:space="preserve"><value>Non riproducibile qui</value></data>
<data name="Videos.Player.Close" xml:space="preserve"><value>Chiudi lettore</value></data>
<data name="Videos.Delete.Title" xml:space="preserve"><value>Elimina video</value></data>
+60 -25
View File
@@ -23,6 +23,41 @@
<Setter Property="MaxWidth" Value="170" />
<Setter Property="ItemTemplate" Value="{StaticResource Template.FilterOption}" />
</Style>
<!--
The list's preset, format and date columns: with the player open the list keeps the title, duration, size and state
(the player shows the rest), so the state stays in view beside the pane.
-->
<Style x:Key="Column.Preset" TargetType="ColumnDefinition">
<Setter Property="Width" Value="*" />
<Setter Property="MinWidth" Value="110" />
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Width" Value="0" />
<Setter Property="MinWidth" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Column.Format" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="MinWidth" Value="130" />
</Style>
<Style x:Key="Column.Date" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="Width" Value="130" />
<Setter Property="MinWidth" Value="0" />
</Style>
<Style x:Key="Text.CellDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Text.HeaderDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
@@ -35,21 +70,21 @@
-->
<ContextMenu x:Key="Menu.Video" x:Shared="False">
<MenuItem Header="{l:Loc Videos.Play}" Command="{Binding PlacementTarget.Tag.PlayCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding PlayToolTip}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuPlayToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.ShowInFolder}" Command="{Binding PlacementTarget.Tag.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.Copy}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.Copy}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuShowInFolderToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{Binding MenuCopyText}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.CopyOnServer}" Command="{Binding PlacementTarget.Tag.CopyOnServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.CopyOnServer}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyOnServerToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.OpenInEdit}" Command="{Binding PlacementTarget.Tag.OpenInEditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.OpenInEdit}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuOpenInEditToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Render.SendAgain}" Command="{Binding PlacementTarget.Tag.SendCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.WorkspaceRow}" ToolTipService.ShowOnDisabled="True"
Visibility="{Binding Entry.IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<Separator />
<MenuItem Header="{l:Loc Videos.Delete}" Command="{Binding PlacementTarget.Tag.DeleteCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.Delete}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuDeleteToolTip}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
<Style x:Key="ListBoxItem.VideoCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
@@ -141,10 +176,10 @@
ToolTip="{Binding PlayToolTip}" AutomationProperties.Name="{l:Loc Videos.Play}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}"
Command="{Binding DataContext.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" AutomationProperties.Name="{l:Loc Videos.ShowInFolder}" />
ToolTip="{Binding MenuShowInFolderToolTip}" AutomationProperties.Name="{l:Loc Videos.ShowInFolder}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.CopyToFolder}"
Command="{Binding DataContext.CopyCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Videos.Copy}" AutomationProperties.Name="{l:Loc Videos.Copy}" />
ToolTip="{Binding MenuCopyToolTip}" AutomationProperties.Name="{Binding MenuCopyText}" />
</StackPanel>
</v:SequenceCard.ActionsContent>
</v:SequenceCard>
@@ -162,20 +197,20 @@
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,6">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="*" MinWidth="130" />
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="130" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Format}" Margin="10,0,0,0" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Format}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Duration}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Size}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Date}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Date}" Margin="10,0,0,0" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.State}" Margin="16,0,0,0" />
</Grid>
</Border>
@@ -190,20 +225,20 @@
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
<Grid ToolTip="{Binding ToolTip}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="*" MinWidth="130" />
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="130" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding FormatText}" Margin="10,0,0,0" FlowDirection="LeftToRight" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.CellDetail}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.CellDetail}" Text="{Binding FormatText}" Margin="10,0,0,0" FlowDirection="LeftToRight" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding DurationText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellDetail}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<ItemsControl Grid.Column="6" Margin="16,0,0,0" ItemsSource="{Binding States}" ItemTemplate="{StaticResource Template.Status}"
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" ClipToBounds="True" />
</Grid>
@@ -235,10 +270,10 @@
<TextBlock Text="{Binding SelectionText}" FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,12,8" Typography.NumeralAlignment="Tabular" />
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="0,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.Play}" Command="{Binding PlayCommand}" ToolTip="{Binding PlayToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{Binding ShowInFolderToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{Binding CopyText}" Command="{Binding CopyCommand}" ToolTip="{Binding CopyToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.CopyOnServer}" Command="{Binding CopyOnServerCommand}" ToolTip="{Binding CopyOnServerToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.OpenInEdit}" Command="{Binding OpenInEditCommand}" ToolTip="{l:Loc Tooltips.Videos.OpenInEdit}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.OpenInEdit}" Command="{Binding OpenInEditCommand}" ToolTip="{Binding OpenInEditToolTip}" />
<Button Style="{StaticResource Button.Subtle}" Height="30" Margin="0,0,8,8" Content="{l:Loc Library.Action.ClearSelection}" Command="{Binding ClearSelectionCommand}"
ToolTip="{l:Loc Tooltips.Library.ClearSelection}" />
</WrapPanel>
+85 -12
View File
@@ -137,6 +137,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
if (!Set(ref _rows, value)) return;
foreach (var row in _rows)
{
row.Section = this;
row.SelectionChanged += OnSelectionChanged;
row.PosterRequested += OnPosterRequested;
}
@@ -308,7 +309,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
public ICommand PlayCommand { get; }
/// <summary>The toolbar's Play tooltip: why the selection does not play here, else what Play does.</summary>
public string PlayToolTip => SelectedRows is [var one] ? one.PlayToolTip : Loc.L("Tooltips.Videos.Play");
public string PlayToolTip => PlayToolTipOf(SelectedRows);
public ICommand ShowInFolderCommand { get; }
public ICommand CopyCommand { get; }
@@ -318,18 +319,62 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
public ICommand SendCommand { get; }
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string CopyText => SelectedRows is { Count: > 0 } rows && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
public string CopyText => CopyTextOf(SelectedRows);
public string CopyToolTip => CopyBlocker(SelectedRows) ?? (SelectedRows.All(r => !r.Entry.IsLocal) && SelectedRows.Count > 0
? Loc.L("Tooltips.Videos.Download")
: Loc.L("Tooltips.Videos.Copy"));
public string CopyToolTip => CopyToolTipOf(SelectedRows);
public string CopyOnServerToolTip => CopyOnServerBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows);
public string DeleteToolTip => DeleteBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.Delete");
public string DeleteToolTip => DeleteToolTipOf(SelectedRows);
/// <summary>Show in folder's tooltip: why it waits (more than one video, a server's video alone, a file gone), else what it does.</summary>
public string ShowInFolderToolTip => ShowInFolderToolTipOf(SelectedRows);
/// <summary>Open in Edit's tooltip: why it waits (more than one video, a server's video alone), else what it does.</summary>
public string OpenInEditToolTip => OpenInEditToolTipOf(SelectedRows);
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download");
public string RowCopyToolTip(VideoRowViewModel row) => CopyToolTipOf(Targets(row));
/// <summary>What the row's menu acts on: the selection when the row is part of it, else the row alone (as the commands do).</summary>
internal IReadOnlyList<VideoRowViewModel> TargetsOf(VideoRowViewModel row) => Targets(row);
internal static string PlayToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] => one.PlayToolTip,
{ Count: > 1 } => Loc.L("Tooltips.Videos.SelectOne"),
_ => Loc.L("Tooltips.Videos.Play"),
};
internal static string CopyTextOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows is { Count: > 0 } && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
internal string CopyToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
CopyBlocker(rows) ?? (rows.Count > 0 && rows.All(r => !r.Entry.IsLocal) ? Loc.L("Tooltips.Videos.Download") : Loc.L("Tooltips.Videos.Copy"));
internal string CopyOnServerToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => CopyOnServerBlocker(rows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
internal string DeleteToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => DeleteBlocker(rows) ?? Loc.L("Tooltips.Videos.Delete");
internal static string ShowInFolderToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[{ Entry.HasLocalFile: true }] or [] => Loc.L("Tooltips.Videos.ShowInFolder"),
[{ Entry.Missing: true }] => Loc.L("Tooltips.Videos.Missing"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
internal static string OpenInEditToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] when CanOpen(one.Entry) => Loc.L("Tooltips.Videos.OpenInEdit"),
[{ Entry.IsUnsent: true }] => Loc.L("Tooltips.Videos.WorkspaceRow"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
[] => Loc.L("Tooltips.Videos.OpenInEdit"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
public ICommand ClosePlayerCommand { get; }
@@ -360,9 +405,10 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var local = await localTask;
var (remote, state) = await serverTask;
var workspace = await workspaceTask;
var merged = await WithLocalCopiesAsync(VideoSources.Merge(local, remote, workspace));
if (load != _loads) return;
_server = state;
Entries = VideoSources.Merge(local, remote, workspace);
Entries = merged;
OnPropertyChanged(nameof(ServerState));
OnPropertyChanged(nameof(IsServerLimited));
OnPropertyChanged(nameof(ServerStatusText));
@@ -400,6 +446,27 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
}
}
/// <summary>The server's renders this PC downloaded, with their copies here (<see cref="VideoSources.WithLocalCopies"/>).</summary>
private async Task<IReadOnlyList<VideoEntry>> WithLocalCopiesAsync(IReadOnlyList<VideoEntry> entries)
{
List<Guid> serverOnly = [.. entries.Where(e => e.IsOnServer && !e.IsLocal && !e.IsUnsent).Select(e => e.Id)];
if (serverOnly.Count == 0 || LocalLibrary() is not { IsAvailable: true } library) return entries;
try
{
return await Task.Run(async () =>
{
var copies = await library.CopiesAsync(serverOnly);
var paths = copies.ToDictionary(c => c.Key, c => (IReadOnlyList<string>)[.. c.Value.Select(copy => copy.Path)]);
return VideoSources.WithLocalCopies(entries, paths, p => File.Exists(p) || Directory.Exists(p));
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("videos", "The copies of the server's videos on this PC could not be read", ex);
return entries;
}
}
private static async Task<(IReadOnlyList<VideoEntry> Entries, VideoServer State)> ReadServerAsync(VideoServer server)
{
if (server is not { State: VideoServerState.Available, Connect: { } connect }) return ([], server);
@@ -549,6 +616,10 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
OnPropertyChanged(nameof(CopyToolTip));
OnPropertyChanged(nameof(CopyOnServerToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(ShowInFolderToolTip));
OnPropertyChanged(nameof(OpenInEditToolTip));
// A row's menu acts on the selection it is part of: its words follow the selection too.
foreach (var each in _rows) each.RefreshMenu();
CommandManager.InvalidateRequerySuggested();
}
@@ -735,7 +806,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
using var remote = connect();
server = await remote.PlanDeleteAsync(serverIds);
}
plans = new VideoDeletePlans(local, server);
plans = new VideoDeletePlans(local, server, rows.DistinctBy(r => r.Entry.Id).ToDictionary(r => r.Entry.Id, r => VideoDeletePlans.NameOf(r.Entry)));
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
{
@@ -757,15 +828,17 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var deleted = 0;
try
{
// Each delete asks for exactly the ids that were planned, blocked ones included: its fingerprint covers them all, and
// what is blocked stays where it is.
if (plans.Local is { Items.Count: > 0 } localPlan)
{
var result = await Task.Run(() => library!.DeleteAsync([.. localPlan.Items.Select(i => i.Render.Id)], localPlan.Fingerprint, Environment.MachineName));
var result = await Task.Run(() => library!.DeleteAsync(localIds, localPlan.Fingerprint, Environment.MachineName));
deleted += result.Deleted.Count;
}
if (plans.Server is { Items.Count: > 0 } serverPlan && _server.Connect is { } connect)
{
using var remote = connect();
var result = await remote.DeleteAsync([.. serverPlan.Items.Select(i => i.Id)], serverPlan.Fingerprint);
var result = await remote.DeleteAsync(serverIds, serverPlan.Fingerprint);
deleted += result.Items.Count;
}
Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted)));
+50 -6
View File
@@ -42,12 +42,11 @@ public static class VideoText
return size.Length == 0 ? codec : codec.Length == 0 ? size : size + Loc.Separator + codec;
}
/// <summary>"3840×2160 · HEVC · 0:42 · 1.2 GB" (<c>Videos.Details</c>).</summary>
/// <summary>"3840×2160 · HEVC · 0:42 · 1.2 GB": the parts a render has (a still has no duration), joined by the separator.</summary>
public static string Details(VideoEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return Loc.L("Videos.Details", entry.Width.ToString(CultureInfo.InvariantCulture), entry.Height.ToString(CultureInfo.InvariantCulture),
VideoSources.CodecText(entry.Codec), Duration(entry), Formatting.Bytes(entry.Bytes));
return string.Join(Loc.Separator, new[] { Format(entry), Duration(entry), Formatting.Bytes(entry.Bytes) }.Where(p => p.Length > 0));
}
/// <summary>The state chips of a render: where its file is, whether it was copied, and a missing file.</summary>
@@ -137,6 +136,39 @@ public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
/// </summary>
public string PlayToolTip => VideoText.PlayToolTip(Entry);
/// <summary>The section listing the row: its menu's words are those of the commands it runs, on what they act on.</summary>
internal Sections.VideosViewModel? Section { get; set; }
private IReadOnlyList<VideoRowViewModel> MenuTargets => Section?.TargetsOf(this) ?? [this];
/// <summary>The menu's Play tooltip: why it waits, else what it does.</summary>
public string MenuPlayToolTip => Sections.VideosViewModel.PlayToolTipOf(MenuTargets);
public string MenuShowInFolderToolTip => Sections.VideosViewModel.ShowInFolderToolTipOf(MenuTargets);
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string MenuCopyText => Sections.VideosViewModel.CopyTextOf(MenuTargets);
public string MenuCopyToolTip => Section?.CopyToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.Copy");
public string MenuCopyOnServerToolTip => Section?.CopyOnServerToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.CopyOnServer");
public string MenuOpenInEditToolTip => Sections.VideosViewModel.OpenInEditToolTipOf(MenuTargets);
public string MenuDeleteToolTip => Section?.DeleteToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.Delete");
/// <summary>The selection or the section's state changed: the menu's words are read again.</summary>
internal void RefreshMenu()
{
OnPropertyChanged(nameof(MenuPlayToolTip));
OnPropertyChanged(nameof(MenuShowInFolderToolTip));
OnPropertyChanged(nameof(MenuCopyText));
OnPropertyChanged(nameof(MenuCopyToolTip));
OnPropertyChanged(nameof(MenuCopyOnServerToolTip));
OnPropertyChanged(nameof(MenuOpenInEditToolTip));
OnPropertyChanged(nameof(MenuDeleteToolTip));
}
/// <summary>The file name, left to right in every language.</summary>
public string FileNameText => Formatting.LeftToRight(Entry.FileName);
@@ -174,8 +206,17 @@ public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
/// many bytes), the renders whose file is missing (only their entry goes), the renders left where they are and why, and
/// that copies in the videos folder stay. This PC's renders and the server's are planned apart and confirmed together.
/// </summary>
public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server)
/// <param name="Names">What the section shows of each selected render ("title · file"), which names a render that stays
/// (the server's plan gives only its id); a render not among them is named by its id.</param>
public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server, IReadOnlyDictionary<Guid, string>? Names = null)
{
/// <summary>"Harbour sunset · harbour-4k.mp4": how a render that stays is named in the confirmation.</summary>
public static string NameOf(VideoEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return entry.Title + Loc.Separator + Formatting.LeftToRight(entry.FileName);
}
/// <summary>The renders that go.</summary>
public int Count => (Local?.Items.Count ?? 0) + (Server?.Items.Count ?? 0);
@@ -200,14 +241,17 @@ public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto
missing ? Loc.L("Videos.State.Missing") : Formatting.Bytes(bytes)));
}
if (goes.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", goes.Count - DeletePlans.ListedLines));
var stays = (Local?.Blocked.Select(b => (b.Video?.SequenceTitle ?? b.RenderId.ToString("D"), b.Reason)) ?? [])
.Concat(Server?.Blocked.Select(b => (b.Id.ToString("D"), b.Reason)) ?? []).ToList();
var stays = (Local?.Blocked.Select(b => (Named(b.RenderId, b.Video is { } video ? video.SequenceTitle + Loc.Separator + Formatting.LeftToRight(video.FileName) : null), b.Reason)) ?? [])
.Concat(Server?.Blocked.Select(b => (Named(b.Id, null), b.Reason)) ?? []).ToList();
if (stays.Count > 0) lines.Add(Loc.L("Videos.Delete.Blocked", Formatting.Count(stays.Count)));
foreach (var (name, reason) in stays.Take(DeletePlans.ListedLines)) lines.Add(name + Loc.Separator + VideoText.BlockReason(reason));
if (stays.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", stays.Count - DeletePlans.ListedLines));
return lines;
}
/// <summary>The render's name in the section, else <paramref name="fallback"/>, else its id.</summary>
private string Named(Guid id, string? fallback) => Names?.GetValueOrDefault(id) ?? fallback ?? id.ToString("D");
/// <summary>The confirmation of moving the planned renders into the trash; null when nothing would go.</summary>
public ConfirmRequest? Request()
{
+24 -1
View File
@@ -308,7 +308,7 @@ public static class VideoSources
DurationSeconds = render.DurationSeconds,
Bytes = render.Size,
Created = render.Rendered,
Kind = RenderKind.Of(null, render.Codec),
Kind = RenderKind.Of(null, render.Codec, render.Fps, render.DurationSeconds),
FileName = Path.GetFileName(path.TrimEnd('/', '\\')),
LocalPath = path,
IsUnsent = true,
@@ -353,6 +353,29 @@ public static class VideoSources
return [.. order.Select(id => merged[id])];
}
/// <summary>
/// The renders the server alone holds that this PC downloaded (a verified copy in its videos folder, <paramref name="copies"/>
/// by render id): the copies listed with theirs ("Copied"), and the first one still on disk (<paramref name="exists"/>)
/// as the file Play and Show in folder use here. Every other entry as it is.
/// </summary>
public static IReadOnlyList<VideoEntry> WithLocalCopies(IReadOnlyList<VideoEntry> entries, IReadOnlyDictionary<Guid, IReadOnlyList<string>> copies,
Func<string, bool> exists)
{
ArgumentNullException.ThrowIfNull(entries);
ArgumentNullException.ThrowIfNull(copies);
ArgumentNullException.ThrowIfNull(exists);
return
[
.. entries.Select(e => !e.IsLocal && !e.IsUnsent && e.LocalPath is null && copies.TryGetValue(e.Id, out var paths) && paths.Count > 0
? e with
{
LocalPath = paths.FirstOrDefault(exists),
Copies = [.. e.Copies.Concat(paths).Distinct(StringComparer.OrdinalIgnoreCase)],
}
: e),
];
}
/// <summary>Every render of this PC's index (<see cref="MaxPages"/> pages at most); none while the library is not there.</summary>
public static async Task<IReadOnlyList<VideoEntry>> ReadLocalAsync(IVideoLibrary? library, CancellationToken cancellationToken = default)
{
@@ -33,6 +33,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
private readonly Dictionary<long, long> _ticksByHns = [];
private readonly Dictionary<long, long> _durationByTicks = [];
private readonly Queue<long> _inputStarts = new();
private readonly List<EncoderSetting> _ignored = [];
private bool _providesSamples;
private uint _outputBufferSize;
private int _needInput;
@@ -58,6 +59,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
if (UnlockAsync(transform))
_events = transform as IMFMediaEventGenerator ?? throw new NotSupportedException("Asynchronous MFT without an event generator");
if (transform as ICodecAPI is { } codecApi) ApplyCodecSettings(codecApi);
else _ignored.AddRange(Asked());
SetOutputType();
SetInputType();
ReadOutputStreamInfo();
@@ -157,7 +159,8 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
_muxer.Complete();
_file.Flush(flushToDisk: true);
_file.Dispose();
AtomicFile.Commit(_tempPath, _settings.OutputPath);
// The render picked a free name: something that took it meanwhile (a restore) is never overwritten.
AtomicFile.CommitNew(_tempPath, _settings.OutputPath);
_completed = true;
Log.Info(LogCategory, $"\"{EncoderName}\" encoded {_framesIn} frames into {_framesOut} samples: {_settings.OutputPath}");
}
@@ -208,27 +211,51 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
RateControl.Quality => MfNative.RateControlQuality,
_ => MfNative.RateControlUnconstrainedVbr,
};
SetCodecValue(api, MfGuids.CodecRateControlMode, ComVariant.Create(mode), "RateControlMode");
var asked = Asked().ToHashSet();
void Set(in Guid property, ComVariant value, string name, EncoderSetting setting)
{
if (!SetCodecValue(api, property, value, name) && asked.Contains(setting) && !_ignored.Contains(setting)) _ignored.Add(setting);
}
Set(MfGuids.CodecRateControlMode, ComVariant.Create(mode), "RateControlMode", EncoderSetting.RateControl);
if (_settings.RateControl == RateControl.Quality)
SetCodecValue(api, MfGuids.CodecQuality, ComVariant.Create((uint)Math.Clamp(_settings.Quality, 1, 100)), "Quality");
Set(MfGuids.CodecQuality, ComVariant.Create((uint)Math.Clamp(_settings.Quality, 1, 100)), "Quality", EncoderSetting.Quality);
else
SetCodecValue(api, MfGuids.CodecMeanBitRate, ComVariant.Create(BitRate), "MeanBitRate");
Set(MfGuids.CodecMeanBitRate, ComVariant.Create(BitRate), "MeanBitRate", EncoderSetting.BitRate);
var gop = _settings.GopLength > 0 ? _settings.GopLength : (int)Math.Max(1, Math.Round(_settings.FrameRate.Value));
SetCodecValue(api, MfGuids.CodecGopSize, ComVariant.Create((uint)gop), "GOPSize");
Set(MfGuids.CodecGopSize, ComVariant.Create((uint)gop), "GOPSize", EncoderSetting.KeyframeInterval);
var bFrames = _settings.Profile == CodecProfile.H264Baseline ? 0 : Math.Max(0, _settings.BFrames);
SetCodecValue(api, MfGuids.CodecBPictureCount, ComVariant.Create((uint)bFrames), "BPictureCount");
Set(MfGuids.CodecBPictureCount, ComVariant.Create((uint)bFrames), "BPictureCount", EncoderSetting.BFrames);
SetCodecValue(api, MfGuids.CodecLowLatencyMode, ComVariant.Create(false), "LowLatencyMode");
}
private static unsafe void SetCodecValue(ICodecAPI api, in Guid property, ComVariant value, string name)
/// <inheritdoc />
public IReadOnlyList<EncoderSetting> Ignored => _ignored;
/// <summary>
/// The settings that name a value of their own rather than the encoder's default, whose refusal the render reports: a rate
/// control other than VBR, its quality, a bit rate given, a keyframe interval given, a B-frame count other than the default.
/// </summary>
private IEnumerable<EncoderSetting> Asked()
{
if (_settings.RateControl != RateControl.Vbr) yield return EncoderSetting.RateControl;
if (_settings.RateControl == RateControl.Quality) yield return EncoderSetting.Quality;
else if (_settings.BitRate > 0) yield return EncoderSetting.BitRate;
if (_settings.GopLength > 0) yield return EncoderSetting.KeyframeInterval;
if (_settings.Profile != CodecProfile.H264Baseline && _settings.BFrames != EncodeSettings.DefaultBFrames) yield return EncoderSetting.BFrames;
}
/// <summary>Sets an ICodecAPI property; false (logged) when the encoder does not support it or refuses the value.</summary>
private static unsafe bool SetCodecValue(ICodecAPI api, in Guid property, ComVariant value, string name)
{
if (api.IsSupported(property) != 0)
{
Log.Debug(LogCategory, $"ICodecAPI {name} not supported by the encoder");
return;
return false;
}
var hr = api.SetValue(property, (nint)(&value));
if (hr < 0) Log.Debug(LogCategory, $"ICodecAPI {name} rejected (0x{hr:X8})");
return hr >= 0;
}
/// <summary>Requested bit rate, or the preset density (§11.4: 0.10/0.07/0.05 bits per pixel per frame) when unset.</summary>
+12
View File
@@ -93,6 +93,18 @@ public static class AtomicFile
Replace(tempPath, path);
}
/// <summary>
/// Commits an already-written temporary file as <paramref name="path"/>, which must not exist: an output whose free name
/// something else took meanwhile (a restore, another program) is never overwritten.
/// </summary>
/// <exception cref="IOException"><paramref name="path"/> exists (the temporary file stays for the caller to discard).</exception>
public static void CommitNew(string tempPath, string path)
{
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
fs.Flush(flushToDisk: true);
File.Move(tempPath, path, overwrite: false);
}
public static string TempPathFor(string path)
{
var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? ".";
+13 -2
View File
@@ -201,11 +201,22 @@ public static class RenderKind
: codec is { } c && c.EndsWith("sequence", StringComparison.OrdinalIgnoreCase) ? Sequence
: Video;
/// <inheritdoc cref="Of(string?, string?)"/>
/// <summary>
/// <see cref="Of(string?, string?)"/>, telling a still apart when its kind was lost (one uploaded to a server of before
/// phase 5, which does not record it): an image-sequence codec with fps 0 and duration 0, which every still records and
/// no image sequence has.
/// </summary>
public static string Of(string? kind, string? codec, double fps, double durationSeconds)
{
var of = Of(kind, codec);
return of == Sequence && fps <= 0 && durationSeconds <= 0 ? Still : of;
}
/// <inheritdoc cref="Of(string?, string?, double, double)"/>
public static string Of(Render render)
{
ArgumentNullException.ThrowIfNull(render);
return Of(render.Kind, render.Codec);
return Of(render.Kind, render.Codec, render.Fps, render.DurationSeconds);
}
}
+8 -6
View File
@@ -11,7 +11,9 @@ namespace Chronos.Core.Render;
/// <param name="Gain">The linear-light multiplier of the fade to and from black, applied after the look and the knee
/// (<c>FrameFinish</c>): 1 leaves the frame as it is, 0 is black. Already in linear light (the sRGB ramp converted), so a
/// fade looks even.</param>
public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, double Gain);
/// <param name="Pass">The pass of the playback it belongs to (0 for the first; each loop is one more): a star-trail stack
/// starts again at each pass, so every loop plays the trails growing.</param>
public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, double Gain, int Pass = 0);
/// <summary>
/// The output program of a render (owner review 1, R8): the plan's frames in the order and for the time they are emitted,
@@ -87,15 +89,15 @@ public sealed class OutputProgram
switch (direction)
{
case PlaybackDirection.Reverse:
for (var i = frames.Count - 1; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = frames.Count - 1; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
case PlaybackDirection.Boomerang:
// The turning frame plays once, and a later pass starts after the first frame the previous one ended on.
for (var i = pass == 0 ? 0 : 1; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = pass == 0 ? 0 : 1; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
default:
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
}
}
@@ -148,7 +150,7 @@ public sealed class OutputProgram
{
var boundary = (long)double.Round((double)entry.Duration90k * part / parts);
if (boundary == previous) continue;
faded.Add(new ProgramEntry(entry.PlanIndex, boundary - previous, Gain(start + previous, start + boundary, total, fadeIn, fadeOut)));
faded.Add(entry with { Duration90k = boundary - previous, Gain = Gain(start + previous, start + boundary, total, fadeIn, fadeOut) });
previous = boundary;
}
start = end;
+33 -11
View File
@@ -100,6 +100,9 @@ internal sealed class RenderRun : IDisposable
/// <summary>Largest speed (source frames per output period) that scales motion blur; faster plans blur no further.</summary>
private const double MaxBlurSpeed = 4;
/// <summary>Warning key prefix of a setting the encoder refused (<see cref="IVideoEncoderSession.Ignored"/>), followed by its <see cref="EncoderSetting"/>.</summary>
internal const string IgnoredWarningPrefix = "Export.Encoder.Ignored.";
private readonly RenderInput _input;
private readonly RenderCorrections _corrections;
private readonly RenderSetup _setup;
@@ -157,12 +160,14 @@ internal sealed class RenderRun : IDisposable
else
Log.Info(RenderPipeline.LogCategory, $"Rendering {_program.Count} frames of a {_plan.Frames.Count}-frame plan ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
var session = _session = _setup.Encoder.Open();
IReadOnlyList<EncoderSetting> ignored;
try
{
await RenderFramesAsync(cancellationToken).ConfigureAwait(false);
await FlushEncodingAsync().ConfigureAwait(false);
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _program.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
session.Complete();
ignored = [.. session.Ignored];
}
catch
{
@@ -177,6 +182,8 @@ internal sealed class RenderRun : IDisposable
var warnings = new List<RenderWarning>(_setup.Warnings);
warnings.AddRange(_corrections.Report.Warnings);
warnings.AddRange(_warnings);
// What the encoder did not take: the output was encoded with its own value, which the job's log says.
warnings.AddRange(ignored.Select(s => new RenderWarning(IgnoredWarningPrefix + s)));
var result = new RenderResult
{
OutputPath = settings.OutputPath,
@@ -221,28 +228,42 @@ internal sealed class RenderRun : IDisposable
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
break;
case StackSetting.StarTrails:
// The trails accumulate in program order: a reversed video grows its trails from the end.
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
// The trails accumulate in program order: a reversed video grows its trails from the end, and each loop grows
// them again from nothing (a stacker carried over would freeze on the trails the first pass finished).
var decay = StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity);
StarTrailStacker? trails = null;
var pass = -1;
try
{
await RenderProgramAsync(async (index, token) =>
await RenderProgramAsync(async (entry, token) =>
{
using (var frame = await RenderFrameAsync(_plan.Frames[index], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
if (entry.Pass != pass || trails is null)
{
trails?.Dispose();
trails = new StarTrailStacker(decay);
pass = entry.Pass;
}
using (var frame = await RenderFrameAsync(_plan.Frames[entry.PlanIndex], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
return trails.Result!.Clone();
}, cancellationToken).ConfigureAwait(false);
}
finally
{
trails?.Dispose();
}
break;
default:
await RenderProgramAsync((index, token) => RenderFrameAsync(_plan.Frames[index], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
await RenderProgramAsync((entry, token) => RenderFrameAsync(_plan.Frames[entry.PlanIndex], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
break;
}
}
/// <summary>
/// Emits the program's entries in order, each rendered by <paramref name="render"/> from its plan index. Consecutive
/// entries of one plan frame (a held frame split over the periods of a fade) share one rendering, so a stack folds it
/// in once; every other entry is rendered again (a boomerang's way back, each loop).
/// entries of one plan frame and one pass (a held frame split over the periods of a fade) share one rendering, so a
/// stack folds it in once; every other entry is rendered again (a boomerang's way back, each loop).
/// </summary>
private async Task RenderProgramAsync(Func<int, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
private async Task RenderProgramAsync(Func<ProgramEntry, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
{
var entries = _program.Entries;
ImageBuffer? kept = null;
@@ -252,9 +273,9 @@ internal sealed class RenderRun : IDisposable
{
cancellationToken.ThrowIfCancellationRequested();
var entry = entries[i];
var frame = kept ?? await render(entry.PlanIndex, cancellationToken).ConfigureAwait(false);
var frame = kept ?? await render(entry, cancellationToken).ConfigureAwait(false);
kept = null;
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex)
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex && entries[i + 1].Pass == entry.Pass)
{
try
{
@@ -290,8 +311,9 @@ internal sealed class RenderRun : IDisposable
// Plan indices in the stacker, oldest (the next evicted) first.
var held = new List<int>(window + 1);
var previous = -1;
await RenderProgramAsync(async (index, token) =>
await RenderProgramAsync(async (entry, token) =>
{
var index = entry.PlanIndex;
var hi = int.Min(index + half, last);
var lo = int.Max(0, hi - window + 1);
await WindowAsync(stacker, held, lo, hi, index >= previous, token).ConfigureAwait(false);
+21 -1
View File
@@ -102,7 +102,11 @@ public sealed record EncodeSettings
/// <summary>Distance between key frames in frames; 0 = encoder default (≈ 1 s).</summary>
public int GopLength { get; init; }
public int BFrames { get; init; } = 2;
public int BFrames { get; init; } = DefaultBFrames;
/// <summary>The B-frames an encode asks for unless told otherwise.</summary>
public const int DefaultBFrames = 2;
public bool PreferHardware { get; init; } = true;
/// <summary>Optional specific encoder name from <see cref="EncoderCapability.Name"/>.</summary>
@@ -128,6 +132,22 @@ public interface IVideoEncoderSession : IDisposable
/// <summary>Flushes and closes the output. Without it, <see cref="IDisposable.Dispose"/> deletes the partial file.</summary>
void Complete();
/// <summary>
/// The settings asked for that the encoder does not support or refused, so the output was encoded with its own instead;
/// empty when it took every one (the managed encoders, which have none of them to refuse).
/// </summary>
IReadOnlyList<EncoderSetting> Ignored => [];
}
/// <summary>An encoding setting an encoder may refuse (<see cref="IVideoEncoderSession.Ignored"/>).</summary>
public enum EncoderSetting
{
RateControl,
Quality,
BitRate,
KeyframeInterval,
BFrames,
}
/// <summary>A family of encoders (Media Foundation on Windows, managed everywhere).</summary>
@@ -108,7 +108,8 @@ internal abstract class SingleFileSession : ManagedSession
Finish();
File.Flush(flushToDisk: true);
File.Dispose();
AtomicFile.Commit(_tempPath, Settings.OutputPath);
// The render picked a free name: something that took it meanwhile (a restore) is never overwritten.
AtomicFile.CommitNew(_tempPath, Settings.OutputPath);
}
protected override void Discard()
+13 -5
View File
@@ -153,12 +153,19 @@ public static class ProcessingJobs
{
Width = width,
Height = height,
// The job's own export (playback included) is what renders, not the export the settings carry.
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat,
RequiredFormat(settings with { Export = ReadExport(parameters.PresetJson) }, resolved, sourceWidth, sourceHeight)),
// The job's own export (playback included) is what renders, not the export the settings carry; but a node parses
// the settings text as it is, so never less than the format that text is written in.
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, int.Max(TextFormat(settings),
RequiredFormat(settings with { Export = ReadExport(parameters.PresetJson) }, resolved, sourceWidth, sourceHeight))),
};
}
/// <summary>
/// The format of the settings text a node parses: the version it was read with, or the one <see cref="ProjectSettings.ToJson"/>
/// writes for it. A node that reads less refuses that text, whatever export the job renders.
/// </summary>
private static int TextFormat(ProjectSettings settings) => int.Max(settings.Version, settings.WrittenFormat);
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> and each of its batch
/// presets needs (the highest <see cref="RenderRules.RequiredFormat"/> of them): what a server or a render node must read
@@ -227,10 +234,11 @@ public static class ProcessingJobs
settings ??= ReadSettings(settingsJson);
var (width, height) = (settings is null ? null : Size(settings, resolved, sourceWidth, sourceHeight))
?? (resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight);
// The format of what renders: the settings with this export in place of their own (its playback raises it to 3).
// The format of what renders: the settings with this export in place of their own (its playback raises it to 3), and
// never less than the format of the settings text the node parses.
var format = settings is null
? new ProjectSettings { Export = export }.RequiredFormat
: RequiredFormat(settings with { Export = export }, resolved, sourceWidth, sourceHeight);
: int.Max(TextFormat(settings), RequiredFormat(settings with { Export = export }, resolved, sourceWidth, sourceHeight));
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
width, height, useProxies, settingsJson, RequiredSettingsFormat: format);
}
@@ -183,8 +183,9 @@ internal sealed class SequenceRender : IAsyncDisposable
/// <summary>
/// The frame a still job saves (<see cref="Protocol.RenderJobParameters.StillFrame"/>, <see cref="Protocol.RenderJobParameters.StillPhoto"/>):
/// the frame holding the photo when its SHA-256 is given and found (the frames may have moved since), else the index;
/// null when neither names a frame of the sequence.
/// the frame holding the photo when its SHA-256 is given (the frames may have moved since), null when that photo is no
/// longer in the sequence (the index would name another photo now); without a hash (a photo not hashed yet) the index.
/// Null when neither names a frame of the sequence.
/// </summary>
public static int? StillIndex(SequenceFrames frames, int? frameIndex, string? photoSha256)
{
@@ -195,6 +196,7 @@ internal sealed class SequenceRender : IAsyncDisposable
{
if (string.Equals(frames.Frames[i].Sha256, sha, StringComparison.OrdinalIgnoreCase)) return i;
}
return null;
}
return frameIndex is { } index && (uint)index < (uint)frames.Frames.Count ? index : null;
}
@@ -180,17 +180,22 @@ public sealed class RenderRepository
var from = new DateTimeOffset(year, 1, 1, 0, 0, 0, TimeSpan.Zero);
where.Add($"r.created >= {p.Add(from)} AND r.created < {p.Add(from.AddYears(1))}");
}
// A sequence's codec names end in "sequence" (pngsequence, tiff16sequence…).
const string Sequence = "(r.kind IS NULL AND lower(coalesce(r.codec, '')) LIKE '%sequence')";
// A sequence's codec names end in "sequence" (pngsequence, tiff16sequence…). A still whose kind was lost (uploaded to
// a server of before phase 5) has such a codec with fps 0 and duration 0, as RenderKind.Of tells it apart.
const string ImageCodec = "lower(coalesce(r.codec, '')) LIKE '%sequence'";
const string KindlessStill = $"(r.kind IS NULL AND {ImageCodec} AND coalesce(r.fps, 0) <= 0 AND coalesce(r.duration_seconds, 0) <= 0)";
switch (query.Kind?.Trim().ToLowerInvariant())
{
case null or "":
break;
case RenderKind.Video:
where.Add($"(r.kind IS NULL AND NOT {Sequence})");
where.Add($"(r.kind IS NULL AND NOT {ImageCodec})");
break;
case RenderKind.Sequence:
where.Add(Sequence);
where.Add($"(r.kind IS NULL AND {ImageCodec} AND NOT {KindlessStill})");
break;
case RenderKind.Still:
where.Add($"(r.kind = {p.Add(RenderKind.Still)} OR {KindlessStill})");
break;
case var kind:
where.Add($"r.kind = {p.Add(kind)}");
+7
View File
@@ -230,6 +230,13 @@ public interface IVideoLibrary
/// <summary>One render; null when the index has no such render.</summary>
Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default);
/// <summary>
/// The verified copies this host made of <paramref name="renderIds"/>, renders of its index or not (a server's render
/// downloaded into the videos folder); none for a render it never copied.
/// </summary>
Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>>(new Dictionary<Guid, IReadOnlyList<RenderCopy>>());
/// <summary>The dry run of deleting <paramref name="renderIds"/> into the trash; nothing moves.</summary>
Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default);
@@ -154,19 +154,20 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra
await VideoTrash.CopyFileAsync(source.Path!, part, ct).ConfigureAwait(false);
sha = await Verified(part, source.Sha256, context, ct).ConfigureAwait(false);
}
if (sha is null)
{
Mismatch(context, source, part);
return false;
}
// Inside the try: a rename the folder refuses (an antivirus, a permission changed) leaves no part copy behind.
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
return true;
}
catch
{
Remove(part);
throw;
}
if (sha is null)
{
Mismatch(context, source, part);
return false;
}
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
return true;
}
/// <summary>The copy takes its name (never overwriting: another free name when one appeared meanwhile) and is recorded.</summary>
+6
View File
@@ -57,6 +57,12 @@ public sealed class VideoLibrary : IVideoLibrary
? (await ItemsAsync([render], cancellationToken).ConfigureAwait(false)).FirstOrDefault()
: null;
public Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(renderIds);
return _db.RenderCopies.ListByRendersAsync(renderIds, cancellationToken);
}
public async Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(renderIds);
+207 -41
View File
@@ -6,6 +6,7 @@ using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
namespace Chronos.Data.Videos;
@@ -40,6 +41,12 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
private const string PartSuffix = ".part";
/// <summary>
/// The suffix of a marker next to an entry's folder naming a source a copy could not remove after it verified (a file
/// held open): settled by <see cref="RecoverAsync"/>.
/// </summary>
internal const string LeftoverSuffix = ".leftover";
/// <summary>Tests: move as if the trash were on another volume (copy, verify, delete).</summary>
internal bool ForceCopy { get; set; }
@@ -105,9 +112,15 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
long bytes;
if (isFile)
{
// Hashed now when it never was (a render of before migration 0010), and remembered.
sha = row.Sha256 ?? await ContentHash.Sha256Async(source, cancellationToken: cancellationToken).ConfigureAwait(false);
if (row.Sha256 is null) await db.Renders.SetSha256Async(row.Id, sha, CancellationToken.None).ConfigureAwait(false);
// Hashed now, under the lease, whatever the row says: the record keeps the bytes that go into the trash, which a
// restore checks. A file changed in place since it was recorded (or never hashed, before migration 0010) has its
// row brought up to date, so it is never trashed under a hash it can no longer be restored against.
sha = await ContentHash.Sha256Async(source, cancellationToken: cancellationToken).ConfigureAwait(false);
if (!string.Equals(sha, row.Sha256, StringComparison.OrdinalIgnoreCase))
{
if (row.Sha256 is not null) Log.Warning("videos", $"{source} changed since it was recorded; it goes to the trash as it is now");
await db.Renders.SetSha256Async(row.Id, sha, CancellationToken.None).ConfigureAwait(false);
}
bytes = new FileInfo(source).Length;
}
else
@@ -129,20 +142,24 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
// The journal first: a crash from here on is settled by RecoverAsync.
AtomicFile.WriteAllText(recordPath + PendingSuffix, JsonSerializer.Serialize(record, VideoTrashJson.Default.VideoTrashRecord));
var target = Path.Combine(entryFolder, fileName);
bool removed;
try
{
await MoveAsync(source, target, record, cancellationToken).ConfigureAwait(false);
removed = await MoveAsync(source, target, record, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// A file is open elsewhere, the copy did not verify, or the move was cancelled: the render stays where it was.
// A file is open elsewhere, the copy did not verify, or the move was cancelled before the verified copy took
// its name in the trash: nothing moved, the render stays where it was.
Log.Warning("videos", $"{source} could not move to the trash; it stays where it is", ex);
Undo(target, entryFolder, recordPath);
throw;
}
if (CrashAfterMove) throw new IOException("Simulated crash after the move.");
// The file has moved: its row goes too, to the end, whatever the caller cancels meanwhile.
// The file is in the trash (verified, when copied): the delete is done, its row goes too, to the end, whatever
// the caller cancels meanwhile. A source a copy could not remove stays whole and is left for RecoverAsync.
await db.Renders.DeleteAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
if (!removed) MarkLeftover(entryFolder, source);
Publish(recordPath);
}
Log.Info("videos", $"{source} moved to the trash ({name}, {bytes} bytes)");
@@ -179,12 +196,19 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
if (!await MatchesAsync(trashed, record, cancellationToken).ConfigureAwait(false))
throw new VideoLibraryException(VideoErrors.HashMismatch, Loc.L("Errors.Videos.TrashMismatch"));
Render restored;
bool removed;
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var target = Destination(paths, record, sequence);
// The original this entry's delete could not remove goes first (still what went into the trash), so the
// render takes its own name back.
await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false);
// A name a render of this process is writing counts as taken, and stays reserved until the move is done: the
// render's commit would otherwise land on the restored file (and commits never overwrite, for other processes).
using var names = new OutputNames();
var target = names.Reserve(taken => Destination(paths, record, sequence, taken));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
cancellationToken.ThrowIfCancellationRequested();
await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
removed = await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
restored = record.Render with { SequenceId = sequence.Id, OutputPath = Stored(paths, target), Sha256 = record.Sha256 };
try
{
@@ -193,12 +217,17 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
catch (Exception ex)
{
Log.Warning("videos", $"{target} could not be indexed again; it goes back into the trash", ex);
await MoveAsync(target, trashed, record, CancellationToken.None).ConfigureAwait(false);
// A copy that could not remove the trashed one left it whole: the copy alone goes.
if (!removed) RemoveSource(target);
else if (!await MoveAsync(target, trashed, record, CancellationToken.None).ConfigureAwait(false))
Log.Warning("videos", $"{target} went back into the trash but is left over where it was restored to");
throw;
}
}
// The render is back: its trash copy goes (left for RecoverAsync when a copy could not remove it), then its record.
if (!removed) MarkLeftover(entryFolder, trashed);
File.Delete(recordPath);
RemoveEmpty(entryFolder);
if (removed) RemoveEmpty(entryFolder);
Log.Info("videos", $"{name} restored to {restored.OutputPath}");
return restored;
}
@@ -234,11 +263,21 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
{
// The file reached the trash (a copy only takes its name once verified): the delete completes. A source still
// there is the original a copy left behind, unless something new took its name since.
if ((File.Exists(record.OriginalPath) || System.IO.Directory.Exists(record.OriginalPath))
&& await MatchesAsync(record.OriginalPath, record, cancellationToken).ConfigureAwait(false))
DeletePath(record.OriginalPath);
if (await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null)
await db.Renders.DeleteAsync(record.Render.Id, CancellationToken.None).ConfigureAwait(false);
if ((File.Exists(record.OriginalPath) || System.IO.Directory.Exists(record.OriginalPath))
&& await MatchesAsync(record.OriginalPath, record, cancellationToken).ConfigureAwait(false))
{
try
{
RemoveSource(record.OriginalPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{record.OriginalPath} is still in use; it is removed at the next start", ex);
MarkLeftover(entryFolder, record.OriginalPath);
}
}
Publish(recordPath);
Log.Info("videos", $"An interrupted delete of {record.OriginalPath} completed");
}
@@ -251,9 +290,82 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
settled++;
}
}
foreach (var marker in System.IO.Directory.EnumerateFiles(folder, "*" + LeftoverSuffix).ToList())
{
cancellationToken.ThrowIfCancellationRequested();
if (!marker.EndsWith(LeftoverSuffix, StringComparison.OrdinalIgnoreCase)) continue;
var entryFolder = marker[..^LeftoverSuffix.Length];
var sequence = ReadRecord(entryFolder + RecordExtension) is { } record
? await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false)
: null;
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
if (await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false)) settled++;
}
}
return settled;
}
/// <summary>
/// Settles what a move that copied left at its source because it could not remove it (a file held open): the original of
/// a delete, removed once it still holds what went into the trash and no render was recorded there since; the trash copy
/// of a restore, removed once the render is back in the index. Its marker goes either way, unless removing fails again
/// (the next start tries again). True when the marker was settled.
/// </summary>
private async Task<bool> SettleLeftoverAsync(ArchivePaths paths, string entryFolder, CancellationToken cancellationToken)
{
var marker = entryFolder + LeftoverSuffix;
if (!File.Exists(marker)) return false;
try
{
var path = File.ReadAllText(marker).Trim();
var record = ReadRecord(entryFolder + RecordExtension);
var indexed = record is not null && await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null;
var inside = path.Length > 0 && Path.GetFullPath(path).StartsWith(Path.GetFullPath(entryFolder) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
if (path.Length > 0 && (File.Exists(path) || System.IO.Directory.Exists(path)))
{
if (inside && (record is null || indexed))
{
// A restored render's trash copy: the render is back, the copy goes, and a record a crash left with it.
RemoveSource(path);
if (record is not null) File.Delete(entryFolder + RecordExtension);
RemoveEmpty(entryFolder);
}
else if (!inside && record is not null && !indexed)
{
var stored = Stored(paths, path);
var recorded = await db.Renders.ListBySequenceAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
if (recorded.All(r => r.OutputPath != stored) && await MatchesAsync(path, record, cancellationToken).ConfigureAwait(false))
{
RemoveSource(path);
Log.Info("videos", $"{path}, left over by a delete, removed");
}
}
}
File.Delete(marker);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"What {marker} names could not be removed yet; the next start tries again", ex);
return false;
}
}
/// <summary>Records that a move's source stays at <paramref name="path"/> for <see cref="SettleLeftoverAsync"/>; a failure is logged.</summary>
private static void MarkLeftover(string entryFolder, string path)
{
try
{
AtomicFile.WriteAllText(entryFolder + LeftoverSuffix, path);
Log.Warning("videos", $"{path} could not be removed after it was copied; it is removed at the next start");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{path} is left over and could not be recorded as such", ex);
}
}
/// <summary>
/// The SHA-256 of every file of an image sequence's folder (paths inside it, forward slashes, in order); the folder's
/// own render records no hash (decision 14).
@@ -287,9 +399,13 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
/// <summary>
/// Moves a render's file or folder from <paramref name="from"/> to <paramref name="to"/>: renamed on one volume; copied
/// under a part name, verified against <paramref name="record"/>, renamed and the source deleted across volumes.
/// under a part name, verified against <paramref name="record"/>, renamed and the source removed across volumes. Once the
/// verified copy took its name the move is done: a source that cannot be removed then (a file held open) stays whole
/// (<see cref="RemoveSource"/>) and the move returns false, for the caller to record it as left over.
/// </summary>
private async Task MoveAsync(string from, string to, VideoTrashRecord record, CancellationToken cancellationToken)
/// <returns>True when the source is gone; false when the copy is in place and the source left over.</returns>
/// <exception cref="IOException">The move failed before it took its name (nothing moved, no part copy left), the copy not verifying among others.</exception>
private async Task<bool> MoveAsync(string from, string to, VideoTrashRecord record, CancellationToken cancellationToken)
{
var folder = System.IO.Directory.Exists(from);
if (!ForceCopy && SameVolume(from, to))
@@ -298,37 +414,84 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
{
if (folder) System.IO.Directory.Move(from, to);
else File.Move(from, to, overwrite: false);
return;
return true;
}
catch (IOException) when (folder && !System.IO.Directory.Exists(to) && System.IO.Directory.Exists(from))
{
// Another mount on the same root (Linux): copied instead.
// Another mount on the same root (Linux), or a file of the folder held open (Windows): copied instead.
}
}
var part = to + PartSuffix;
DeletePath(part);
if (folder)
{
foreach (var file in System.IO.Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(part, Path.GetRelativePath(from, file));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false);
}
System.IO.Directory.CreateDirectory(part);
}
else
{
await CopyFileAsync(from, part, cancellationToken).ConfigureAwait(false);
}
if (!await MatchesAsync(part, record, cancellationToken).ConfigureAwait(false))
try
{
DeletePath(part);
throw new IOException(Loc.L("Errors.Videos.TrashMismatch"));
if (folder)
{
foreach (var file in System.IO.Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(part, Path.GetRelativePath(from, file));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false);
}
System.IO.Directory.CreateDirectory(part);
}
else
{
await CopyFileAsync(from, part, cancellationToken).ConfigureAwait(false);
}
if (!await MatchesAsync(part, record, cancellationToken).ConfigureAwait(false)) throw new IOException(Loc.L("Errors.Videos.TrashMismatch"));
if (folder) System.IO.Directory.Move(part, to);
else File.Move(part, to, overwrite: false);
}
catch
{
try
{
DeletePath(part);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"The part copy {part} could not be removed", ex);
}
throw;
}
try
{
RemoveSource(from);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{from} was copied to {to} but could not be removed: it stays whole", ex);
return false;
}
}
/// <summary>
/// Removes the source of a verified copy all or nothing: a file is deleted; a folder is renamed aside first (which fails
/// at once while any of its files is open on Windows, leaving it whole), then erased.
/// </summary>
private static void RemoveSource(string path)
{
if (System.IO.Directory.Exists(path))
{
var full = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var aside = Path.Combine(Path.GetDirectoryName(full)!, "." + Path.GetFileName(full) + ".removing-" + Guid.NewGuid().ToString("N")[..8]);
System.IO.Directory.Move(full, aside);
try
{
SequenceTrash.Erase(aside);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Its name is free and its content is in the trash already: what could not be erased is only left over.
Log.Warning("videos", $"{aside} could not be erased whole; it is left over", ex);
}
}
else if (File.Exists(path))
{
File.Delete(path);
}
if (folder) System.IO.Directory.Move(part, to);
else File.Move(part, to, overwrite: false);
DeletePath(from);
}
/// <summary>Copies a file, flushed to the disk.</summary>
@@ -340,8 +503,11 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
to.Flush(flushToDisk: true);
}
/// <summary>Where a restored render goes: where it was (in its sequence's folder as the index has it now), or a free name next to it.</summary>
private static string Destination(ArchivePaths paths, VideoTrashRecord record, Sequence sequence)
/// <summary>
/// Where a restored render goes: where it was (in its sequence's folder as the index has it now), or a free name next to
/// it when that one is on disk or <paramref name="taken"/> (an output a render of this process is writing).
/// </summary>
private static string Destination(ArchivePaths paths, VideoTrashRecord record, Sequence sequence, Func<string, bool> taken)
{
var stored = record.Render.OutputPath;
string full;
@@ -354,8 +520,8 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
: stored;
full = paths.FromRelative(rebased);
}
return File.Exists(full) || System.IO.Directory.Exists(full)
? VideosFolder.FreeName(Path.GetDirectoryName(full)!, Path.GetFileName(full), record.Files is not null)
return File.Exists(full) || System.IO.Directory.Exists(full) || taken(full)
? VideosFolder.FreeName(Path.GetDirectoryName(full)!, Path.GetFileName(full), record.Files is not null, taken)
: full;
}
+3 -2
View File
@@ -64,7 +64,8 @@ public static class VideosFolder
/// "name (2).ext", "name (3).ext"… (a folder's name, an image sequence, has no extension to keep).
/// </summary>
/// <param name="isFolder">The copy is an image sequence's folder: its whole name is the stem.</param>
public static string FreeName(string folder, string fileName, bool isFolder = false)
/// <param name="taken">Names in use besides those on disk (outputs a render of this process is writing).</param>
public static string FreeName(string folder, string fileName, bool isFolder = false, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
@@ -73,7 +74,7 @@ public static class VideosFolder
for (var n = 1; ; n++)
{
var candidate = Path.Combine(folder, (n == 1 ? stem : string.Create(CultureInfo.InvariantCulture, $"{stem} ({n})")) + extension);
if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate;
if (!File.Exists(candidate) && !Directory.Exists(candidate) && taken?.Invoke(candidate) != true) return candidate;
}
}
+33 -5
View File
@@ -38,6 +38,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
const codecs = new Set();
const years = new Set();
const selection = new Selection();
/** Sequence titles read for the sequence filter, by id. */
const titles = new Map();
const user = api.user();
const may = (bit) => (Number(user?.permissions ?? 0) & bit) !== 0;
/** The server's videos folder: "" when none is set (Copy is off), null while unknown (the server decides). */
@@ -232,7 +234,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
root.querySelector("#clear").hidden = !isFiltered();
// One sequence's videos ("All videos" of a sequence page): its title, which opens it, and × for every sequence's
// videos again (the other filters stay).
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle : null;
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle ?? sequenceTitle(filters.sequence) : null;
const chip = root.querySelector("#sequence-filter");
chip.innerHTML = filters.sequence ? `<a class="pill" href="#/library?id=${attr(encodeURIComponent(filters.sequence))}" dir="auto"
title="${attr(t("Admin.Library.Open.Tip"))}">${escapeHtml(title ?? "…")}</a>
@@ -243,6 +245,20 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
setMeta(title ?? "");
}
/**
* The title of a sequence none of whose videos is on the page (a filter that matches nothing, or its videos further
* down): read once from the sequence's own record, and the chip redrawn when it comes; undefined until then.
*/
function sequenceTitle(id) {
if (titles.has(id)) return titles.get(id);
titles.set(id, undefined);
api.get(`/api/v1/sequences/${encodeURIComponent(id)}`).then((s) => {
titles.set(id, s.title ?? "");
if (root.isConnected && filters.sequence === id) drawFilters();
}, () => {});
return undefined;
}
function draw() {
itemsHost.className = `seq-items video-items ${view === "list" ? "rows" : "cards"}`;
itemsHost.setAttribute("role", "listbox");
@@ -330,6 +346,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
return;
}
const one = n === 1;
const [only] = selection.ids;
const downloadWhy = one ? downloadBlock(rows.find((v) => v.id === only)) : "Admin.Videos.Download.One.Tip";
const copyWhy = !may(EDIT) ? "Admin.Videos.Copy.NoRight.Tip" : folder === "" ? "Admin.Videos.Copy.NoFolder.Tip" : null;
const deleteWhy = may(DELETE) ? null : "Admin.Videos.Delete.NoRight.Tip";
mass.hidden = false;
@@ -340,8 +358,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
<span class="spacer"></span>
<button class="btn small" id="mass-play" data-mass="play" data-i18n-title="${one ? "Admin.Videos.Play.Tip" : "Admin.Videos.Play.One.Tip"}"
${one ? "" : "disabled"}>${icons.play}<span data-i18n="Admin.Videos.Play"></span></button>
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${one ? "Admin.Videos.Download.Tip" : "Admin.Videos.Download.One.Tip"}"
${one ? "" : "disabled"}>${icons.download}<span data-i18n="Admin.Videos.Download"></span></button>
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${downloadWhy ?? "Admin.Videos.Download.Tip"}"
${downloadWhy ? "disabled" : ""}>${icons.download}<span data-i18n="Admin.Videos.Download"></span></button>
<button class="btn small" id="mass-copy" data-mass="copy" data-i18n-title="${copyWhy ?? "Admin.Videos.Copy.Tip"}"
${copyWhy ? "disabled" : ""}>${icons.copyToFolder}<span data-i18n="Admin.Videos.Copy"></span></button>
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Videos.Delete"
@@ -377,7 +395,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
}
function download(v) {
if (!v) return;
if (!v || downloadBlock(v)) return;
const a = document.createElement("a");
a.href = fileUrl(v);
a.download = v.fileName ?? "";
@@ -470,7 +488,9 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
dialog.innerHTML = `
<div class="viewer-head"><h2 id="player-title" class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</h2>
<span class="muted ellipsis" dir="ltr">${escapeHtml(v.fileName ?? "")}</span><span class="spacer"></span>
<a class="btn icon" href="${attr(fileUrl(v))}" download="${attr(v.fileName ?? "")}" data-i18n-title="Admin.Videos.Download.Tip">${icons.download}</a>
${downloadBlock(v)
? `<button class="btn icon" type="button" disabled data-i18n-title="${downloadBlock(v)}">${icons.download}</button>`
: `<a class="btn icon" href="${attr(fileUrl(v))}" download="${attr(v.fileName ?? "")}" data-i18n-title="Admin.Videos.Download.Tip">${icons.download}</a>`}
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Videos.Player.Close.Tip">${icons.close}</button></div>
<div class="viewer-stage" dir="ltr">${media}<p class="player-note" ${media ? "hidden" : ""}>${escapeHtml(v.state === "missing"
? t("Admin.Videos.State.Missing.Tip") : t("Admin.Videos.Player.NoPlay"))}</p></div>
@@ -524,6 +544,14 @@ export function videoKind(v) {
return String(v.codec ?? "").toLowerCase().endsWith("sequence") ? "sequence" : "video";
}
/** Why a video has no download: an image sequence is a folder, not one file, and a missing file is gone; null when it has. */
export function downloadBlock(v) {
if (!v) return null;
if (videoKind(v) === "sequence") return "Admin.Videos.Download.Folder.Tip";
if (v.state === "missing") return "Admin.Videos.Download.Missing.Tip";
return null;
}
/** A kind in words; a newer server's kind as it is. */
export function kindText(kind) {
if (kind === "still") return t("Admin.Videos.Kind.Still.Label");
@@ -57,6 +57,54 @@ public sealed class VideoSourcesTests
Assert.Equal(Loc.L("Tooltips.Videos.Missing"), VideoText.PlayToolTip(local[1] with { Missing = true }));
}
[Test]
public void AServersVideoDownloadedHerePlaysFromItsCopy()
{
var remote = Server(Guid.CreateVersion7(), Comet, "Comet", 300, copies: ["/videos/comet.mp4"]);
var gone = Server(Guid.CreateVersion7(), Comet, "Comet", 300);
var local = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 100);
var copy = @"C:\Users\me\Videos\Chronos\comet.mp4";
var copies = new Dictionary<Guid, IReadOnlyList<string>>
{
[remote.Id] = [copy],
[gone.Id] = [@"C:\Users\me\Videos\Chronos\deleted.mp4"],
[local.Id] = [@"C:\elsewhere\harbour.mp4"],
};
var entries = VideoSources.WithLocalCopies([remote, gone, local], copies, path => path == copy);
var downloaded = entries[0];
Assert.Equal(copy, downloaded.LocalPath);
Assert.True(downloaded.HasLocalFile, "Play and Show in folder use the copy");
Assert.SequenceEqual(["/videos/comet.mp4", copy], downloaded.Copies);
Assert.Contains(VideoText.States(downloaded), s => s.Text == Loc.L("Videos.State.Copied"));
Assert.Equal(Loc.L("Tooltips.Videos.Play"), VideoText.PlayToolTip(downloaded));
// A copy deleted since names no file to play, but is still listed; this PC's own render keeps its file.
Assert.True(entries[1] is { LocalPath: null, HasLocalFile: false });
Assert.Same(local, entries[2]);
}
[Test]
public void AServersVideoThatStaysIsNamedNotNumbered()
{
var known = Server(Guid.CreateVersion7(), Comet, "Comet", 300);
var unknown = Guid.CreateVersion7();
var server = new VideoDeletePlanDto([], 0, [new VideoBlockedDto(known.Id, VideoBlockReasons.Busy), new VideoBlockedDto(unknown, VideoBlockReasons.NotFound)], "f", DryRun: true);
var lines = new VideoDeletePlans(null, server, new Dictionary<Guid, string> { [known.Id] = VideoDeletePlans.NameOf(known) }).Lines();
Assert.Contains("Comet" + Loc.Separator + Formatting.LeftToRight("comet.mp4") + Loc.Separator + VideoText.BlockReason(VideoBlockReasons.Busy), lines);
Assert.Contains(unknown.ToString("D") + Loc.Separator + VideoText.BlockReason(VideoBlockReasons.NotFound), lines, "an id the section does not show");
}
[Test]
public void TheDetailsLeaveOutWhatARenderDoesNotHave()
{
var video = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 1_000_000);
var still = video with { Kind = RenderKind.Still, Codec = "PngSequence", DurationSeconds = 0, Width = 6000, Height = 4000 };
Assert.Equal(string.Join(Loc.Separator, "3840×2160", "H.264", VideoText.Duration(video), Formatting.Bytes(video.Bytes)), VideoText.Details(video));
Assert.Equal(string.Join(Loc.Separator, "6000×4000", "PNG", Formatting.Bytes(still.Bytes)), VideoText.Details(still), "no empty duration");
Assert.Equal(string.Join(Loc.Separator, "6000×4000", Formatting.Bytes(still.Bytes)), VideoText.Details(still with { Codec = null }));
}
[Test]
public void TheFiltersNarrowAndTheOrdersSort()
{
@@ -281,9 +329,9 @@ public sealed class VideosSectionTests(TestContext context)
public Task DeleteRunsTheDryRunFirstAndShowsItsBytesAndWhatStays() => WithSectionAsync(async (shell, section, library, dialogs) =>
{
await section.RefreshAsync();
foreach (var row in section.Rows.Where(r => r.Entry.Id != library.Items[2].Render.Id)) row.IsSelected = true;
foreach (var row in section.Rows) row.IsSelected = true;
var selected = section.SelectedRows;
Assert.Equal(2, selected.Count);
Assert.Equal(3, selected.Count);
Assert.Null(section.DeleteBlocker(selected));
// Kept: the plan was made, nothing was deleted.
@@ -299,14 +347,45 @@ public sealed class VideosSectionTests(TestContext context)
Assert.Contains(Loc.L("Videos.Delete.Blocked", Formatting.Count(1)), request.Detail!);
Assert.Contains(VideoText.BlockReason(VideoBlockReasons.Busy), request.Detail!);
// Confirmed: the delete gives back the plan's fingerprint.
// Confirmed: the delete gives back the plan's fingerprint with exactly the ids planned, the one that stays included
// (a fingerprint of fewer ids would never match).
dialogs.Answer = true;
var asked = selected.Select(r => r.Entry.Id).ToList();
await section.DeleteAsync(selected);
Assert.SequenceEqual(["plan", "plan", "delete:fingerprint-2"], library.Calls);
Assert.SequenceEqual(asked.Order(), library.DeletedIds.Order());
Assert.Contains(shell.PendingToasts, t => t.Title == Loc.L("Videos.Delete.Done", Formatting.Count(2)) && !t.IsError);
Assert.Equal(1, section.Rows.Count);
});
[Test]
public Task ADisabledActionSaysWhyInTheBarAndInTheMenu() => WithSectionAsync(async (shell, section, library, _) =>
{
await section.RefreshAsync();
var video = section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id);
var missing = section.Rows.Single(r => r.Entry.Id == library.Items[1].Render.Id);
// Signed out: Copy on server gives the server's reason, in the row's menu too.
Assert.Equal(Loc.L("Tooltips.Videos.ServerOffline"), video.MenuCopyOnServerToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.Missing"), missing.MenuShowInFolderToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.ShowInFolder"), video.MenuShowInFolderToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.Missing"), missing.MenuCopyToolTip, "the menu's Copy gives the row's reason");
// Two selected: Play, Show in folder and Open in Edit act on one video, and say so.
video.IsSelected = true;
missing.IsSelected = true;
Assert.False(section.PlayCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.PlayToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.ShowInFolderToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.OpenInEditToolTip);
Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), video.MenuPlayToolTip, "a selected row's menu acts on the selection");
// A server's video alone: not on this PC.
var remote = new VideoRowViewModel(VideoSources.FromServer(Dto(library.Items[0]) with { Id = Guid.CreateVersion7() }));
Assert.Equal(Loc.L("Tooltips.Videos.ServerOnly"), VideosViewModel.OpenInEditToolTipOf([remote]));
Assert.Equal(Loc.L("Tooltips.Videos.ServerOnly"), VideosViewModel.ShowInFolderToolTipOf([remote]));
Assert.Equal(Loc.L("Videos.Download"), VideosViewModel.CopyTextOf([remote]));
});
[Test]
public Task ACopyWithoutAVideosFolderSaysWhy() => WithSectionAsync(async (shell, section, library, _) =>
{
@@ -393,6 +472,19 @@ public sealed class VideosSectionTests(TestContext context)
var player = Assert.NotNull(section.Player);
Assert.Equal(library.Items[0].Render.Id, player.Entry.Id);
Layout(view);
// Beside the player, at 1000 px too (a 1200 px window with the rail open), the list keeps its state column in view:
// the preset, format and date columns give way.
Layout(view, 1000);
var pane = Descendants(view).OfType<VideoPlayerPane>().Single();
var paneLeft = pane.TranslatePoint(new System.Windows.Point(0, 0), view).X;
foreach (var header in new[] { "Videos.Column.State", "Videos.Column.Size" })
{
var cell = Descendants(view).OfType<System.Windows.Controls.TextBlock>().First(t => t.Text == Loc.L(header));
Assert.True(cell.ActualWidth > 0, header);
Assert.True(cell.TranslatePoint(new System.Windows.Point(cell.ActualWidth, 0), view).X <= paneLeft, $"{header} runs under the player");
}
Assert.Equal(System.Windows.Visibility.Collapsed,
Descendants(view).OfType<System.Windows.Controls.TextBlock>().First(t => t.Text == Loc.L("Videos.Column.Date")).Visibility);
section.ClosePlayerCommand.Execute(null);
Assert.False(section.IsPlayerOpen);
// Settings › Archive shows the videos folder row.
@@ -413,13 +505,23 @@ public sealed class VideosSectionTests(TestContext context)
Assert.True(shell.Settings.OpenVideosFolderCommand.CanExecute(null));
});
private static void Layout(System.Windows.FrameworkElement view)
private static void Layout(System.Windows.FrameworkElement view, double width = 1200)
{
view.Measure(new System.Windows.Size(1200, 800));
view.Arrange(new System.Windows.Rect(0, 0, 1200, 800));
view.Measure(new System.Windows.Size(width, 800));
view.Arrange(new System.Windows.Rect(0, 0, width, 800));
view.UpdateLayout();
}
private static IEnumerable<System.Windows.DependencyObject> Descendants(System.Windows.DependencyObject root)
{
for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = System.Windows.Media.VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var below in Descendants(child)) yield return below;
}
}
/// <summary>The section of a shell on a fresh data folder, reading <see cref="FakeLibrary"/>, signed out, no workspace renders.</summary>
private Task WithSectionAsync(Func<ShellViewModel, VideosViewModel, FakeLibrary, ScriptedDialogs, Task> body) => ScreenHost.RunAsync(async () =>
{
@@ -475,6 +577,9 @@ public sealed class VideosSectionTests(TestContext context)
public List<string> Calls { get; } = [];
/// <summary>The ids the last delete was asked for.</summary>
public List<Guid> DeletedIds { get; private set; } = [];
public bool IsAvailable => true;
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(new VideoPage([.. Items], null, Items.Count));
@@ -484,16 +589,17 @@ public sealed class VideosSectionTests(TestContext context)
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
{
lock (Calls) Calls.Add("plan");
// Both go (the missing one only loses its row); another render, being sent, is named as staying.
var wanted = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
// Both go (the missing one only loses its row); the still, being sent, is named as staying.
var stays = new VideoBlocked(Items[2].Render.Id, VideoBlockReasons.Busy, Items[2]);
var wanted = Items.Where(i => renderIds.Contains(i.Render.Id) && i.Render.Id != stays.RenderId).ToList();
return Task.FromResult(new VideoDeletePlan(wanted, [stays], "fingerprint-" + Interlocked.Increment(ref _plans)));
}
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
{
lock (Calls) Calls.Add("delete:" + fingerprint);
var gone = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
DeletedIds = [.. renderIds];
var gone = Items.Where(i => renderIds.Contains(i.Render.Id) && i != Items[2]).ToList();
Items.RemoveAll(gone.Contains);
return Task.FromResult(new VideoDeleteResult(gone, [], []));
}
@@ -26,6 +26,9 @@ internal sealed class CapturingEncoderProvider(string name, params EncoderCapabi
/// <summary>When set, WriteFrame throws this for the frame with that zero-based index.</summary>
public (int Frame, Exception Error)? FailAt { get; set; }
/// <summary>The settings each session says it did not take (<see cref="IVideoEncoderSession.Ignored"/>).</summary>
public IReadOnlyList<EncoderSetting> Ignores { get; set; } = [];
public bool CanEncode(EncodeSettings settings) => capabilities.Any(c =>
c.Codec == settings.Codec && EncoderSelector.Takes(c, settings.Width, settings.Height) && (settings.BitDepth == 8 || c.SupportsTenBit));
@@ -54,5 +57,7 @@ internal sealed class CapturingEncoderProvider(string name, params EncoderCapabi
public void Complete() => encode.Completed = true;
public void Dispose() => encode.Disposed = true;
public IReadOnlyList<EncoderSetting> Ignored => owner.Ignores;
}
}
@@ -82,6 +82,20 @@ public sealed class PlaybackRenderTests
Assert.Contains(result.Warnings, w => w.Key == OutputProgram.BoomerangStackWarning);
}
[Test]
public async Task EachLoopOfStarTrailsGrowsItsTrailsAgain()
{
var stars = Source(6, motion: i => (1.0 * i, 0), configure: o => o with { StarField = true, StartEv = 0, EndEv = 0, StarCount = 60 });
var trails = new StackSettings { Mode = StackSetting.StarTrails, Length = 0 };
var (looped, _) = await CaptureAsync(Input(stars, Playing(new PlaybackSettings { Loops = 2 }) with { Stack = trails }),
cancellationToken: _context.Cancellation);
Assert.Equal(12, looped.Frames.Count);
// The second pass starts from nothing again: frame 6 + k is frame k, never the finished trails of the first pass.
for (var k = 0; k < 6; k++)
Assert.True(double.IsPositiveInfinity(Psnr(looped.Frames[k], looped.Frames[6 + k])), $"frame {6 + k} differs from frame {k}");
Assert.False(double.IsPositiveInfinity(Psnr(looped.Frames[5], looped.Frames[6])), "the loop seam shows the trails start again");
}
[Test]
public async Task AMedianWindowIsTheSameFrameInEitherDirection()
{
@@ -142,6 +142,21 @@ public sealed class RenderPipelineTests
Assert.Equal(4, encode.Frames.Count);
}
[Test]
public async Task SettingsTheEncoderIgnoredAreRenderWarnings()
{
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true))
{
Ignores = [EncoderSetting.RateControl, EncoderSetting.BFrames],
};
var result = await Pipeline(capture).RenderAsync(Input(Source()), Target(_context.CreateTempDirectory(), Preset("png-sequence")));
Assert.Contains(result.Warnings, w => w.Key == "Export.Encoder.Ignored.RateControl");
Assert.Contains(result.Warnings, w => w.Key == "Export.Encoder.Ignored.BFrames");
// Each key is a message of the catalogue.
foreach (var setting in Enum.GetValues<EncoderSetting>())
Assert.NotEqual("Export.Encoder.Ignored." + setting, Chronos.Core.Localization.Loc.L("Export.Encoder.Ignored." + setting));
}
[Test]
public async Task ProgressReportsEveryFrameAndPreviews()
{
@@ -67,6 +67,35 @@ public sealed class VideoLibraryTests(TestContext context)
Assert.True((await fx.Library.GetAsync(gif.Id, fx.Ct))!.Missing);
}
[Test]
public async Task AStillWhoseKindWasLostIsStillAStill()
{
// A still a server of before phase 5 stored (and a PC then synced) has no kind: its image codec, fps 0 and duration 0 tell it.
await using var fx = await VideoFixture.CreateAsync(context);
var roof = await fx.SequenceAsync("Roof", 2);
var kindless = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = roof.Id,
PresetName = "PNG",
OutputPath = "Roof/exports/roof - 0007.png",
Codec = "PngSequence",
Width = 96,
Height = 64,
Created = Day,
};
await fx.Db.Renders.InsertAsync(kindless, fx.Ct);
var pngs = await fx.SequenceRenderAsync(roof, "roof-PNG", 2);
Assert.Equal(RenderKind.Still, RenderKind.Of(kindless));
Assert.Equal(RenderKind.Sequence, RenderKind.Of(pngs), "an image sequence has a frame rate");
async Task<List<Guid>> Ids(string kind) => [.. (await fx.Library.ListAsync(new VideoQuery { Kind = kind }, fx.Ct)).Items.Select(i => i.Render.Id)];
Assert.SequenceEqual([kindless.Id], await Ids(RenderKind.Still));
Assert.SequenceEqual([pngs.Id], await Ids(RenderKind.Sequence));
Assert.Empty(await Ids(RenderKind.Video));
Assert.Equal(RenderKind.Still, (await fx.Library.GetAsync(kindless.Id, fx.Ct))!.Kind);
}
[Test]
public async Task TheDryRunFingerprintChangesWhenTheVideosDo()
{
@@ -208,4 +237,80 @@ public sealed class VideoLibraryTests(TestContext context)
Assert.Equal((pngs.Id, (string?)null), (restored.Id, restored.Sha256));
Assert.Equal(4, Directory.GetFiles(fx.FileOf(pngs)).Length);
}
[Test]
[WindowsOnly]
public async Task AFileHeldOpenWhileItIsCopiedToTheTrashStaysWholeUntilTheNextStart()
{
await using var fx = await VideoFixture.CreateAsync(context);
var sequence = await fx.SequenceAsync();
var render = await fx.RenderAsync(sequence, "sunset.mp4", 3000);
var source = fx.FileOf(render);
fx.Library.Trash.ForceCopy = true;
var plan = await fx.Library.PlanDeleteAsync([render.Id], fx.Ct);
// A player holds the file open: it copies and verifies, but the original cannot be deleted.
string name;
using (new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
name = (await fx.Library.DeleteAsync([render.Id], plan.Fingerprint, null, fx.Ct)).TrashEntries.Single();
// The delete is done (row gone, verified copy listed); the original stays whole and is marked as left over.
var (folder, _) = VideoTrash.Location(fx.Archive.Paths, name);
Assert.Null(await fx.Db.Renders.GetAsync(render.Id, fx.Ct));
Assert.Equal(3000L, new FileInfo(Path.Combine(folder, "sunset.mp4")).Length);
Assert.Equal(3000L, new FileInfo(source).Length);
Assert.True(File.Exists(folder + VideoTrash.LeftoverSuffix));
Assert.Equal(name, (await fx.Archive.Service.Trash.ListAsync(fx.Archive.Archive, fx.Ct)).Single(e => e.Kind == Chronos.Data.Archiving.TrashKind.Videos).Name);
// The next start removes it, and the render comes back under its own name.
Assert.Equal(1, await fx.Library.RecoverAsync(fx.Archive.Archive, fx.Ct));
Assert.False(File.Exists(source));
Assert.False(File.Exists(folder + VideoTrash.LeftoverSuffix));
Assert.Equal(render.OutputPath, (await fx.Library.RestoreAsync(fx.Archive.Archive.Id, name, fx.Ct)).OutputPath);
}
[Test]
[WindowsOnly]
public async Task AnImageSequenceWithAFileHeldOpenKeepsEveryFileUntilTheNextStart()
{
await using var fx = await VideoFixture.CreateAsync(context);
var sequence = await fx.SequenceAsync();
var pngs = await fx.SequenceRenderAsync(sequence, "clip-PNG", 4);
var source = fx.FileOf(pngs);
var files = Directory.GetFiles(source).Order(StringComparer.Ordinal).ToList();
fx.Library.Trash.ForceCopy = true;
var plan = await fx.Library.PlanDeleteAsync([pngs.Id], fx.Ct);
string name;
using (new FileStream(files[2], FileMode.Open, FileAccess.Read, FileShare.Read))
name = (await fx.Library.DeleteAsync([pngs.Id], plan.Fingerprint, null, fx.Ct)).TrashEntries.Single();
// Never half a folder: every file stays where it was, and every one is in the trash.
var (folder, _) = VideoTrash.Location(fx.Archive.Paths, name);
Assert.SequenceEqual(files, Directory.GetFiles(source).Order(StringComparer.Ordinal));
Assert.Equal(4, Directory.GetFiles(Path.Combine(folder, Path.GetFileName(source))).Length);
Assert.True(File.Exists(folder + VideoTrash.LeftoverSuffix));
Assert.Equal(1, await fx.Library.RecoverAsync(fx.Archive.Archive, fx.Ct));
Assert.False(Directory.Exists(source));
Assert.Empty(Directory.GetDirectories(Path.GetDirectoryName(source)!, ".*removing-*"));
Assert.Equal(4, Directory.GetFiles(Path.Combine(folder, Path.GetFileName(source))).Length, "the trash keeps its copy");
}
[Test]
public async Task ARestoreSkipsANameARenderIsWriting()
{
await using var fx = await VideoFixture.CreateAsync(context);
var sequence = await fx.SequenceAsync();
var render = await fx.RenderAsync(sequence, "sunset.mp4", 2000);
var plan = await fx.Library.PlanDeleteAsync([render.Id], fx.Ct);
var name = (await fx.Library.DeleteAsync([render.Id], plan.Fingerprint, null, fx.Ct)).TrashEntries.Single();
// A render of this process picked the free name meanwhile and is still encoding it.
using var writing = new Chronos.Data.Processing.OutputNames();
Assert.True(writing.TryReserve(fx.FileOf(render)));
var restored = await fx.Library.RestoreAsync(fx.Archive.Archive.Id, name, fx.Ct);
Assert.Equal("sunset (2).mp4", Path.GetFileName(restored.OutputPath));
Assert.False(File.Exists(fx.FileOf(render)));
}
}
@@ -50,10 +50,11 @@ public sealed class VideoRenderTests(TestContext context)
// Only a batch preset plays back: the job of that preset needs format 3, the plain one does not.
var split = ProcessingJobs.Split(Read(ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64, new ProjectSettings())), 96, 64, new ProjectSettings());
Assert.SequenceEqual([1, 1], split.Select(p => p.RequiredSettingsFormat));
// Routed with settings whose own export plays back, the job's export (which does not) is what counts, and the other way round.
// Routed with settings whose own export plays back, the job's export does not, but the settings text the node reads is
// format 3: a node of format 2 could not parse it. The other way round, the job's export counts.
var plain = Read(ProcessingJobs.Render(sequence, Mjpeg, 96, 64, new ProjectSettings()));
var playing = new ProjectSettings { Export = Mjpeg with { Playback = Boomerang } };
Assert.Equal(1, ProcessingJobs.Routed(plain, playing, 96, 64).RequiredSettingsFormat);
Assert.Equal(ProjectSettings.PlaybackVersion, ProcessingJobs.Routed(plain, playing, 96, 64).RequiredSettingsFormat);
var posted = Read(ProcessingJobs.Render(sequence, Mjpeg with { Playback = Boomerang }, 96, 64, new ProjectSettings())) with { RequiredSettingsFormat = 1 };
Assert.Equal(ProjectSettings.PlaybackVersion, ProcessingJobs.Routed(posted, new ProjectSettings(), 96, 64).RequiredSettingsFormat);
Assert.Equal(ProjectSettings.PlaybackVersion, ProcessingJobs.RequiredFormat(new ProjectSettings(), Mjpeg with { Batch = ["gif-preview"], Playback = Boomerang }, 96, 64));
@@ -124,7 +125,8 @@ public sealed class VideoRenderTests(TestContext context)
var set = new SequenceFrames(sequence, frames, frames.Select(f => (string?)f.RelativePath).ToList());
Assert.Equal(3, SequenceRender.StillIndex(set, 1, new string('d', 64)));
Assert.Equal(3, SequenceRender.StillIndex(set, 1, new string('D', 64)), "any case");
Assert.Equal(1, SequenceRender.StillIndex(set, 1, new string('z', 64)), "a photo no longer there: the index");
Assert.Null(SequenceRender.StillIndex(set, 1, new string('z', 64)), "a photo no longer there: its index names another photo now");
Assert.Equal(1, SequenceRender.StillIndex(set, 1, null), "no hash: the index");
Assert.Null(SequenceRender.StillIndex(set, 9, null));
// Named by the export's template and the frame number from 1; a taken name gets " (2)".
var folder = context.CreateTempDirectory("still");
@@ -48,12 +48,12 @@ public sealed partial class AdminVideosTests(TestContext context)
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
var calls = ApiCall().Matches(page).Select(m => (Method: m.Groups[1].Value, Target: m.Groups[2].Value)).ToList();
Assert.True(calls.Count >= 4, string.Join(", ", calls));
// Reads the list and the server's videos folder; writes only the videos' delete and copy: no settings, no project,
// no render, no job of its own.
// Reads the list, the server's videos folder and a filtered sequence's title; writes only the videos' delete and copy:
// no settings, no project, no render, no job of its own.
foreach (var (method, target) in calls)
{
Assert.True(method is "get" or "post", $"api.{method}({target}");
if (method == "get") Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""", target);
if (method == "get") Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""" or "`/api/v1/sequences/${encodeURIComponent(id)}`", target);
else Assert.True(target is @"""/api/v1/videos/copy""" or @"""/api/v1/videos/delete""", target);
}
Assert.Contains("return `/api/v1/videos?${p}`;", page);
@@ -82,6 +82,14 @@ public sealed partial class AdminVideosTests(TestContext context)
Assert.Contains(@"<video controls autoplay preload=""metadata"" src=""${attr(fileUrl(v))}""></video>", page);
Assert.Contains("return `/api/v1/renders/${encodeURIComponent(v.id)}/file`;", page);
Assert.Contains(@"shown?.addEventListener(""error"", () => {", page);
// An image sequence (a folder, no single file) and a missing file have no download, in the bar or the player.
Assert.Contains(@"if (videoKind(v) === ""sequence"") return ""Admin.Videos.Download.Folder.Tip"";", page);
Assert.Contains(@"if (v.state === ""missing"") return ""Admin.Videos.Download.Missing.Tip"";", page);
Assert.Contains(@"const downloadWhy = one ? downloadBlock(rows.find((v) => v.id === only)) : ""Admin.Videos.Download.One.Tip"";", page);
Assert.Contains("if (!v || downloadBlock(v)) return;", page);
Assert.Contains("${downloadBlock(v)\n", page);
// A sequence filter whose videos are not on the page names the sequence from its own record.
Assert.Contains("api.get(`/api/v1/sequences/${encodeURIComponent(id)}`)", page);
// The list follows the jobs that end (a copy, a render), the sequences that change and a reconnection.
Assert.Contains(@"if (e.type === ""jobState"" && JOB_ENDED.has(e.state)) refreshSoon(1500);", page);
Assert.Contains(@"else if (e.type === ""reconnected"") refreshSoon(0);", page);
@@ -36,4 +36,24 @@ public sealed class PlaybackRoutingTests
var still = ProcessingJobs.ReadRender(ProcessingJobs.Still(sequence, Mjpeg, VideoCodec.JpegSequence, 0, null, 96, 64, new ProjectSettings()).ParametersJson).Parameters;
Assert.False(RenderNodeService.Renders(Node(2) with { Encoders = [new NodeEncoder(still.Codec, "managed", false, false)] }, still));
}
[Test]
public void SettingsWrittenInFormatThreeNeverGoToAFormatTwoNodeEvenWhenTheJobDoesNotPlayBack()
{
// The sequence's own export plays back, so its settings text is stamped version 3; the job's preset does not.
var stored = new ProjectSettings { Export = Mjpeg with { Playback = new PlaybackSettings { Loops = 3 } } }.ToJson();
var read = ProcessingJobs.ReadSettings(stored)!;
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Roof", Title = "Roof" };
var job = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson).Parameters;
Assert.Equal(1, job.RequiredSettingsFormat);
var routed = ProcessingJobs.Routed(job, read, 96, 64);
var split = ProcessingJobs.Split(job, 96, 64, read);
Assert.Equal(3, routed.RequiredSettingsFormat);
Assert.True(split.All(p => p.RequiredSettingsFormat == 3));
RegisterNodeRequest Node(int format) => new("node", [new NodeEncoder("mjpeg", "managed", false, false)], 0, 0, format);
Assert.False(RenderNodeService.Renders(Node(2), routed), "a format-2 node cannot parse the settings it would be handed");
Assert.True(RenderNodeService.Renders(Node(3), routed));
}
}