5#include <Poco/Checksum.h>
6#include <Poco/DeflatingStream.h>
7#include <Poco/InflatingStream.h>
26void writeBytes(
const std::filesystem::path&
path,
const char* data,
size_t size) {
27 std::ofstream stream(
path, std::ios::binary | std::ios::trunc);
28 stream.write(data,
static_cast<std::streamsize
>(
size));
29 if (!stream)
throw std::runtime_error(
"failed writing " +
path.generic_string());
32std::vector<uint8_t> readAllBytes(
const std::filesystem::path&
path) {
33 std::ifstream stream(
path, std::ios::binary);
34 if (!stream)
throw std::runtime_error(
"failed reading " +
path.generic_string());
35 return std::vector<uint8_t>(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
38uint32_t readBe32(
const uint8_t* data) {
39 return (uint32_t(data[0]) << 24) | (uint32_t(data[1]) << 16) | (uint32_t(data[2]) << 8) | uint32_t(data[3]);
42void be32(std::vector<uint8_t>&
out, uint32_t
value) {
43 for (
int shift = 24; shift >= 0; shift -= 8)
out.push_back(
static_cast<uint8_t
>(
value >> shift));
46void pngChunk(std::vector<uint8_t>&
out,
const char*
type,
const std::vector<uint8_t>&
bytes) {
47 be32(
out,
static_cast<uint32_t
>(
bytes.size()));
51 Poco::Checksum checksum(Poco::Checksum::TYPE_CRC32);
52 checksum.update(
reinterpret_cast<const char*
>(
out.data() +
start),
static_cast<unsigned>(
out.size() -
start));
53 be32(
out, checksum.checksum());
56Result<std::vector<uint8_t>> encodeRgbaPng(uint32_t
width, uint32_t
height,
57 const std::shared_ptr<
const std::vector<uint8_t>>& rgba) {
61 std::vector<uint8_t> scanlines((
size_t(
width) * 4 + 1) *
height);
63 const size_t row = size_t(
y) * (size_t(
width) * 4 + 1);
65 std::memcpy(scanlines.data() + row + 1, rgba->data() +
size_t(
y) *
width * 4,
size_t(
width) * 4);
67 std::ostringstream compressed;
68 Poco::DeflatingOutputStream zlib(compressed, Poco::DeflatingStreamBuf::STREAM_ZLIB);
69 zlib.write(
reinterpret_cast<const char*
>(scanlines.data()),
static_cast<std::streamsize
>(scanlines.size()));
71 const auto data = compressed.str();
72 std::vector<uint8_t> png = {137, 80, 78, 71, 13, 10, 26, 10};
73 std::vector<uint8_t>
header;
77 pngChunk(png,
"IHDR", header);
78 pngChunk(png,
"IDAT", std::vector<uint8_t>(data.begin(), data.end()));
79 pngChunk(png,
"IEND", {});
80 return Result<std::vector<uint8_t>>::success(std::move(png));
83std::string padFolder(
size_t index1Based) {
84 std::ostringstream oss;
85 oss << std::setw(4) << std::setfill(
'0') << index1Based;
92 static const uint8_t kSig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
93 if (pngBytes.size() < 8 || std::memcmp(pngBytes.data(), kSig, 8) != 0)
97 bool sawIhdr =
false, sawIend =
false;
98 std::vector<uint8_t> idat;
99 while (
offset + 12 <= pngBytes.size()) {
100 const uint32_t
length = readBe32(pngBytes.data() +
offset);
103 const char*
type =
reinterpret_cast<const char*
>(pngBytes.data() +
offset + 4);
104 const auto* data = pngBytes.data() +
offset + 8;
105 Poco::Checksum
crc(Poco::Checksum::TYPE_CRC32);
106 crc.update(
reinterpret_cast<const char*
>(pngBytes.data() +
offset + 4),
static_cast<unsigned>(
length + 4));
107 const uint32_t expected = readBe32(pngBytes.data() +
offset + 8 +
length);
108 if (
crc.checksum() != expected)
110 if (std::strncmp(
type,
"IHDR", 4) == 0) {
111 if (
length != 13 || sawIhdr)
113 width = readBe32(data);
114 height = readBe32(data + 4);
115 const auto bitDepth = data[8];
116 const auto colorType = data[9];
117 const auto interlace = data[12];
118 if (bitDepth != 8 || colorType != 6 || interlace != 0 ||
width == 0 ||
height == 0 ||
width > 4096 ||
121 "only non-interlaced 8-bit RGBA PNG is supported");
123 }
else if (std::strncmp(
type,
"IDAT", 4) == 0) {
124 idat.insert(idat.end(), data, data +
length);
125 }
else if (std::strncmp(
type,
"IEND", 4) == 0) {
132 if (!sawIhdr || !sawIend || idat.empty())
135 std::string compressed(
reinterpret_cast<const char*
>(idat.data()), idat.size());
136 std::istringstream
input(compressed);
137 Poco::InflatingInputStream zlib(
input, Poco::InflatingStreamBuf::STREAM_ZLIB);
138 std::ostringstream inflated;
139 inflated << zlib.rdbuf();
140 const auto raw = inflated.str();
141 const size_t stride = size_t(
width) * 4 + 1;
145 auto rgba = std::make_shared<std::vector<uint8_t>>(size_t(
width) *
height * 4);
147 const auto* row =
reinterpret_cast<const uint8_t*
>(
raw.data() + size_t(
y) * stride);
148 const auto filter = row[0];
151 "PNG filter methods other than None are unsupported");
152 std::memcpy(rgba->data() +
size_t(
y) *
width * 4, row + 1,
size_t(
width) * 4);
157 frame.rgba8 = std::move(rgba);
163 if (
pack.shots.empty())
165 if (!std::filesystem::is_directory(candidateDir))
167 candidateDir.generic_string());
168 std::vector<ActionGuideCandidateFrame> frames;
169 frames.reserve(
pack.shots.size());
171 for (
size_t i = 0; i <
pack.shots.size(); ++i) {
172 const auto folder = candidateDir / padFolder(i + 1);
173 const auto metaPath = folder /
"meta.json";
174 const auto pngPath = folder /
"frame.png";
175 if (!std::filesystem::is_regular_file(metaPath) || !std::filesystem::is_regular_file(pngPath))
176 return fail<std::vector<ActionGuideCandidateFrame>>(
178 const auto metaBytes = readAllBytes(metaPath);
180 Value::fromJson(std::string(
reinterpret_cast<const char*
>(metaBytes.data()), metaBytes.size()));
184 const auto pngBytes = readAllBytes(pngPath);
187 frame.value().meta = std::move(meta).takeValue();
188 frames.push_back(std::move(
frame).takeValue());
190 }
catch (
const std::exception& e) {
192 std::string(
"candidate load failed: ") + e.what());
198 std::span<const ActionGuideCandidateFrame> frames,
199 const std::filesystem::path& outputRoot) {
200 if (frames.empty() ||
static_cast<std::int64_t
>(frames.size()) !=
draft.frameCount)
202 const auto staging = outputRoot /
".staging";
204 std::filesystem::remove_all(staging);
205 std::filesystem::create_directories(staging /
"frames");
206 for (
size_t i = 0; i < frames.size(); ++i) {
207 auto png = encodeRgbaPng(frames[i].
width, frames[i].
height, frames[i].rgba8);
209 std::filesystem::remove_all(staging);
212 writeBytes(staging / (
"frames/frame_" + std::to_string(i) +
".png"),
213 reinterpret_cast<const char*
>(png.value().data()), png.value().size());
216 auto json =
value.toJson();
218 writeBytes(staging /
name, json.value().data(), json.value().size());
221 if (
auto r = writeJson(
"clip.json",
draft.clipDescriptor); !
r) {
222 std::filesystem::remove_all(staging);
225 if (
auto r = writeJson(
"ability.draft.json",
draft.abilityDraft); !
r) {
226 std::filesystem::remove_all(staging);
229 if (
auto r = writeJson(
"attribution.gen.json",
draft.attribution); !
r) {
230 std::filesystem::remove_all(staging);
235 {
"schemaVersion",
Value(
static_cast<std::int64_t
>(1))},
236 {
"sourceGuideRevision",
Value(
static_cast<std::int64_t
>(
draft.sourceGuideRevision))},
239 {
"sequencePattern",
Value(
draft.sequencePattern)},
240 {
"sequenceFirst",
Value(
draft.sequenceFirst)},
242 {
"clipPath",
Value(
"clip.json")},
243 {
"abilityDraftPath",
Value(
"ability.draft.json")},
244 {
"attributionPath",
Value(
"attribution.gen.json")}});
245 if (
auto r = writeJson(
"ingest.manifest.json", manifest); !
r) {
246 std::filesystem::remove_all(staging);
250 std::filesystem::create_directories(outputRoot);
252 const auto publishedTmp = outputRoot / (
".published-" + std::to_string(
draft.sourceGuideRevision));
253 std::filesystem::remove_all(publishedTmp);
254 std::filesystem::rename(staging, publishedTmp);
255 for (
const auto& entry : std::filesystem::directory_iterator(publishedTmp)) {
256 const auto name = entry.path().filename();
257 if (
name ==
"." ||
name ==
"..")
continue;
258 const auto dest = outputRoot /
name;
259 std::filesystem::remove_all(dest);
260 std::filesystem::rename(entry.path(), dest);
262 std::filesystem::remove_all(publishedTmp);
266 {
"manifest",
Value(
"ingest.manifest.json")},
267 {
"clipPath",
Value(
"clip.json")},
268 {
"abilityDraftPath",
Value(
"ability.draft.json")},
271 {
"sourceGuideRevision",
Value(
static_cast<std::int64_t
>(
draft.sourceGuideRevision))}}));
272 }
catch (
const std::exception& e) {
274 std::filesystem::remove_all(staging, ec);
Filesystem load/write helpers for ActionGuide candidate ingest.
Stable, structured diagnostics shared by engine modules.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
The canonical owning dynamic value used by data-facing protocols.
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
static Value object(Object value)
Compatibility factory for an object value.
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
Result< Value > writeActionGuideIngestPack(const ActionGuideIngestDraft &draft, std::span< const ActionGuideCandidateFrame > frames, const std::filesystem::path &outputRoot)
Atomically write frames + clip/ability drafts under outputRoot.
Result< std::vector< ActionGuideCandidateFrame > > loadActionGuideCandidates(const std::filesystem::path &candidateDir, const ActionGuidePack &pack)
Load NNNN/{meta.json,frame.png} under candidateDir into an ordered frame list. @cost Disk IO + PNG de...
Result< ActionGuideCandidateFrame > decodeActionGuideCandidatePng(std::span< const std::uint8_t > pngBytes)
Decode an 8-bit RGBA PNG into an owning RGBA8 buffer.
std::string header(int localX, int localY)
Header.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
DiagnosticCode
Stable machine-readable diagnostic codes.
Result< ActionGuideCandidateMeta > decodeActionGuideCandidateMeta(const Value &value)
Decode one candidate meta object; unknown fields/versions are rejected. @cost Linear in object field ...
One candidate frame with lease-owned RGBA8 pixels.
Draft artifacts produced by ingest (no formal AbilityRuntime mutation). @ownership Caller owns; Value...
Authoritative guide-pack document (no pointers, GPU tokens, or ECS slots). @ownership Caller-owned va...