Files

260 lines
9.7 KiB
C#

using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Import.Support;
/// <summary>Bytes of test media written by hand: JPEGs with an EXIF date, PNGs with eXIf, MP4/MOV headers.</summary>
internal static class ImportTestFiles
{
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>A generated photo as JPEG.</summary>
public static byte[] Photo(int scene, int width = 800, int height = 600, int quality = 88)
{
using var bitmap = TestImages.Scene(scene, width, height);
return TestImages.Jpeg(bitmap, quality);
}
/// <summary>
/// A TIFF structure (big or little endian) with IFD0 → Exif IFD holding DateTimeOriginal and/or CreateDate and an
/// optional OffsetTimeOriginal: the content of an EXIF block after «Exif\0\0».
/// </summary>
public static byte[] Tiff(string? dateTimeOriginal, string? createDate = null, string? offsetOriginal = null, bool littleEndian = false)
{
var tags = new List<(ushort Tag, string Value)>();
if (dateTimeOriginal is not null)
{
tags.Add((0x9003, dateTimeOriginal));
}
if (createDate is not null)
{
tags.Add((0x9004, createDate));
}
if (offsetOriginal is not null)
{
tags.Add((0x9011, offsetOriginal));
}
tags.Sort((a, b) => a.Tag.CompareTo(b.Tag));
var buffer = new byte[1024];
var span = buffer.AsSpan();
void U16(int at, ushort v)
{
if (littleEndian)
{
BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(at), v);
}
else
{
BinaryPrimitives.WriteUInt16BigEndian(buffer.AsSpan(at), v);
}
}
void U32(int at, uint v)
{
if (littleEndian)
{
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(at), v);
}
else
{
BinaryPrimitives.WriteUInt32BigEndian(buffer.AsSpan(at), v);
}
}
(littleEndian ? "II"u8 : "MM"u8).CopyTo(span);
U16(2, 42);
U32(4, 8);
// IFD0 at 8: one entry, the Exif IFD pointer.
U16(8, 1);
U16(10, 0x8769);
U16(12, 4); // LONG
U32(14, 1);
const int exifIfd = 26;
U32(18, exifIfd);
U32(22, 0); // no next IFD
// Exif IFD at 26: the ASCII tags, values after the IFD.
U16(exifIfd, (ushort)tags.Count);
var valueAt = exifIfd + 2 + (tags.Count * 12) + 4;
for (var i = 0; i < tags.Count; i++)
{
var at = exifIfd + 2 + (i * 12);
var bytes = Encoding.ASCII.GetBytes(tags[i].Value + "\0");
U16(at, tags[i].Tag);
U16(at + 2, 2); // ASCII
U32(at + 4, (uint)bytes.Length);
if (bytes.Length <= 4)
{
bytes.CopyTo(span[(at + 8)..]);
}
else
{
U32(at + 8, (uint)valueAt);
bytes.CopyTo(span[valueAt..]);
valueAt += bytes.Length;
}
}
U32(exifIfd + 2 + (tags.Count * 12), 0);
return buffer[..valueAt];
}
/// <summary>Inserts an APP1 «Exif» segment with the given TIFF block right after the SOI marker of a JPEG.</summary>
public static byte[] JpegWithExif(byte[] jpeg, byte[] tiff)
{
var length = 2 + 6 + tiff.Length;
var app1 = new byte[2 + length];
app1[0] = 0xFF;
app1[1] = 0xE1;
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), (ushort)length);
"Exif\0\0"u8.CopyTo(app1.AsSpan(4));
tiff.CopyTo(app1.AsSpan(10));
return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)];
}
/// <summary>A generated JPEG photo with DateTimeOriginal «yyyy:MM:dd HH:mm:ss» written by hand.</summary>
public static byte[] PhotoWithExifDate(int scene, DateTime local, string? offset = null, int width = 800, int height = 600) =>
JpegWithExif(Photo(scene, width, height), Tiff(local.ToString("yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), offsetOriginal: offset));
/// <summary>A PNG with an eXIf chunk inserted before the image data.</summary>
public static byte[] PngWithExif(byte[] png, byte[] tiff)
{
// After the signature (8) comes IHDR (8 + 13 + 4 = 25 bytes).
var chunk = new byte[12 + tiff.Length];
BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)tiff.Length);
"eXIf"u8.CopyTo(chunk.AsSpan(4));
tiff.CopyTo(chunk.AsSpan(8));
// CRC left at zero: readers of dates do not check it.
return [.. png.AsSpan(0, 33), .. chunk, .. png.AsSpan(33)];
}
/// <summary>
/// A minimal ISO media file: ftyp, then (or after the media data) a moov with mvhd and a video tkhd. The payload
/// makes each file different.
/// </summary>
public static byte[] Mp4(
DateTimeOffset? createdAt,
int width = 1080,
int height = 1920,
int durationMs = 15_000,
int payloadSeed = 1,
string brand = "isom",
bool moovAtEnd = false,
bool rotated = false,
bool withFtyp = true)
{
using var output = new MemoryStream();
if (withFtyp)
{
WriteBox(output, "ftyp", [.. Encoding.ASCII.GetBytes(brand), 0, 0, 2, 0, .. Encoding.ASCII.GetBytes("isommp41")]);
}
var payload = new byte[4096];
new Random(payloadSeed).NextBytes(payload);
var mvhd = new byte[100];
var creation = createdAt is { } c ? (uint)(c - Epoch1904).TotalSeconds : 0u;
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(4), creation);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(8), creation);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(12), 1000);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(16), (uint)durationMs);
var tkhd = new byte[84];
tkhd[3] = 3; // enabled, in movie
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(4), creation);
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(12), 1);
var matrix = tkhd.AsSpan(40, 36);
int[] values = rotated ? [0, 0x10000, 0, -0x10000, 0, 0, 0, 0, 0x40000000] : [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];
for (var i = 0; i < 9; i++)
{
BinaryPrimitives.WriteInt32BigEndian(matrix[(i * 4)..], values[i]);
}
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(76), (uint)width << 16);
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(80), (uint)height << 16);
using var trak = new MemoryStream();
WriteBox(trak, "tkhd", tkhd);
using var moov = new MemoryStream();
WriteBox(moov, "mvhd", mvhd);
WriteBox(moov, "trak", trak.ToArray());
if (moovAtEnd)
{
WriteBox(output, "mdat", payload);
WriteBox(output, "moov", moov.ToArray());
}
else
{
WriteBox(output, "moov", moov.ToArray());
WriteBox(output, "mdat", payload);
}
return output.ToArray();
}
/// <summary>Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing.</summary>
public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt)
{
var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists);
if (ffmpeg is null)
{
return false;
}
var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false };
foreach (var argument in new[]
{
"-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x3366aa:s=64x48:d=1:r=10",
"-metadata", "creation_time=" + createdAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "Z",
"-c:v", "mpeg4", "-f", "mp4", path,
})
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
process.StandardError.ReadToEnd();
process.WaitForExit(30_000);
return process.ExitCode == 0 && File.Exists(path);
}
/// <summary>The PNG encoding of a generated scene.</summary>
public static byte[] Png(int scene, int width = 400, int height = 300)
{
using var bitmap = TestImages.Scene(scene, width, height);
return TestImages.Png(bitmap);
}
/// <summary>A resized and recompressed copy of a scene (a probable duplicate).</summary>
public static byte[] Resized(int scene, int width, int height, int targetWidth, int targetHeight, int quality = 60)
{
using var bitmap = TestImages.Scene(scene, width, height);
using var smaller = TestImages.Resize(bitmap, targetWidth, targetHeight);
return TestImages.Jpeg(smaller, quality);
}
/// <summary>A crop of a scene: the top-left quarter (not a duplicate).</summary>
public static byte[] Cropped(int scene, int width, int height)
{
using var bitmap = TestImages.Scene(scene, width, height);
using var crop = TestImages.Crop(bitmap, new SKRectI(0, 0, width / 2, height / 2));
return TestImages.Jpeg(crop, 88);
}
private static void WriteBox(Stream output, string type, byte[] body)
{
Span<byte> header = stackalloc byte[8];
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(body.Length + 8));
Encoding.ASCII.GetBytes(type).CopyTo(header[4..]);
output.Write(header);
output.Write(body);
}
}