Files
anm2ed/src/render.cpp
T
shweetandClaude Opus 5.5 8953101245 Stage 0: continuity test suite
- anm2ed_core static library (anm2 + non-UI util + log) shared by app and tests
- Logger is inert until session_open, so the core has no SDL dependency
- doctest suite: golden round-trips of 12 synthetic fixtures across every
  serialization preset, format and merge type; save/reload invariants
  (fixed point, hash stability, game view equals re-baked game view);
  operation goldens; env-gated private corpus run (ANM2ED_CORPUS)
- ANM2ED_UPDATE_GOLDEN=1 regenerates goldens; tests/MANUAL.md UI checklist

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:34:31 -04:00

174 lines
5.7 KiB
C++

#include "render.hpp"
#include <algorithm>
#include <cstring>
#include <filesystem>
#include <format>
#include <string>
#include <string_view>
#include <SDL3/SDL_timer.h>
#include "file.hpp"
#include "log.hpp"
#include "path.hpp"
#include "process.hpp"
#if _WIN32
#include "string.hpp"
#endif
using namespace anm2ed::util;
namespace anm2ed
{
bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path,
const std::vector<std::filesystem::path>& framePaths, AudioStream& audioStream,
render::Type type, int fps)
{
if (framePaths.empty() || ffmpegPath.empty() || path.empty()) return false;
fps = std::max(fps, 1);
auto pathString = path::to_utf8(path);
auto ffmpegPathString = path::to_utf8(ffmpegPath);
auto loggerPath = logger.path();
auto loggerPathString = path::to_utf8(loggerPath);
#if _WIN32
auto ffmpegTempPath = loggerPath.parent_path() / "ffmpeg_log.temp.txt";
auto ffmpegTempPathString = path::to_utf8(ffmpegTempPath);
std::error_code ffmpegTempError;
std::filesystem::remove(ffmpegTempPath, ffmpegTempError);
#endif
std::filesystem::path audioPath{};
std::string audioInputArguments{};
std::string audioOutputArguments{"-an"};
std::string command{};
auto temporaryDirectory = framePaths.front().parent_path();
if (temporaryDirectory.empty()) temporaryDirectory = std::filesystem::temp_directory_path();
auto audio_remove = [&]()
{
if (!audioPath.empty())
{
std::error_code ec;
std::filesystem::remove(audioPath, ec);
}
};
if (type != render::GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 &&
audioStream.spec.channels > 0)
{
auto tempFilenameUtf8 = std::format("anm2ed_audio_{}_{}.f32", std::hash<std::string>{}(pathString), SDL_GetTicks());
audioPath = temporaryDirectory / path::from_utf8(tempFilenameUtf8);
auto data = (const char*)audioStream.stream.data();
auto byteCount = audioStream.stream.size() * sizeof(float);
if (file::write_string(audioPath, std::string_view(data, byteCount), "wb"))
{
auto sampleRate = std::max(audioStream.spec.freq, 1);
auto channels = std::max(audioStream.spec.channels, 1);
auto audioDurationFilter = std::string{};
auto frameCount = (double)std::max((int)framePaths.size(), 1);
auto expectedDurationSeconds = frameCount / (double)fps;
if (expectedDurationSeconds > 0.0)
audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds);
audioInputArguments =
std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path::to_utf8(audioPath));
switch (type)
{
case render::WEBM:
audioOutputArguments = "-c:a libopus -b:a 160k -shortest";
break;
case render::OGV:
audioOutputArguments = "-c:a libvorbis -q:a 4 -shortest";
break;
case render::MP4:
audioOutputArguments = "-c:a aac -b:a 192k -shortest";
break;
default:
break;
}
if (!audioDurationFilter.empty())
audioOutputArguments = std::format("-af \"{}\" {}", audioDurationFilter, audioOutputArguments);
}
else
{
logger.warning("Failed to open temporary audio file; exporting video without audio.");
audio_remove();
}
}
auto framePattern = temporaryDirectory / path::from_utf8("frame_%06d.png");
auto framePatternString = path::to_utf8(framePattern);
command = std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps,
framePatternString);
if (!audioInputArguments.empty()) command += " " + audioInputArguments;
command += std::format(" -fps_mode cfr -r {}", fps);
switch (type)
{
case render::GIF:
command +=
" -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];"
"[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\""
" -loop 0";
command += std::format(" \"{}\"", pathString);
break;
case render::WEBM:
command += " -c:v libvpx-vp9 -crf 30 -b:v 0 -pix_fmt yuva420p -row-mt 1 -threads 0 -speed 2 -auto-alt-ref 0";
if (!audioOutputArguments.empty()) command += " " + audioOutputArguments;
command += std::format(" \"{}\"", pathString);
break;
case render::OGV:
command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libtheora -q:v 7";
if (!audioOutputArguments.empty()) command += " " + audioOutputArguments;
command += std::format(" \"{}\"", pathString);
break;
case render::MP4:
command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libx265 -crf 20 -preset slow"
" -tag:v hvc1 -movflags +faststart";
if (!audioOutputArguments.empty()) command += " " + audioOutputArguments;
command += std::format(" \"{}\"", pathString);
break;
default:
{
return false;
}
}
#if _WIN32
command = string::quote(command);
#endif
logger.command(command);
#if _WIN32
Process process(command.c_str(), "wb");
#else
Process process(command.c_str(), "w");
#endif
if (!process.get())
{
audio_remove();
return false;
}
auto ffmpegExitCode = process.close();
if (ffmpegExitCode != 0)
{
logger.error(std::format("FFmpeg exited with code {} while exporting {}", ffmpegExitCode, pathString));
audio_remove();
return false;
}
audio_remove();
return true;
}
}