E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova: - JPEG: il controllo stima la memoria di lavoro del decodificatore (progressivo), così un file che non si decodifica esce «troppo grande» e non «illeggibile». - Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento, perché la foto convertita non esca girata. - Fotogrammi: istanti in millisecondi interi; la copia trova l'indice del nome dall'istante, non dall'ordine delle righe. - Video di durata sconosciuta misurati prima di registrare: contano nei limiti di 500 per richiesta e 5000 per video. - Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine tagliata resta nascosta (anche nei fotogrammi). - H.264: il punto di recupero vale come IDR solo con exact_match_flag. - MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre. - Conversione della libreria: il lavoro toglie le righe di un formato spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova» solo i formati di adesso; pausa per spazio prima di rileggere l'originale. - «Anche i N» conta e mette in coda solo il tipo che si cambia; le impostazioni dell'esportazione si salvano una per volta. - Eliminazione e «Tieni il più grande» scelgono i convertiti nella stessa transazione: nessun convertito orfano. - Un file arrivato tardi in un elemento vecchio mette in coda solo sé (file nuovo = salvato da quando il formato è scelto). - Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non si interrompe, uno fermo sì. Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eb79b05fda
commit
958cb71cd6
38 files changed
+1276
-222
No files matched your search
@@ -282,6 +282,7 @@ public static class IsoBmffReader
|
||||
internal long EditOffset;
|
||||
internal bool HasEdits;
|
||||
internal long EmptyEditMovie;
|
||||
internal long EditSegmentMovie;
|
||||
internal int EditCount;
|
||||
internal string? Language;
|
||||
internal int ObjectType;
|
||||
@@ -417,6 +418,7 @@ public static class IsoBmffReader
|
||||
leading = false;
|
||||
track.HasEdits = true;
|
||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||
track.EditSegmentMovie = segment; // and how long it is shown (movie units; 0: to the end)
|
||||
}
|
||||
|
||||
// A rate other than 1 (a slowed or still segment) is not an ordinary edit either.
|
||||
@@ -1040,6 +1042,7 @@ public static class IsoBmffReader
|
||||
Samples = video.Samples,
|
||||
EditMediaTime = video.HasEdits ? video.EditOffset : null,
|
||||
EmptyEditDuration = EmptyEdit(video),
|
||||
EditSegmentDuration = EditSegment(video),
|
||||
EditCount = video.EditCount,
|
||||
Language = video.Language,
|
||||
};
|
||||
@@ -1070,6 +1073,7 @@ public static class IsoBmffReader
|
||||
Samples = audio.Samples,
|
||||
EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
|
||||
EmptyEditDuration = EmptyEdit(audio),
|
||||
EditSegmentDuration = EditSegment(audio),
|
||||
EditCount = audio.EditCount,
|
||||
Language = audio.Language,
|
||||
};
|
||||
@@ -1096,6 +1100,21 @@ public static class IsoBmffReader
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The segment of the first non-empty edit (movie units) in track units, rounded to the nearest; null when the
|
||||
/// edit has none (0, as fragmented files write it) or the track has no edit list.
|
||||
/// </summary>
|
||||
private long? EditSegment(Track track)
|
||||
{
|
||||
if (!track.HasEdits || track.EditSegmentMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var value = (((Int128)track.EditSegmentMovie * track.Timescale) + (timescale / 2)) / timescale;
|
||||
return value > long.MaxValue / 4 ? null : (long)value;
|
||||
}
|
||||
|
||||
/// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
|
||||
private long EmptyEdit(Track track)
|
||||
{
|
||||
|
||||
@@ -107,6 +107,13 @@ public abstract class MediaTrack
|
||||
/// </summary>
|
||||
public long EmptyEditDuration { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How long the first non-empty edit shows the media from <see cref="EditMediaTime"/>, in track units; null when the
|
||||
/// edit runs to the end of the media (no segment written) or there is no edit list. Shorter than the media after
|
||||
/// <see cref="EditMediaTime"/>: the end of the media is hidden (a trim, the padding of AAC).
|
||||
/// </summary>
|
||||
public long? EditSegmentDuration { get; init; }
|
||||
|
||||
/// <summary>The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list).</summary>
|
||||
public int EditCount { get; init; }
|
||||
|
||||
|
||||
@@ -267,6 +267,7 @@ public static class Mp4Remuxer
|
||||
Language = video.Language,
|
||||
EditMediaTime = edit,
|
||||
EmptyEditDuration = video.EmptyEditDuration,
|
||||
EditSegmentDuration = video.EditSegmentDuration,
|
||||
LastSampleDuration = LastDuration(video),
|
||||
};
|
||||
}
|
||||
@@ -287,6 +288,7 @@ public static class Mp4Remuxer
|
||||
Language = audio.Language,
|
||||
EditMediaTime = edit,
|
||||
EmptyEditDuration = audio.EmptyEditDuration,
|
||||
EditSegmentDuration = audio.EditSegmentDuration,
|
||||
LastSampleDuration = LastDuration(audio),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ public sealed class Mp4OutputTrack
|
||||
public string? SampleEntryType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, ISO/IEC 14496-1): it has no
|
||||
/// AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
|
||||
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, or 0x69 at 24 kHz and below,
|
||||
/// ISO/IEC 14496-1): it has no AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
|
||||
/// </summary>
|
||||
public bool IsMp3 { get; init; }
|
||||
|
||||
@@ -66,6 +66,12 @@ public sealed class Mp4OutputTrack
|
||||
|
||||
/// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary>
|
||||
public long EmptyEditDuration { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How long the edit shows the media, in track units (the source's segment: a trimmed end stays hidden); null shows
|
||||
/// it from <see cref="EditMediaTime"/> to the end. Never longer than the media.
|
||||
/// </summary>
|
||||
public long? EditSegmentDuration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The dates of the movie header; the modification date falls back to the creation date.</summary>
|
||||
@@ -264,9 +270,15 @@ public static class Mp4Writer
|
||||
return new Mp4Layout(tracks, chunks, head, payload);
|
||||
}
|
||||
|
||||
/// <summary>Times of a track as the boxes need them; <paramref name="EmptyEdit"/> is in track units.</summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit)
|
||||
/// <summary>
|
||||
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/> and <paramref name="Shown"/> (the media
|
||||
/// the edit shows, from <paramref name="EditMediaTime"/>) are in track units.
|
||||
/// </summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown)
|
||||
{
|
||||
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
|
||||
public bool TrimsEnd => Shown < MediaDuration - EditMediaTime;
|
||||
|
||||
internal static Timing Of(Mp4OutputTrack track)
|
||||
{
|
||||
var samples = track.Samples;
|
||||
@@ -313,7 +325,13 @@ public static class Mp4Writer
|
||||
editTime = 0;
|
||||
}
|
||||
|
||||
return new Timing(durations, offsets, total, editTime, allKey, empty);
|
||||
var shown = Math.Max(0, total - editTime);
|
||||
if (track.EditSegmentDuration is { } segment && segment > 0)
|
||||
{
|
||||
shown = Math.Min(shown, segment);
|
||||
}
|
||||
|
||||
return new Timing(durations, offsets, total, editTime, allKey, empty, shown);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +376,7 @@ public static class Mp4Writer
|
||||
long movieDuration = 0;
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
|
||||
movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].Shown, tracks[t].Timescale));
|
||||
}
|
||||
|
||||
var moov = new Box("moov");
|
||||
@@ -433,7 +451,7 @@ public static class Mp4Writer
|
||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
|
||||
{
|
||||
var trak = new Box("trak");
|
||||
var segment = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
|
||||
var segment = ToMovie(timing.Shown, track.Timescale);
|
||||
var empty = EmptyMovie(timing, track.Timescale);
|
||||
var duration = empty + segment;
|
||||
var wide = duration > uint.MaxValue || Wide(time);
|
||||
@@ -466,7 +484,7 @@ public static class Mp4Writer
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
||||
trak.Child(tkhd);
|
||||
|
||||
if (timing.EditMediaTime != 0 || empty > 0)
|
||||
if (timing.EditMediaTime != 0 || empty > 0 || timing.TrimsEnd)
|
||||
{
|
||||
var edts = new Box("edts");
|
||||
var elst = new Box("elst");
|
||||
@@ -734,7 +752,9 @@ public static class Mp4Writer
|
||||
|
||||
var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!);
|
||||
var config = new byte[13 + decoderSpecific.Length];
|
||||
config[0] = track.IsMp3 ? (byte)0x6B : (byte)0x40; // MPEG-1 audio (layer III) or MPEG-4 audio
|
||||
// MPEG-4 audio, or layer III: MPEG-1 audio (ISO/IEC 11172-3, 32 to 48 kHz) or the MPEG-2 audio of the lower
|
||||
// rates (ISO/IEC 13818-3, 16 to 24 kHz and the 8 to 12 kHz of «MPEG-2.5»): ISO/IEC 14496-1 Table 5.
|
||||
config[0] = !track.IsMp3 ? (byte)0x40 : track.SampleRate is > 0 and <= 24000 ? (byte)0x69 : (byte)0x6B;
|
||||
config[1] = 0x15; // audio stream
|
||||
decoderSpecific.CopyTo(config, 13);
|
||||
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
||||
|
||||
@@ -217,8 +217,9 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0: decoding from it
|
||||
/// gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before the first slice counts.
|
||||
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0 and exact_match_flag
|
||||
/// 1: decoding from it gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before
|
||||
/// the first slice counts.
|
||||
/// </summary>
|
||||
internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
|
||||
{
|
||||
@@ -281,7 +282,15 @@ public sealed partial class H264Decoder
|
||||
payloadSize += data[p++];
|
||||
if (payloadType == 6)
|
||||
{
|
||||
return payloadSize > 0 && new RbspReader(data, Math.Min(length, p + payloadSize), p).ReadUe() == 0;
|
||||
// recovery_frame_cnt 0, then exact_match_flag 1 (§D.2.8): with 0 the pictures from here may
|
||||
// differ from those decoded from the IDR before, so it is no exact start.
|
||||
if (payloadSize <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var reader = new RbspReader(data, Math.Min(length, p + payloadSize), p);
|
||||
return reader.ReadUe() == 0 && reader.BitsLeft > 0 && reader.ReadFlag();
|
||||
}
|
||||
|
||||
p += payloadSize;
|
||||
|
||||
@@ -86,6 +86,52 @@ internal static class ExifOrientation
|
||||
return ifd >= 8 && ifd <= (uint)(tiff.Length - 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The smallest EXIF block that carries <paramref name="orientation"/>: a TIFF header in the byte order asked, a
|
||||
/// first IFD at offset 8 with the one Orientation entry (SHORT, count 1) and no next IFD. 26 bytes.
|
||||
/// </summary>
|
||||
public static byte[] Minimal(int orientation, bool littleEndian)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(orientation, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(orientation, 8);
|
||||
var block = new byte[26];
|
||||
var b = block.AsSpan();
|
||||
b[0] = b[1] = littleEndian ? (byte)'I' : (byte)'M';
|
||||
W16(b[2..], 42, littleEndian);
|
||||
W32(b[4..], 8, littleEndian); // the first IFD
|
||||
W16(b[8..], 1, littleEndian); // one entry
|
||||
W16(b[10..], OrientationTag, littleEndian);
|
||||
W16(b[12..], 3, littleEndian); // SHORT
|
||||
W32(b[14..], 1, littleEndian); // count
|
||||
W16(b[18..], (ushort)orientation, littleEndian); // the value, left-justified in the 4-byte field
|
||||
// Bytes 22-25: the offset of the next IFD, 0.
|
||||
return block;
|
||||
}
|
||||
|
||||
private static void W16(Span<byte> b, ushort value, bool little)
|
||||
{
|
||||
if (little)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16BigEndian(b, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static void W32(Span<byte> b, uint value, bool little)
|
||||
{
|
||||
if (little)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(b, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
|
||||
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
|
||||
|
||||
|
||||
@@ -202,6 +202,10 @@ public static class ImageConverter
|
||||
var tooLarge = target == ImageFormat.WebP
|
||||
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
|
||||
: pixels > ImageLimits.Default.MaxPixels;
|
||||
|
||||
// What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder
|
||||
// would refuse is too large for the conversion, never «not readable» (§4.10).
|
||||
tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes;
|
||||
return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
|
||||
}
|
||||
|
||||
@@ -279,7 +283,7 @@ public static class ImageConverter
|
||||
{
|
||||
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
|
||||
losses.Add(ImageConversionLosses.LostExifUnreadable);
|
||||
exif = null;
|
||||
exif = OrientationOnly(metadata);
|
||||
}
|
||||
|
||||
var icc = metadata.IccProfile;
|
||||
@@ -364,7 +368,7 @@ public static class ImageConverter
|
||||
{
|
||||
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
|
||||
losses.Add(ImageConversionLosses.LostExifTooLarge);
|
||||
exif = null;
|
||||
exif = OrientationOnly(metadata);
|
||||
}
|
||||
|
||||
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
|
||||
@@ -431,6 +435,16 @@ public static class ImageConverter
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In place of an EXIF block left behind, the smallest one that keeps its orientation (in the source's byte order),
|
||||
/// or null when the orientation is 1: the pixels are never turned (§4.10), so without the tag the picture would
|
||||
/// show turned. The loss stays in the notes.
|
||||
/// </summary>
|
||||
private static byte[]? OrientationOnly(ImageMetadata metadata) =>
|
||||
metadata.Orientation is > 1 and <= 8
|
||||
? ExifOrientation.Minimal(metadata.Orientation, metadata.Exif is not { Length: > 0 } e || e[0] != (byte)'M')
|
||||
: null;
|
||||
|
||||
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
|
||||
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
|
||||
{
|
||||
|
||||
@@ -71,4 +71,11 @@ public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int Fr
|
||||
|
||||
/// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary>
|
||||
public bool IsCmyk { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The working memory a full decode asks besides the decoded image, as the decoder checks it against
|
||||
/// <see cref="ImageLimits.MaxWorkingBytes"/> (a progressive or lossless JPEG keeps its coefficients or samples:
|
||||
/// up to 9 bytes a pixel); 0 when the format's decoder needs none worth counting before it starts.
|
||||
/// </summary>
|
||||
public long DecodeWorkingBytes { get; init; }
|
||||
}
|
||||
@@ -332,7 +332,12 @@ internal sealed partial class JpegFile : IDisposable
|
||||
Texts = _texts ?? [],
|
||||
Unread = _unread ?? [],
|
||||
};
|
||||
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision, IsCmyk = Components.Length == 4 };
|
||||
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata)
|
||||
{
|
||||
BitsPerSample = Precision,
|
||||
IsCmyk = Components.Length == 4,
|
||||
DecodeWorkingBytes = Height == 0 ? 0 : WorkingBytes(Progressive, 0),
|
||||
};
|
||||
}
|
||||
|
||||
public JpegCoefficients ToCoefficients()
|
||||
@@ -478,6 +483,34 @@ internal sealed partial class JpegFile : IDisposable
|
||||
|
||||
private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor;
|
||||
|
||||
/// <summary>
|
||||
/// The working memory <see cref="Allocate"/> asks of the limits: the sample planes (reduced by
|
||||
/// <paramref name="scaleShift"/>), the coefficients when kept (a progressive file), the samples of a lossless one.
|
||||
/// </summary>
|
||||
private long WorkingBytes(bool keepCoefficients, int scaleShift)
|
||||
{
|
||||
long bytes = 0;
|
||||
foreach (var c in Components)
|
||||
{
|
||||
var unit = Lossless ? 1 : 8;
|
||||
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
|
||||
bytes += samples >> (2 * scaleShift);
|
||||
if (keepCoefficients && !Lossless)
|
||||
{
|
||||
bytes += samples * 2;
|
||||
}
|
||||
|
||||
if (Lossless)
|
||||
{
|
||||
// The samples before the point transform, and for arithmetic coding the class of every difference.
|
||||
bytes += samples * (Arithmetic ? 3 : 2);
|
||||
}
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
|
||||
private void ReadDnl(ReadOnlySpan<byte> p)
|
||||
{
|
||||
if (p.Length < 2)
|
||||
@@ -833,25 +866,7 @@ internal sealed partial class JpegFile : IDisposable
|
||||
|
||||
_limits.CheckSize(OutputWidth, OutputHeight);
|
||||
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
|
||||
long bytes = 0;
|
||||
foreach (var c in Components)
|
||||
{
|
||||
var unit = Lossless ? 1 : 8;
|
||||
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
|
||||
bytes += samples >> (2 * _scaleShift);
|
||||
if (keepCoefficients && !Lossless)
|
||||
{
|
||||
bytes += samples * 2;
|
||||
}
|
||||
|
||||
if (Lossless)
|
||||
{
|
||||
// The samples before the point transform, and for arithmetic coding the class of every difference.
|
||||
bytes += samples * (Arithmetic ? 3 : 2);
|
||||
}
|
||||
}
|
||||
|
||||
_limits.CheckWorkingBytes(bytes);
|
||||
_limits.CheckWorkingBytes(WorkingBytes(keepCoefficients, _scaleShift));
|
||||
_pooledArrays = _mode == Mode.Pixels;
|
||||
foreach (var c in Components)
|
||||
{
|
||||
|
||||
@@ -603,13 +603,26 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
|
||||
await using (stream.ConfigureAwait(false))
|
||||
{
|
||||
var (reader, info) = await Task.Run(
|
||||
var knownLength = library.Media.Duration;
|
||||
var (reader, info, length) = await Task.Run(
|
||||
() =>
|
||||
{
|
||||
// «N in tutto» names a frame by its position among the N instants, from the length the job used
|
||||
// (the library's, or the one read from the file when the library has none: ExportService).
|
||||
var probed = knownLength;
|
||||
if (mode == FrameMode.Count && probed is null)
|
||||
{
|
||||
probed = VideoFrameReader.ProbeDuration(stream);
|
||||
stream.Position = 0;
|
||||
}
|
||||
|
||||
var opened = VideoFrameReader.Open(stream, out var found);
|
||||
return (opened, found);
|
||||
return (opened, found, probed);
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
IReadOnlyList<TimeSpan> spread = mode == FrameMode.Count && length is { } d && d > TimeSpan.Zero && count is >= 1 and <= ExportFrames.MaxCount
|
||||
? ExportFrames.Spread(d, count)
|
||||
: [];
|
||||
using (reader)
|
||||
{
|
||||
var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : [];
|
||||
@@ -637,7 +650,11 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
followers[k] = [];
|
||||
var at = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
|
||||
var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, sha, ExportVariant.Frame, format, at);
|
||||
var index = mode == FrameMode.Count ? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue) : k;
|
||||
// The position among the N instants (two on one millisecond are one item: ids skip nothing then);
|
||||
// by the ids only when the instant is not one of them (the library's length changed meanwhile).
|
||||
var index = mode == FrameMode.Count
|
||||
? ExportFrames.IndexOf(spread, batch[k].FrameAt ?? TimeSpan.Zero) ?? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue)
|
||||
: k;
|
||||
var plan = new FramePlan(identity, ExportFrames.Suffix(mode, target.Actual, index, count), null);
|
||||
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
if (current is { State: ExportCopyState.Copied })
|
||||
|
||||
@@ -72,13 +72,16 @@ public static class ExportFrames
|
||||
var instants = new TimeSpan[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
instants[i] = TimeSpan.FromTicks(step.Ticks * i);
|
||||
instants[i] = WholeMs(TimeSpan.FromTicks(step.Ticks * i));
|
||||
}
|
||||
|
||||
return instants;
|
||||
}
|
||||
|
||||
/// <summary>«N in tutto»: (i + ½) · duration / N for i = 0…N − 1, in 100 ns ticks rounded down.</summary>
|
||||
/// <summary>
|
||||
/// «N in tutto»: (i + ½) · duration / N for i = 0…N − 1, rounded up to the millisecond: the item, the preview and
|
||||
/// the download locate the same instant. On a video shorter than N milliseconds neighbours can share one.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
|
||||
{
|
||||
if (count is < 1 or > MaxCount)
|
||||
@@ -90,7 +93,7 @@ public static class ExportFrames
|
||||
var instants = new TimeSpan[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
instants[i] = TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count)));
|
||||
instants[i] = WholeMs(TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))));
|
||||
}
|
||||
|
||||
return instants;
|
||||
@@ -128,6 +131,28 @@ public static class ExportFrames
|
||||
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The position of <paramref name="requested"/> among <paramref name="instants"/> (the first of those on the same
|
||||
/// millisecond, as the items keep them), or null when it is not one of them.
|
||||
/// </summary>
|
||||
public static int? IndexOf(IReadOnlyList<TimeSpan> instants, TimeSpan requested)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instants);
|
||||
var ms = (long)requested.TotalMilliseconds;
|
||||
for (var i = 0; i < instants.Count; i++)
|
||||
{
|
||||
if ((long)instants[i].TotalMilliseconds == ms)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>An instant rounded up to the whole millisecond (never before the instant computed).</summary>
|
||||
private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at));
|
||||
|
||||
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
|
||||
public static long ActualMs(TimeSpan shown) =>
|
||||
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
|
||||
|
||||
@@ -116,15 +116,20 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
/// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts
|
||||
/// once across accounts.
|
||||
/// </summary>
|
||||
/// <param name="lengthOf">
|
||||
/// Frames job: the length of a video the library does not know, read from its file (null when unreadable); without
|
||||
/// it such a video is one planned file without instants (<see cref="PlannedFile.UnknownDuration"/>, the dialog).
|
||||
/// </param>
|
||||
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
|
||||
ExportJobRequest request,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
ExportSettings settings,
|
||||
[EnumeratorCancellation] CancellationToken ct)
|
||||
[EnumeratorCancellation] CancellationToken ct,
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = null)
|
||||
{
|
||||
if (request.Frames is { } frames)
|
||||
{
|
||||
await foreach (var frame in EnumerateFramesAsync(request, frames, effective, ct).ConfigureAwait(false))
|
||||
await foreach (var frame in EnumerateFramesAsync(request, frames, effective, lengthOf, ct).ConfigureAwait(false))
|
||||
{
|
||||
yield return frame;
|
||||
}
|
||||
@@ -237,18 +242,21 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
|
||||
/// <summary>
|
||||
/// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due
|
||||
/// video gives one planned frame per instant of the request. A video of unknown length gives one planned file
|
||||
/// without an instant (<see cref="PlannedFile.UnknownDuration"/>): its instants are found when the job is recorded.
|
||||
/// Frames are not checked for «già copiato» here: the copy looks at each one's exact instant.
|
||||
/// video gives one planned frame per instant of the request. A video of unknown length is measured by
|
||||
/// <paramref name="lengthOf"/> (the job: before anything is recorded, so that its frames count against the caps of
|
||||
/// D12) or, without it, gives one planned file without an instant (<see cref="PlannedFile.UnknownDuration"/>, the
|
||||
/// dialog). One that cannot be read gets one instant, and the copy says «Fotogramma non disponibile per questo
|
||||
/// video». Frames are not checked for «già copiato» here: the copy looks at each one's exact instant.
|
||||
/// </summary>
|
||||
private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync(
|
||||
ExportJobRequest request,
|
||||
ExportFramesRequest frames,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf,
|
||||
[EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var seen = new HashSet<(long Destination, long Account, string Sha256, long Ticks, ExportFormat Format)>();
|
||||
var seen = new HashSet<(long Destination, long Account, string Sha256, long Ms, ExportFormat Format)>();
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
@@ -286,13 +294,27 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
Prediction = ExportPrediction.Converted,
|
||||
FirstOfVideo = true,
|
||||
};
|
||||
if (frames.Mode != FrameMode.At && c.Duration is not { } known)
|
||||
var duration = c.Duration ?? TimeSpan.Zero;
|
||||
if (frames.Mode != FrameMode.At && c.Duration is null)
|
||||
{
|
||||
yield return frame with { UnknownDuration = true };
|
||||
continue;
|
||||
if (lengthOf is null)
|
||||
{
|
||||
yield return frame with { UnknownDuration = true };
|
||||
continue;
|
||||
}
|
||||
|
||||
if (await lengthOf(c, ct).ConfigureAwait(false) is not { } measured || measured <= TimeSpan.Zero)
|
||||
{
|
||||
var unreadable = frame with { FrameAt = TimeSpan.Zero };
|
||||
yield return seen.Add((destination, c.AccountId, c.Sha256!, 0, frames.Format))
|
||||
? unreadable
|
||||
: unreadable with { Action = PlannedCopy.AlreadyCopied };
|
||||
continue;
|
||||
}
|
||||
|
||||
duration = measured;
|
||||
}
|
||||
|
||||
var duration = c.Duration ?? TimeSpan.Zero;
|
||||
if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo)
|
||||
{
|
||||
yield return frame with { Action = PlannedCopy.OverCap };
|
||||
@@ -304,7 +326,8 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
{
|
||||
var planned = frame with { FrameAt = at, FirstOfVideo = first };
|
||||
first = false;
|
||||
if (!seen.Add((destination, c.AccountId, c.Sha256!, at.Ticks, frames.Format)))
|
||||
// By the millisecond the item keeps (ux_export_item_file): two instants on one are one item.
|
||||
if (!seen.Add((destination, c.AccountId, c.Sha256!, (long)at.TotalMilliseconds, frames.Format)))
|
||||
{
|
||||
planned = planned with { Action = PlannedCopy.AlreadyCopied };
|
||||
}
|
||||
|
||||
@@ -167,11 +167,26 @@ public sealed class ExportService : IAsyncDisposable
|
||||
var runs = new Dictionary<long, ExportRun>();
|
||||
var pending = new List<ExportItem>();
|
||||
var exports = _env.Storage.Exports;
|
||||
// Frames job: the videos whose length the library does not know are measured once, in the first pass, so that
|
||||
// their frames count against the caps; the recording pass reuses the lengths (they cannot disagree).
|
||||
var lengths = new Dictionary<long, TimeSpan?>();
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = request.Frames is null
|
||||
? null
|
||||
: async (candidate, token) =>
|
||||
{
|
||||
if (!lengths.TryGetValue(candidate.MediaId, out var length))
|
||||
{
|
||||
length = await ProbeLengthAsync(candidate, token).ConfigureAwait(false);
|
||||
lengths[candidate.MediaId] = length;
|
||||
}
|
||||
|
||||
return length;
|
||||
};
|
||||
if (request.Frames is not null)
|
||||
{
|
||||
// Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all.
|
||||
var count = new PlanTally();
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||
{
|
||||
count.Add(file);
|
||||
}
|
||||
@@ -187,9 +202,10 @@ public sealed class ExportService : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
var frameItems = 0;
|
||||
try
|
||||
{
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||
{
|
||||
tally.Add(file);
|
||||
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
|
||||
@@ -207,24 +223,24 @@ public sealed class ExportService : IAsyncDisposable
|
||||
}
|
||||
|
||||
// Frame items of one video are added together, in instant order (the copy takes them as one batch).
|
||||
IReadOnlyList<TimeSpan?> instants = file.UnknownDuration && request.Frames is { } frames
|
||||
? await FrameInstantsAsync(file.Candidate, frames, ct).ConfigureAwait(false)
|
||||
: [file.FrameAt];
|
||||
foreach (var at in instants)
|
||||
// The first pass already refused more than 20.000: this only guards that it saw the same files.
|
||||
if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest)
|
||||
{
|
||||
pending.Add(new ExportItem
|
||||
{
|
||||
RunId = run.Id,
|
||||
MediaId = file.Candidate.MediaId,
|
||||
AccountId = file.Candidate.AccountId,
|
||||
SourceSha256 = file.Candidate.Sha256,
|
||||
Variant = file.Variant,
|
||||
Format = file.Format,
|
||||
FrameAt = at,
|
||||
State = ExportItemState.Pending,
|
||||
});
|
||||
throw new ArgumentException(TooManyFramesText, nameof(request));
|
||||
}
|
||||
|
||||
pending.Add(new ExportItem
|
||||
{
|
||||
RunId = run.Id,
|
||||
MediaId = file.Candidate.MediaId,
|
||||
AccountId = file.Candidate.AccountId,
|
||||
SourceSha256 = file.Candidate.Sha256,
|
||||
Variant = file.Variant,
|
||||
Format = file.Format,
|
||||
FrameAt = file.FrameAt,
|
||||
State = ExportItemState.Pending,
|
||||
});
|
||||
|
||||
if (pending.Count >= ItemBatch)
|
||||
{
|
||||
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
||||
@@ -299,44 +315,32 @@ public sealed class ExportService : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The instants of a video whose length the library does not know: its headers are read now (only the library
|
||||
/// file, never the destination). A video that cannot be read gets one instant, and the copy says «Fotogramma non
|
||||
/// disponibile per questo video».
|
||||
/// The length of a video the library does not know, from its headers (only the library file, never the
|
||||
/// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells).
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<TimeSpan?>> FrameInstantsAsync(ExportCandidate candidate, ExportFramesRequest frames, CancellationToken ct)
|
||||
private async Task<TimeSpan?> ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct)
|
||||
{
|
||||
TimeSpan? duration = null;
|
||||
var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false);
|
||||
var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false);
|
||||
if (media is not null && account is not null && _env.ResolveSourcePath(account, media) is { } path)
|
||||
if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path)
|
||||
{
|
||||
try
|
||||
{
|
||||
duration = await Task.Run(
|
||||
() =>
|
||||
{
|
||||
using var stream = _env.FileSystem.OpenRandomAccess(path);
|
||||
return VideoFrameReader.ProbeDuration(stream);
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Not readable now: one instant, the copy tells.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (duration is not { } d || d <= TimeSpan.Zero)
|
||||
try
|
||||
{
|
||||
return [TimeSpan.Zero];
|
||||
return await Task.Run(
|
||||
() =>
|
||||
{
|
||||
using var stream = _env.FileSystem.OpenRandomAccess(path);
|
||||
return VideoFrameReader.ProbeDuration(stream);
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (ExportFrames.FrameCount(d, frames) > ExportFrames.MaxPerVideo)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
throw new ArgumentException(ExportFrames.OverCapMessage, nameof(frames));
|
||||
return null; // not readable now: one instant, the copy tells
|
||||
}
|
||||
|
||||
return [.. ExportFrames.Instants(d, frames).Select(at => (TimeSpan?)at)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
@@ -19,24 +20,49 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
|
||||
public const string PausedKey = "esportazione.libreria-sospesa";
|
||||
|
||||
/// <summary>
|
||||
/// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files
|
||||
/// stored in the library from then on (<see cref="Media.DownloadedAt"/>), the others only with «Anche i N».
|
||||
/// </summary>
|
||||
public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal";
|
||||
|
||||
/// <summary>As <see cref="PhotoSinceKey"/>, for videos.</summary>
|
||||
public const string VideoSinceKey = "esportazione.libreria-formato-video-dal";
|
||||
|
||||
private static readonly Lock SignalGate = new();
|
||||
private static TaskCompletionSource _signal = NewSignal();
|
||||
|
||||
/// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
|
||||
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
public Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var (files, bytes) = await storage.Conversions.CountExistingAsync(
|
||||
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct).ConfigureAwait(false);
|
||||
return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked
|
||||
/// about, as when only the other one is being turned on).
|
||||
/// </summary>
|
||||
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false);
|
||||
return new LibraryConversionPreview(files, bytes);
|
||||
}
|
||||
|
||||
/// <summary>«Anche i N già in libreria»: queues the present files that convert, in one statement per kind. Returns how many.</summary>
|
||||
public async Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
/// <summary>«Anche i N già in libreria» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
|
||||
public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var added = await storage.Conversions.EnqueueExistingAsync(
|
||||
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), clock.Now, ct).ConfigureAwait(false);
|
||||
return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds
|
||||
/// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many.
|
||||
/// </summary>
|
||||
public async Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false);
|
||||
if (added > 0)
|
||||
{
|
||||
Signal();
|
||||
@@ -46,7 +72,8 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings changed: a library format turned off or changed loses its queue (its converted files and rows stay).
|
||||
/// The settings changed: a library format turned off or changed loses its queue and its failures that «Riprova»
|
||||
/// would put back (its converted files and rows stay).
|
||||
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
|
||||
/// «Anche i N già in libreria».
|
||||
/// </summary>
|
||||
@@ -57,17 +84,35 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
|
||||
{
|
||||
var old = LibraryConversionRules.FormatFor(kind, before);
|
||||
if (old is { } format && old != LibraryConversionRules.FormatFor(kind, after))
|
||||
var now = LibraryConversionRules.FormatFor(kind, after);
|
||||
if (old == now)
|
||||
{
|
||||
await storage.Conversions.DeletePendingAsync(format, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (old is { } format)
|
||||
{
|
||||
await storage.Conversions.DeleteQueueAsync(format, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
|
||||
var since = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
|
||||
await storage.Settings.SetAsync(SinceKey(kind), since, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>«Riprova»: the failed files go back to the queue, except those that never convert (<c>AsIs*</c>). Returns how many.</summary>
|
||||
/// <summary>
|
||||
/// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert
|
||||
/// (<c>AsIs*</c>). Returns how many.
|
||||
/// </summary>
|
||||
public async Task<int> RetryFailedAsync(CancellationToken ct = default)
|
||||
{
|
||||
var reset = await storage.Conversions.ResetFailedAsync(clock.Now, ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
var formats = new[] { MediaKind.Photo, MediaKind.Video }
|
||||
.Select(kind => LibraryConversionRules.FormatFor(kind, settings))
|
||||
.OfType<ExportFormat>()
|
||||
.ToList();
|
||||
var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false);
|
||||
if (reset > 0)
|
||||
{
|
||||
Signal();
|
||||
@@ -94,8 +139,10 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the present files of an entry by the library formats set now, after its journal line (the hook of
|
||||
/// <see cref="LibraryIngest"/>). Nothing when both formats are «Originale». Returns how many rows were added.
|
||||
/// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
|
||||
/// <see cref="LibraryIngest"/>): those stored in the library since the format was set (<see cref="PhotoSinceKey"/>),
|
||||
/// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included).
|
||||
/// Nothing when both formats are «Originale». Returns how many rows were added.
|
||||
/// </summary>
|
||||
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
|
||||
{
|
||||
@@ -107,7 +154,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
return 0;
|
||||
}
|
||||
|
||||
var requests = LibraryConversionRules.RequestsFor(media, settings);
|
||||
var photoSince = await SinceAsync(storage.Settings, MediaKind.Photo, ct).ConfigureAwait(false);
|
||||
var videoSince = await SinceAsync(storage.Settings, MediaKind.Video, ct).ConfigureAwait(false);
|
||||
var requests = LibraryConversionRules.RequestsFor(
|
||||
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|
||||
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
|
||||
settings);
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
@@ -122,6 +174,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
return added;
|
||||
}
|
||||
|
||||
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
|
||||
|
||||
/// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary>
|
||||
private static async Task<long?> SinceAsync(ISettingsStore settings, MediaKind kind, CancellationToken ct) =>
|
||||
long.TryParse(await settings.GetAsync(SinceKey(kind), ct).ConfigureAwait(false), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
|
||||
|
||||
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
|
||||
public static void Signal()
|
||||
{
|
||||
|
||||
@@ -245,6 +245,15 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
|
||||
// Only in the library format set now (§4.10, Q29): a row left in a format turned off or changed (put back by a
|
||||
// supersession, say) is dropped, never converted.
|
||||
var settings = await ExportSettings.LoadAsync(storage.Settings, token).ConfigureAwait(false);
|
||||
if (LibraryConversionRules.FormatFor(media.Kind, settings) != row.Format)
|
||||
{
|
||||
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
|
||||
var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false);
|
||||
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
|
||||
if (entry is null || account is null)
|
||||
@@ -269,6 +278,13 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
// A disk already below the threshold stays below it with the file: the pause starts before the original is read
|
||||
// (hashed, decoded or remuxed) again at every wake-up (D17). The exact check with the file's length follows.
|
||||
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before))
|
||||
{
|
||||
return Outcome.LowSpace;
|
||||
}
|
||||
|
||||
var source = media.Sha256.ToLowerInvariant();
|
||||
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
|
||||
{
|
||||
|
||||
@@ -136,25 +136,26 @@ public static class MediaConverter
|
||||
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
|
||||
}
|
||||
|
||||
var converted = await throttle.RunAsync(token =>
|
||||
var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) =>
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
return ImageConverter.Convert(bytes, format);
|
||||
return (ImageConverter.Convert(bytes, format), null);
|
||||
}
|
||||
catch (ImageLimitException)
|
||||
{
|
||||
return null;
|
||||
// Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge».
|
||||
return (null, ImageConversionLosses.AsIsTooLarge);
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return null;
|
||||
return (null, ImageConversionLosses.AsIsNotDecodable);
|
||||
}
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (converted is null)
|
||||
{
|
||||
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsNotDecodable]);
|
||||
return Whole(bytes, extension, sha, [refusal!]);
|
||||
}
|
||||
|
||||
var data = converted.Data;
|
||||
|
||||
@@ -283,14 +283,11 @@ public sealed class DownloadDuplicateReview(
|
||||
|
||||
var folder = layout.AccountFolder(account);
|
||||
|
||||
// Its converted files of the library (tappa E3) go with it: the queue and the failures are dropped, the rows
|
||||
// with a file become «Tolto». No supersession for the loser.
|
||||
var conversions = await storage.Conversions.ListByMediaAsync(media.Id, ct).ConfigureAwait(false);
|
||||
var withFiles = conversions
|
||||
.Where(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null)
|
||||
.ToList();
|
||||
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
|
||||
await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
|
||||
// Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue
|
||||
// and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the
|
||||
// worker records meanwhile is among them). No supersession for the loser.
|
||||
var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
|
||||
var withFiles = removed.Where(LibraryDeletion.HasFile).ToList();
|
||||
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
|
||||
hashIndex?.Remove(media.Id);
|
||||
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
|
||||
|
||||
@@ -65,9 +65,6 @@ public sealed class LibraryDeletion(
|
||||
var folder = layout.AccountFolder(account);
|
||||
var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
|
||||
|
||||
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
|
||||
var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false);
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
// From here the deletion goes to the end: a half-done deletion is worse than a late one.
|
||||
@@ -75,16 +72,12 @@ public sealed class LibraryDeletion(
|
||||
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
IReadOnlyList<MediaConversion> withFiles;
|
||||
if (mode == DeletionMode.Remember)
|
||||
{
|
||||
withFiles = conversions.Where(HasFile).ToList();
|
||||
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList();
|
||||
}
|
||||
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
|
||||
// Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them.
|
||||
var removed = mode == DeletionMode.Remember
|
||||
? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false)
|
||||
: await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false);
|
||||
IReadOnlyList<MediaConversion> withFiles = removed.Where(HasFile).ToList();
|
||||
|
||||
foreach (var media in stored.Media)
|
||||
{
|
||||
@@ -141,7 +134,7 @@ public sealed class LibraryDeletion(
|
||||
}
|
||||
|
||||
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
|
||||
private static bool HasFile(MediaConversion c) =>
|
||||
internal static bool HasFile(MediaConversion c) =>
|
||||
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -373,7 +373,8 @@ public sealed class LibraryIngest(
|
||||
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line.
|
||||
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
|
||||
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
|
||||
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -83,8 +83,10 @@ public sealed class VideoFrameReader : IDisposable
|
||||
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
|
||||
}
|
||||
|
||||
// Samples shown before the start (cut by the edit list) are not chosen, unless nothing else is.
|
||||
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0).ToArray();
|
||||
// Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless
|
||||
// nothing else is.
|
||||
var end = video.EditSegmentDuration is { } segment && segment > 0 ? video.EmptyEditDuration + segment : long.MaxValue;
|
||||
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0 && shown[i] < end).ToArray();
|
||||
order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)];
|
||||
Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
|
||||
}
|
||||
|
||||
@@ -67,6 +67,14 @@ public interface IEntryStore
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Elimina dalla libreria» with memory: as <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>,
|
||||
/// and in the same transaction every conversion of its files with a file (Converted, Superseded) becomes «Tolto»
|
||||
/// and is returned as it was: chosen inside the transaction, so a conversion recorded just before is among them
|
||||
/// (its file is the caller's to delete) and none can be recorded after. The queue and the failures go.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaConversion>> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions
|
||||
/// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with
|
||||
|
||||
@@ -50,10 +50,12 @@ public interface IMediaConversionStore
|
||||
Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// A library file left its entry («Tieni il più grande» on a file of a series): its queue and failures go, its rows
|
||||
/// with a file become «Tolto», in one transaction. Returns the rows marked «Tolto».
|
||||
/// A library file leaves its entry («Tieni il più grande» on a file of a series), in one transaction: the file
|
||||
/// becomes <see cref="MediaState.Deleted"/>, its queue and failures go, its rows with a file become «Tolto». Returns
|
||||
/// those rows as they were (chosen inside the transaction: their files are the caller's to delete). The state of
|
||||
/// the entry is the caller's to recompute.
|
||||
/// </summary>
|
||||
Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10
|
||||
@@ -63,8 +65,11 @@ public interface IMediaConversionStore
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The setting of a format went off or changed: its queue is emptied (Converted rows and their files stay).</summary>
|
||||
Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default);
|
||||
/// <summary>
|
||||
/// The setting of a format went off or changed: its queue is emptied, with its failures that «Riprova» would put
|
||||
/// back (Converted rows and their files stay, and so do the <c>AsIs*</c> verdicts). Returns how many rows went.
|
||||
/// </summary>
|
||||
Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
|
||||
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
|
||||
@@ -97,8 +102,11 @@ public interface IMediaConversionStore
|
||||
/// </summary>
|
||||
Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Riprova»: Failed rows go back to Pending, except those with an <c>AsIs*</c> code (they never convert). Returns how many.</summary>
|
||||
Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default);
|
||||
/// <summary>
|
||||
/// «Riprova»: Failed rows in <paramref name="formats"/> (the library formats set now) go back to Pending, except those
|
||||
/// with an <c>AsIs*</c> code (they never convert). Returns how many.
|
||||
/// </summary>
|
||||
Task<int> ResetFailedAsync(IReadOnlyCollection<ExportFormat> formats, DateTimeOffset at, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>One file to queue in one format, made from these bytes.</summary>
|
||||
|
||||
Reference in new issue
Block a user