Improved reading and writing large Office files without copying them into memory (#1243)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-28 23:03:30 +01:00
1 parent 918572c158
commit dbe609a9a7
37 files changed
+1161 -471

No files matched your search

@@ -1,13 +1,19 @@
using System.IO.Compression;
using AIStudio.Tests.Tools.OpenXml;
using AIStudio.Tools.PowerPoint;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools.PowerPoint;
/// <summary>
/// Checks that a presentation file comes about without anything next to the file the user chose.
/// Checks that a presentation file comes about without anything next to the file the user chose, and without its
/// template or its pictures in memory.
/// </summary>
/// <remarks>
/// Inside the Flatpak, the save dialog grants access to exactly the chosen file. A temporary file next
@@ -27,6 +33,16 @@ public sealed class PresentationFileTests
private static readonly byte[] PREVIOUS_CONTENT = [1, 2, 3];
/// <summary>
/// A video of a template, large enough that the update mode of ZipArchive would show in the allocations.
/// </summary>
private const int VIDEO_SIZE = 32 * 1024 * 1024;
private static readonly SlotBounds PICTURE_BOUNDS = new(6_200_000, 1_825_625, 5_150_000, 3_500_000);
private static readonly byte[] TEMPLATE_PICTURE = [11, 12, 13];
private static readonly byte[] SAMPLE_PICTURE = [21, 22, 23];
private static readonly byte[] PHOTO = [31, 32, 33, 34];
private string templateFolder = string.Empty;
private string targetFolder = string.Empty;
@@ -47,7 +63,7 @@ public sealed class PresentationFileTests
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var temporaryFiles = TemporaryFiles();
var stagedFiles = StagingFolder.Files();
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, BasisOf(templatePath), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
@@ -57,7 +73,7 @@ public sealed class PresentationFileTests
Assert.That(result.IsWritten, Is.True);
Assert.That(Directory.GetFileSystemEntries(this.targetFolder), Is.EqualTo(new[] { targetPath }), "Nothing else came about next to the chosen file.");
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The chosen file holds the presentation instead of what it held before.");
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
@@ -67,7 +83,7 @@ public sealed class PresentationFileTests
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var temporaryFiles = TemporaryFiles();
var stagedFiles = StagingFolder.Files();
// Without a basis, nothing is known to fit, as after a change of the template:
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, new Dictionary<string, string>(), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
@@ -77,7 +93,7 @@ public sealed class PresentationFileTests
{
Assert.That(result.IsWritten, Is.False);
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT));
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
@@ -93,7 +109,91 @@ public sealed class PresentationFileTests
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was copied before it was written over.");
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was read completely before it was written over.");
}
}
[Test]
public async Task APictureWhichFailsLeavesNothingBehind()
{
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var deck = new SlideDeckSpec("Mars", [new SlideSpec("L2", false, "Why Mars", string.Empty, [], [], [1, 2], null)]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var stagedFiles = StagingFolder.Files();
// The first picture is staged already when the second one fails:
await Assert.ThrowsAsync<IOException>(() => PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new FailingAtSecondPicture(), NullLogger.Instance, CancellationToken.None));
var targetContent = await File.ReadAllBytesAsync(targetPath);
using (Assert.EnterMultipleScope())
{
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT), "The chosen file stays as it was.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template and the staged picture are gone.");
}
}
[TestCase(false)]
[TestCase(true)]
public async Task TheMediaOfTheTemplateStreamThroughAsTheyAre(bool asTemplate)
{
// The deck keeps slide 1 with its picture and video, and leaves out slide 2, a sample with a picture and a video of its own:
var templatePath = Path.Join(this.templateFolder, asTemplate ? "template.potx" : "template.pptx");
var templateOptions = new TestTemplateOptions(AsTemplate: asTemplate, Slides:
[
new TestSlide(1, (TestPlaceholder.Title(), "Mars")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, TEMPLATE_PICTURE)] },
new TestSlide(1, (TestPlaceholder.Title(), "Sample")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, SAMPLE_PICTURE)] },
]);
using (var template = TestTemplate.Create(templateOptions,
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)),
new TestLayout("Picture", TestPlaceholder.Title(), TestPlaceholder.Picture(11, PICTURE_BOUNDS))))
await File.WriteAllBytesAsync(templatePath, template.ToArray());
var video = TestTemplate.VideoOf(VIDEO_SIZE);
TestTemplate.AddVideo(templatePath, 1, video);
TestTemplate.AddVideo(templatePath, 2, TestTemplate.VideoOf(1024 * 1024, 2), "/ppt/media/video2.mp4");
var deck = new SlideDeckSpec("Mars",
[
new SlideSpec(string.Empty, false, string.Empty, string.Empty, [], [], [], null, 1),
new SlideSpec("L3", false, "The rocket", string.Empty, [], [], [1], null),
]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
var stagedFiles = StagingFolder.Files();
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new OnePhoto(), NullLogger.Instance, CancellationToken.None);
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
List<string> templateErrors;
using (var template = PresentationDocument.Open(templatePath, false))
templateErrors = ValidationErrorsOf(template);
using var archive = ZipFile.OpenRead(targetPath);
var targetVideo = archive.GetEntry("ppt/media/video1.mp4");
var smallEntries = archive.Entries.Where(entry => entry.Length < 1024).Select(ContentOf).ToList();
using var document = PresentationDocument.Open(targetPath, false);
var slides = document.PresentationPart!.Presentation!.SlideIdList!.Elements<DocumentFormat.OpenXml.Presentation.SlideId>()
.Select(slideId => (SlidePart)document.PresentationPart.GetPartById(slideId.RelationshipId!.Value!))
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(targetVideo, Is.Not.Null, "The video of the kept slide comes along.");
Assert.That(targetVideo is null ? Array.Empty<byte>() : ContentOf(targetVideo), Is.EqualTo(video), "The video keeps its bytes.");
Assert.That(targetVideo?.CompressedLength, Is.EqualTo(targetVideo?.Length), "The video stays stored.");
Assert.That(archive.GetEntry("ppt/media/video2.mp4"), Is.Null, "The video of the sample slide stays out.");
Assert.That(smallEntries, Has.None.EqualTo(SAMPLE_PICTURE), "The picture of the sample slide stays out.");
Assert.That(slides.Select(slide => slide.ImageParts.Select(ContentOf).Single()), Is.EqualTo(new[] { TEMPLATE_PICTURE, PHOTO }), "The kept slide keeps its picture, and the new slide shows the photo.");
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 4), $"The template goes through streams, not through memory; {allocated / 1024 / 1024} MB were allocated.");
Assert.That(ValidationErrorsOf(document), Is.EquivalentTo(templateErrors), "The presentation is as valid as its template.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton, the photo, and the presentation leave nothing behind in the staging folder.");
}
}
@@ -108,19 +208,43 @@ public sealed class PresentationFileTests
return templatePath;
}
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath).DescribeBasisOf(DECK);
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(DECK);
/// <summary>
/// The files in the folder where the presentations come about; others may have left some there.
/// </summary>
private static string[] TemporaryFiles()
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
.Validate(document)
.Select(error => $"{error.Path?.XPath}: {error.Description}")
.ToList();
private static byte[] ContentOf(ZipArchiveEntry entry)
{
var folder = Path.Join(Path.GetTempPath(), "mindwork-ai-studio-presentations");
return Directory.Exists(folder) ? Directory.GetFiles(folder) : [];
using var stream = entry.Open();
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private static byte[] ContentOf(ImagePart part)
{
using var stream = part.GetStream(FileMode.Open, FileAccess.Read);
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private sealed class NoPictures : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult<SlidePicture?>(null);
}
private sealed class OnePhoto : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult(number == 1 ? new SlidePicture(PHOTO, "image/jpeg", 400, 300) : null);
}
private sealed class FailingAtSecondPicture : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => number < 2
? Task.FromResult<SlidePicture?>(new SlidePicture([1, 2, 3], "image/png", 400, 100))
: throw new IOException("The picture cannot be read.");
}
}
@@ -1,5 +1,8 @@
using AIStudio.Tests.Tools.OpenXml;
using AIStudio.Tools.PowerPoint;
using Microsoft.Extensions.Logging.Abstractions;
using P = DocumentFormat.OpenXml.Presentation;
namespace AIStudio.Tests.Tools.PowerPoint;
@@ -37,6 +40,40 @@ public sealed class PresentationTemplateTests
}
}
[Test]
public void ATemplateFileIsReadThroughItsSkeleton()
{
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
try
{
var path = Path.Join(folder, "template.pptx");
using (var file = TestTemplate.Create(
new TestTemplateOptions(Slides: [new TestSlide(1, (TestPlaceholder.Title(), "News"), (TestPlaceholder.Text(1, FULL_TEXT), "A point"))]),
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE)),
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, FULL_TEXT))))
File.WriteAllBytes(path, file.ToArray());
TestTemplate.AddVideo(path, 1, TestTemplate.VideoOf(1024 * 1024));
var stagedBefore = StagingFolder.Files();
var fromFile = PresentationTemplate.ReadFile(path, NullLogger.Instance);
PresentationTemplate fromStream;
using (var stream = File.OpenRead(path))
fromStream = PresentationTemplate.Read(stream);
using (Assert.EnterMultipleScope())
{
Assert.That(fromFile.ToCatalogPrompt(), Is.EqualTo(fromStream.ToCatalogPrompt()), "The skeleton holds every layout.");
Assert.That(fromFile.Slides.Select(slide => slide.Title), Is.EqualTo(new[] { "News" }), "The skeleton holds every slide.");
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the template is read.");
}
}
finally
{
Directory.Delete(folder, true);
}
}
[Test]
public void LayoutsWhichOnlyLookAlikeAreNoVariants()
{
@@ -4,6 +4,8 @@ using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Microsoft.Extensions.Logging.Abstractions;
using A = DocumentFormat.OpenXml.Drawing;
using P = DocumentFormat.OpenXml.Presentation;
using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
@@ -321,16 +323,8 @@ public sealed class PresentationWriterTests
new TestLayout("A Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(10, FOOTER)),
new TestLayout("B Content", TestPlaceholder.Title(), TestPlaceholder.Text(2, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(12, FOOTER)));
var template = PresentationTemplate.Read(templateFile);
templateFile.Position = 0;
using var output = new MemoryStream();
await templateFile.CopyToAsync(output);
output.Position = 0;
await PresentationWriter.WriteAsync(output, template, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" }, new FakePictureSource(), CancellationToken.None);
output.Position = 0;
using var document = PresentationDocument.Open(output, false);
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" });
using var document = PresentationDocument.Open(file, false);
var slide = SlidesOf(document)[0];
using (Assert.EnterMultipleScope())
{
@@ -570,6 +564,61 @@ public sealed class PresentationWriterTests
}
}
[Test]
public async Task ARemovedVideoLeavesTheFile()
{
var templateOptions = new TestTemplateOptions(Slides: [new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] }]);
var deck = new SlideDeckSpec("Weekly", [Edit(1) with { Removals = ["element 1"] }]);
var (file, _) = await WriteAsync(deck, OPTIONS, templateOptions);
using var document = PresentationDocument.Open(file, false);
var slide = SlidesOf(document)[0];
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(document), Is.Empty);
Assert.That(slide.Slide!.Descendants<P.Picture>(), Is.Empty);
Assert.That(slide.ImageParts, Is.Empty, "The poster frame leaves the file along with its shape.");
Assert.That(slide.DataPartReferenceRelationships, Is.Empty, "The slide no longer refers to the video.");
Assert.That(document.DataParts, Is.Empty, "The video leaves the file along with its shape.");
}
}
[Test]
public async Task ALinkOfAKeptSlideKeepsNoRemovedSlideInTheFile()
{
var templateOptions = new TestTemplateOptions(Slides:
[
new TestSlide(2, (TestPlaceholder.Title(), "Agenda")) { Elements = [TestElement.TextBox(HEADING, "Launch"), TestElement.TextBox(LEFT_TEXT, "Budget")] },
new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] },
new TestSlide(2, (TestPlaceholder.Title(), "Budget"))
]);
using var templateFile = TestTemplate.Create(templateOptions, Layouts());
using (var templateDocument = PresentationDocument.Open(templateFile, true))
{
// The agenda leads to both other slides, as a table of contents does:
var templateSlides = SlidesOf(templateDocument);
LinkText(templateSlides[0], "Launch", templateSlides[1]);
LinkText(templateSlides[0], "Budget", templateSlides[2]);
}
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1), Keep(3)]), OPTIONS);
using var document = PresentationDocument.Open(file, false);
var slides = SlidesOf(document);
var links = slides[0].Slide!.Descendants<A.HyperlinkOnClick>().ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(document), Is.Empty);
Assert.That(document.GetAllParts().OfType<SlidePart>().Count(), Is.EqualTo(2), "The removed slide leaves the file, although the agenda led to it.");
Assert.That(document.DataParts, Is.Empty, "The video of the removed slide leaves the file along with it.");
Assert.That(links, Has.Count.EqualTo(1), "Only the link to the slide which is gone is gone.");
Assert.That(links.Select(link => slides[0].GetPartById(link.Id!.Value!)), Has.All.SameAs(slides[1]), "The link to the kept slide still leads to it.");
Assert.That(slides[0].Slide!.InnerText, Does.Contain("Launch"), "The text of the link stays, as a plain text.");
}
}
[Test]
public async Task RemovingAnAnimatedShapeDropsTheAnimationsOfItsSlide()
{
@@ -676,6 +725,15 @@ public sealed class PresentationWriterTests
private static P.Shape ShapeWithIdOf(SlidePart slide, uint id) => slide.Slide!.Descendants<P.Shape>()
.Single(shape => shape.NonVisualShapeProperties?.NonVisualDrawingProperties?.Id?.Value == id);
/// <summary>
/// Turns a text of a slide into a link to another slide, as PowerPoint writes one.
/// </summary>
private static void LinkText(SlidePart slide, string text, SlidePart target)
{
var run = slide.Slide!.Descendants<A.Run>().Single(run => run.InnerText == text);
run.RunProperties = new A.RunProperties(new A.HyperlinkOnClick { Id = slide.GetIdOfPart(slide.AddPart(target)), Action = "ppaction://hlinksldjump" });
}
private static TestLayout[] Layouts() =>
[
new("A Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE), TestPlaceholder.Footer(10, FOOTER), TestPlaceholder.SlideNumber(11, SLIDE_NUMBER)),
@@ -696,19 +754,29 @@ public sealed class PresentationWriterTests
/// <summary>
/// Writes a presentation from a template file of the test's own, e.g., from a presentation written before.
/// </summary>
/// <remarks>
/// The presentation comes about as in the Slide Assistant: from a template file into the file the user chose.
/// </remarks>
private static async Task<WrittenPresentation> WriteFromAsync(Stream templateFile, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource? pictures = null)
{
templateFile.Position = 0;
var template = PresentationTemplate.Read(templateFile);
templateFile.Position = 0;
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
try
{
var templatePath = Path.Join(folder, "template.pptx");
var targetPath = Path.Join(folder, "presentation.pptx");
templateFile.Position = 0;
await using (var file = new FileStream(templatePath, FileMode.CreateNew, FileAccess.Write))
await templateFile.CopyToAsync(file);
// The writer edits a copy of the template, as the Slide Assistant does with one on disk:
var output = new MemoryStream();
await templateFile.CopyToAsync(output);
output.Position = 0;
var result = await PresentationWriter.WriteAsync(output, template, deck, options, pictures ?? new FakePictureSource(), CancellationToken.None);
output.Position = 0;
return new WrittenPresentation(output, result);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, options, pictures ?? new FakePictureSource(), NullLogger.Instance, CancellationToken.None);
Assert.That(result.IsWritten, Is.True, "The template stays as it is, so the deck still fits.");
return new WrittenPresentation(new MemoryStream(await File.ReadAllBytesAsync(targetPath)), result);
}
finally
{
Directory.Delete(folder, true);
}
}
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
@@ -765,5 +833,5 @@ public sealed class PresentationWriterTests
/// </summary>
/// <param name="File">The presentation, positioned at its start.</param>
/// <param name="Result">What happened beyond writing.</param>
private sealed record WrittenPresentation(MemoryStream File, PresentationWriteResult Result);
private sealed record WrittenPresentation(MemoryStream File, PresentationFileResult Result);
}
@@ -1,3 +1,4 @@
using System.IO.Packaging;
using System.Text;
using AIStudio.Tools.PowerPoint;
@@ -226,6 +227,44 @@ internal static class TestTemplate
return PresentationTemplate.Read(stream);
}
/// <summary>
/// Adds a video to a slide of a presentation file as PowerPoint stores it: uncompressed, behind the slides, which
/// the update mode of ZipArchive would load into memory.
/// </summary>
/// <param name="path">The presentation file.</param>
/// <param name="slideNumber">The 1-based number of the slide in the order of the presentation.</param>
/// <param name="video">The content of the video.</param>
/// <param name="videoPartName">The name of the part of the video.</param>
public static void AddVideo(string path, int slideNumber, byte[] video, string videoPartName = "/ppt/media/video1.mp4")
{
Uri slideUri;
using (var document = PresentationDocument.Open(path, false))
{
var presentationPart = document.PresentationPart!;
var slideId = presentationPart.Presentation!.SlideIdList!.Elements<P.SlideId>().ElementAt(slideNumber - 1);
slideUri = presentationPart.GetPartById(slideId.RelationshipId!.Value!).Uri;
}
using var package = Package.Open(path, FileMode.Open, FileAccess.ReadWrite);
var videoPart = package.CreatePart(new Uri(videoPartName, UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
using (var stream = videoPart.GetStream())
stream.Write(video);
package.GetPart(slideUri).CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
}
/// <summary>
/// The content of a video for a test, which no compression shrinks.
/// </summary>
/// <param name="size">The size in bytes.</param>
/// <param name="seed">Tells videos of the same size apart.</param>
public static byte[] VideoOf(int size, int seed = 1179)
{
var video = new byte[size];
new Random(seed).NextBytes(video);
return video;
}
/// <summary>
/// The shape tree of a layout, a master or a slide.
/// </summary>
@@ -423,6 +462,34 @@ internal sealed record TestElement(Func<uint, SlidePart, OpenXmlElement> Create)
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
});
/// <summary>
/// A video as PowerPoint embeds one: a picture with a poster frame, which refers to the video twice, once for older
/// versions of PowerPoint and once for newer ones.
/// </summary>
public static TestElement Video(SlotBounds bounds, params byte[] data) => new((id, slidePart) =>
{
var mediaPart = ((PresentationDocument)slidePart.OpenXmlPackage).CreateMediaDataPart(MediaDataPartType.Mp4);
using (var stream = new MemoryStream(data))
mediaPart.FeedData(stream);
var posterPart = slidePart.AddImagePart("image/png");
using (var stream = new MemoryStream([1, 2, 3]))
posterPart.FeedData(stream);
var videoId = slidePart.AddVideoReferenceRelationship(mediaPart).Id;
var mediaId = slidePart.AddMediaReferenceRelationship(mediaPart).Id;
return new P.Picture(
new P.NonVisualPictureProperties(
new P.NonVisualDrawingProperties { Id = id, Name = $"Video {id}" },
new P.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true }),
new P.ApplicationNonVisualDrawingProperties(
new A.VideoFromFile { Link = videoId },
new P.ApplicationNonVisualDrawingPropertiesExtensionList(
new P.ApplicationNonVisualDrawingPropertiesExtension(new P14.Media { Embed = mediaId }) { Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}" }))),
new P.BlipFill(new A.Blip { Embed = slidePart.GetIdOfPart(posterPart) }, new A.Stretch(new A.FillRectangle())),
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
});
/// <summary>
/// A bar chart without data, with a chart part of its own.
/// </summary>