Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Support video thumbnails and robust cross-platform file opening

gtxPrimeeff90bde791a
diff --git a/src/Filee.App/Services/HistoryThumbnails.cs b/src/Filee.App/Services/HistoryThumbnails.cs
index 6f1c36e5..940fb581 100644
--- a/src/Filee.App/Services/HistoryThumbnails.cs
+++ b/src/Filee.App/Services/HistoryThumbnails.cs
@@ -1,12 +1,17 @@
-// Small square pictures of converted files for the Home page's recent conversions. Skia decodes them off the UI
+// Small square pictures of converted files for the Home page's recent conversions. Skia decodes images off the UI
// thread, at a fraction of the picture's size where the format allows it (JPEG, WebP), from a copy of the file read in
-// one go, so the file is held open only while it is read and others may still write, rename or delete it meanwhile. A
-// small cache keeps them while the files don't change: a search lists the same conversions again at once.
+// one go, so the file is held open only while it is read and others may still write, rename or delete it meanwhile.
+// Video formats (MP4, MKV, WebM, etc.) have a representative frame extracted via FFmpeg off the UI thread without
+// locking the file. A small cache keeps them while the files don't change: a search lists the same conversions again at once.
+using System.Diagnostics;
+using System.Globalization;
using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
+using Filee.Core.Formats;
using Filee.Core.Platform;
+using Filee.Engines.Media;
using SkiaSharp;
namespace Filee.App.Services;
@@ -16,7 +21,7 @@ internal static class HistoryThumbnails
/// <summary>Width and height in pixels: the card shows it at 42, so this is sharp up to 200 % scaling.</summary>
public const int Size = 96;
- /// <summary>Larger files are not read: the card shows their format instead.</summary>
+ /// <summary>Larger image files are not read: the card shows their format instead.</summary>
internal const long MaxFileBytes = 64L * 1024 * 1024;
/// <summary>
@@ -38,8 +43,15 @@ internal static class HistoryThumbnails
private static readonly Dictionary<string, Entry> Cache = new(FileSystemPaths.Comparer);
private static readonly Lock CacheLock = new();
- /// <summary>Whether <paramref name="path"/> is a picture a thumbnail can be made of (by its extension only).</summary>
- public static bool CanShow(string path) => Readable.Contains(Path.GetExtension(path).TrimStart('.'));
+ /// <summary>Whether <paramref name="path"/> is a picture or video a thumbnail can be made of (by its extension only).</summary>
+ public static bool CanShow(string path)
+ {
+ var ext = Path.GetExtension(path).TrimStart('.');
+ return Readable.Contains(ext) || IsVideo(ext);
+ }
+
+ internal static bool IsVideo(string ext) =>
+ FormatRegistry.FindByExtension(ext)?.Category == FormatCategory.Video;
/// <summary>The thumbnail made last time for <paramref name="path"/>, without looking at the file.</summary>
public static Bitmap? Cached(string path)
@@ -50,7 +62,7 @@ internal static class HistoryThumbnails
/// <summary>
/// The thumbnail of <paramref name="path"/>, from the cache while the file is unchanged. Null when the file is gone,
- /// too large or not a picture Skia reads. Reads the disk: never call it on the UI thread.
+ /// too large or not a picture/video Filee reads. Reads the disk: never call it on the UI thread.
/// </summary>
public static Bitmap? Load(string path)
{
@@ -74,8 +86,14 @@ internal static class HistoryThumbnails
return hit.Bitmap;
}
+ var ext = Path.GetExtension(path).TrimStart('.');
+ var isVideo = IsVideo(ext);
// A file that can't be read is remembered too, so a search doesn't try it again on every key.
- var bitmap = length <= MaxFileBytes ? Decode(path, MaxDecodedPixels) : null;
+ // Image files larger than MaxFileBytes are skipped to conserve memory; videos are seeked by FFmpeg directly.
+ var bitmap = isVideo
+ ? (length > 0 ? DecodeVideo(path, MaxDecodedPixels) : null)
+ : (length <= MaxFileBytes ? Decode(path, MaxDecodedPixels) : null);
+
lock (CacheLock)
{
if (Cache.Count >= CacheSize)
@@ -85,6 +103,105 @@ internal static class HistoryThumbnails
return bitmap;
}
+ /// <summary>
+ /// Extracts a representative frame of video <paramref name="path"/> using FFmpeg and decodes it into a <see cref="Size"/> square.
+ /// Null when FFmpeg is unavailable, video is broken, or frame decoding fails.
+ /// </summary>
+ internal static Bitmap? DecodeVideo(string path, long maxPixels)
+ {
+ var ffmpeg = FfmpegConverter.Locate()?.Ffmpeg;
+ if (ffmpeg is null || !File.Exists(ffmpeg))
+ return null;
+
+ // Try seeking to 1s first (avoids blank/black title frame), then fall back to the beginning (e.g. videos shorter than 1s).
+ var frameBytes = ExtractVideoFrame(ffmpeg, path, seekSeconds: 1)
+ ?? ExtractVideoFrame(ffmpeg, path, seekSeconds: null);
+ if (frameBytes is null || frameBytes.Length == 0)
+ return null;
+
+ try
+ {
+ using var data = SKData.CreateCopy(frameBytes);
+ using var codec = SKCodec.Create(data);
+ if (codec is null || codec.Info.Width <= 0 || codec.Info.Height <= 0)
+ return null;
+
+ var scale = Math.Min(1f, (float)Size / Math.Min(codec.Info.Width, codec.Info.Height));
+ var scaled = codec.GetScaledDimensions(scale);
+ if (scaled.Width <= 0 || scaled.Height <= 0 || (long)scaled.Width * scaled.Height > maxPixels)
+ return null;
+
+ var info = new SKImageInfo(scaled.Width, scaled.Height, SKColorType.Bgra8888, SKAlphaType.Premul);
+ using var decoded = new SKBitmap(info);
+ if (codec.GetPixels(info, decoded.GetPixels()) is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
+ return null;
+
+ return Square(decoded, codec.EncodedOrigin);
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ private static byte[]? ExtractVideoFrame(string ffmpeg, string path, int? seekSeconds)
+ {
+ try
+ {
+ var psi = new ProcessStartInfo(ffmpeg)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ };
+ psi.ArgumentList.Add("-hide_banner");
+ psi.ArgumentList.Add("-nostdin");
+ psi.ArgumentList.Add("-v");
+ psi.ArgumentList.Add("error");
+ if (seekSeconds.HasValue)
+ {
+ psi.ArgumentList.Add("-ss");
+ psi.ArgumentList.Add(seekSeconds.Value.ToString(CultureInfo.InvariantCulture));
+ }
+ psi.ArgumentList.Add("-i");
+ psi.ArgumentList.Add(Path.GetFullPath(path));
+ psi.ArgumentList.Add("-frames:v");
+ psi.ArgumentList.Add("1");
+ psi.ArgumentList.Add("-f");
+ psi.ArgumentList.Add("image2");
+ psi.ArgumentList.Add("-c:v");
+ psi.ArgumentList.Add("png");
+ psi.ArgumentList.Add("pipe:1");
+
+ using var process = new Process { StartInfo = psi };
+ if (!process.Start())
+ return null;
+
+ using var ms = new MemoryStream();
+ var copyOut = process.StandardOutput.BaseStream.CopyToAsync(ms);
+ var discardErr = process.StandardError.BaseStream.CopyToAsync(Stream.Null);
+
+ if (!process.WaitForExit(5_000))
+ {
+ try
+ {
+ if (!process.HasExited)
+ process.Kill(entireProcessTree: true);
+ }
+ catch { }
+ return null;
+ }
+
+ copyOut.GetAwaiter().GetResult();
+ return process.ExitCode == 0 && ms.Length > 0 ? ms.ToArray() : null;
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
/// <summary>
/// Decodes <paramref name="path"/> into a <see cref="Size"/> square: upright (the EXIF orientation applied) and
/// cropped from the middle. Null when it can't, or would have to decode more than <paramref name="maxPixels"/>.
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
index e5b06141..990a1415 100644
--- a/src/Filee.App/ViewModels/JobViewModel.cs
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -134,7 +134,15 @@ public sealed partial class JobViewModel : ObservableObject
{
var first = Job.Outputs.FirstOrDefault();
if (first is not null)
- _platform.RevealInFileManager(first);
+ {
+ try
+ {
+ _platform.RevealInFileManager(first);
+ }
+ catch
+ {
+ }
+ }
}
[RelayCommand]
diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
index c55d3540..54eb8295 100644
--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
@@ -283,7 +283,16 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable
}
[RelayCommand]
- private void OpenDataFolder() => _platform.RevealInFileManager(_store.Directory);
+ private void OpenDataFolder()
+ {
+ try
+ {
+ _platform.RevealInFileManager(_store.Directory);
+ }
+ catch
+ {
+ }
+ }
public void Export(string path)
{
diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
index 447facf1..81d345f6 100644
--- a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
@@ -106,21 +106,53 @@ public sealed partial class HistoryItemViewModel : ObservableObject
{
// An output may be a folder ("Extract"): revealing it opens the extracted files.
if (_output is not null && ConversionService.Exists(_output))
- _platform.RevealInFileManager(_output);
+ {
+ try
+ {
+ _platform.RevealInFileManager(_output);
+ }
+ catch
+ {
+ }
+ }
}
[RelayCommand]
private void OpenFile()
{
if (CanOpen && ConversionService.Exists(_output!))
- _platform.OpenFile(_output!);
+ {
+ try
+ {
+ _platform.OpenFile(_output!);
+ }
+ catch
+ {
+ // Fall back to opening the containing folder with the file highlighted if the OS has no registered handler.
+ try
+ {
+ _platform.RevealInFileManager(_output!);
+ }
+ catch
+ {
+ }
+ }
+ }
}
[RelayCommand]
private void OpenWith()
{
if (CanOpenWith && File.Exists(_output))
- _platform.OpenWith(_output!);
+ {
+ try
+ {
+ _platform.OpenWith(_output!);
+ }
+ catch
+ {
+ }
+ }
}
}
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
index ebb8d640..e044cbf2 100644
--- a/src/Filee.Core/Platform/IPlatformServices.cs
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -174,9 +174,15 @@ public sealed class NullPlatformServices : IPlatformServices
private static void Open(string path)
{
+ if (OperatingSystem.IsWindows())
+ {
+ var start = new System.Diagnostics.ProcessStartInfo(Path.GetFullPath(path)) { UseShellExecute = true };
+ System.Diagnostics.Process.Start(start)?.Dispose();
+ return;
+ }
var opener = OperatingSystem.IsMacOS() ? "open" : "xdg-open";
- var start = new System.Diagnostics.ProcessStartInfo(opener) { UseShellExecute = false };
- start.ArgumentList.Add(path);
- System.Diagnostics.Process.Start(start)?.Dispose();
+ var startUnix = new System.Diagnostics.ProcessStartInfo(opener) { UseShellExecute = false };
+ startUnix.ArgumentList.Add(path);
+ System.Diagnostics.Process.Start(startUnix)?.Dispose();
}
}
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index a0219929..ca144acd 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -38,6 +38,7 @@
<ItemGroup>
<InternalsVisibleTo Include="Filee" />
<InternalsVisibleTo Include="Filee.Engines.Tests" />
+ <InternalsVisibleTo Include="Filee.App.Tests" />
</ItemGroup>
<ItemGroup>
diff --git a/tests/Filee.App.Tests/RecentConversionTests.cs b/tests/Filee.App.Tests/RecentConversionTests.cs
index 2cad57ef..121d8e26 100644
--- a/tests/Filee.App.Tests/RecentConversionTests.cs
+++ b/tests/Filee.App.Tests/RecentConversionTests.cs
@@ -94,7 +94,15 @@ public class RecentConversionTests
File.WriteAllBytes(broken, [0x89, 0x50, 0x4E, 0x47, 1, 2, 3]);
Assert.Null(HistoryThumbnails.Load(broken));
+ var brokenVideo = Path.Combine(folder, "broken.mp4");
+ File.WriteAllBytes(brokenVideo, [0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70]);
+ Assert.Null(HistoryThumbnails.Load(brokenVideo));
+
Assert.True(HistoryThumbnails.CanShow(@"C:\a\photo.JPG"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\clip.mp4"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\movie.MKV"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\sample.webm"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\phone.MOV"));
Assert.False(HistoryThumbnails.CanShow(@"C:\a\report.pdf"));
Assert.False(HistoryThumbnails.CanShow(@"C:\a\folder"));
}
@@ -104,6 +112,53 @@ public class RecentConversionTests
}
}
+ [AvaloniaFact]
+ public void A_video_generates_a_thumbnail_when_ffmpeg_is_available()
+ {
+ var tools = Filee.Engines.Media.FfmpegConverter.Locate();
+ if (tools is null)
+ return;
+
+ var folder = Directory.CreateTempSubdirectory("filee-videothumbs-").FullName;
+ try
+ {
+ var video = Path.Combine(folder, "sample.mp4");
+ // Create a short 2-second video with FFmpeg
+ var psi = new System.Diagnostics.ProcessStartInfo(tools.Value.Ffmpeg)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ };
+ psi.ArgumentList.Add("-hide_banner");
+ psi.ArgumentList.Add("-nostdin");
+ psi.ArgumentList.Add("-v");
+ psi.ArgumentList.Add("error");
+ psi.ArgumentList.Add("-y");
+ psi.ArgumentList.Add("-f");
+ psi.ArgumentList.Add("lavfi");
+ psi.ArgumentList.Add("-i");
+ psi.ArgumentList.Add("testsrc=duration=2:size=320x240:rate=10");
+ psi.ArgumentList.Add(video);
+
+ using var process = System.Diagnostics.Process.Start(psi);
+ Assert.NotNull(process);
+ Assert.True(process.WaitForExit(10_000));
+ Assert.Equal(0, process.ExitCode);
+ Assert.True(File.Exists(video));
+
+ var thumbnail = HistoryThumbnails.Load(video);
+ Assert.NotNull(thumbnail);
+ Assert.Equal(new PixelSize(HistoryThumbnails.Size, HistoryThumbnails.Size), thumbnail.PixelSize);
+ Assert.Same(thumbnail, HistoryThumbnails.Cached(video));
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
[AvaloniaTheory]
[InlineData(true)]
[InlineData(false)]