using System.Windows.Media;
using System.Windows.Media.Imaging;
using Chronos.Core.Diagnostics;
using Chronos.Core.Imaging;
using Chronos.Ui.Visuals;
namespace Chronos.App.Editor;
/// Linear-light frames as frozen sRGB bitmaps the UI thread can show (created on any thread).
public static class EditorImages
{
public static BitmapSource ToBitmap(ImageBuffer image)
{
ArgumentNullException.ThrowIfNull(image);
var channels = int.Min(3, image.Channels);
var pixels = PixelConvert.ToInterleaved8(image, channels);
var format = channels == 1 ? PixelFormats.Gray8 : PixelFormats.Rgb24;
var bitmap = BitmapSource.Create(image.Width, image.Height, 96, 96, format, null, pixels, image.Width * channels);
bitmap.Freeze();
return bitmap;
}
/// A waveform as an opacity mask (white, alpha = density) so the view paints it in a theme brush.
public static BitmapSource ToMask(LumaWaveform waveform)
{
ArgumentNullException.ThrowIfNull(waveform);
var pixels = new byte[waveform.Density.Length * 4];
for (var i = 0; i < waveform.Density.Length; i++)
{
var alpha = waveform.Density[i];
pixels[4 * i] = pixels[4 * i + 1] = pixels[4 * i + 2] = pixels[4 * i + 3] = alpha;
}
var bitmap = BitmapSource.Create(waveform.Columns, waveform.Rows, 96, 96, PixelFormats.Pbgra32, null, pixels, waveform.Columns * 4);
bitmap.Freeze();
return bitmap;
}
}
///
/// Filmstrip thumbnails decoded through the editor's (embedded previews when large
/// enough), at most a few at a time so scrolling the strip never floods the decoders.
///
public sealed class EditorThumbnails(ISequenceSource source, int count) : IThumbnailSource
{
private readonly SemaphoreSlim _decoders = new(int.Clamp(Environment.ProcessorCount / 2, 2, 6));
private int _pending;
public int Count { get; } = count;
/// Thumbnails requested and not yet returned (capture and tests wait for them).
public int Pending => Volatile.Read(ref _pending);
public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _pending);
try
{
return await DecodeAsync(index, pixelWidth, cancellationToken);
}
finally
{
Interlocked.Decrement(ref _pending);
}
}
private async Task DecodeAsync(int index, int pixelWidth, CancellationToken cancellationToken)
{
await _decoders.WaitAsync(cancellationToken);
try
{
// Long edge for frames up to 16:9 tall or wide; the cache rounds requests, so nearby widths share a decode.
using var frame = await source.DecodeAsync(index, int.Clamp(pixelWidth, 32, 512), DecodePurpose.Thumbnail, cancellationToken);
return frame is null ? null : EditorImages.ToBitmap(frame);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Log.Debug("editor", $"No thumbnail for frame {index}: {ex.Message}");
return null;
}
finally
{
_decoders.Release();
}
}
}