From 250ff3238625fb568dcb17de89c52e7b84f52264 Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:52:11 +0100 Subject: [PATCH 1/6] Window captures from an offscreen picture: no black shots while hidden The back buffer's pixels are undefined where the window isn't visible (GL pixel ownership), so captures of a covered or minimised window came out black. The window now presents into its own framebuffer, blits it to the screen, and captures read from that framebuffer. Co-Authored-By: Claude Opus 5.5 --- runtime/app/window.cpp | 54 +++++++++++++++++++++++--- runtime/include/bozo/render/gl.h | 2 + runtime/include/bozo/render/renderer.h | 4 ++ runtime/render/present_gl.cpp | 2 +- 4 files changed, 55 insertions(+), 7 deletions(-) diff --git a/runtime/app/window.cpp b/runtime/app/window.cpp index b301c44..f66171e 100644 --- a/runtime/app/window.cpp +++ b/runtime/app/window.cpp @@ -72,8 +72,9 @@ namespace bozo::app m_thread.join(); } - // The back buffer (pixels w x h) now, saved as path. - void capture(const std::string &path, int w, int h) + // The picture (pixels w x h) now, saved as path: framebuffer `from`'s colour (0: the window's back buffer, + // whose pixels are undefined while the window is covered, minimised or its display asleep). + void capture(const std::string &path, int w, int h, render::gl::GLuint from = 0) { const render::gl::Api &g = render::gl::api(); Job job; @@ -81,9 +82,11 @@ namespace bozo::app job.width = w; job.height = h; job.pixels.resize(static_cast(w) * h * 4u); - g.ReadBuffer(render::gl::kBack); + g.BindFramebuffer(render::gl::kReadFramebuffer, from); + g.ReadBuffer(from ? render::gl::kColorAttachment0 : render::gl::kBack); g.PixelStorei(render::gl::kPackAlignment, 4); g.ReadPixels(0, 0, w, h, render::gl::kRgba, render::gl::kUnsignedByte, job.pixels.data()); + g.BindFramebuffer(render::gl::kReadFramebuffer, 0); { std::lock_guard lock(m_mutex); m_jobs.push_back(std::move(job)); @@ -270,6 +273,8 @@ namespace bozo::app uint64_t runFirstFrames = 0; Clock::time_point runFirst{}; uint64_t seen = 0; + render::gl::GLuint pictureFbo = 0, pictureColour = 0, pictureDepth = 0; // the game's picture (see below) + int pictureWidth = 0, pictureHeight = 0; int swapRate = 0; // the frame rate the swap interval was set for Clock::time_point nextPresent{}; while (!quit) @@ -381,7 +386,36 @@ namespace bozo::app SDL_GetWindowSizeInPixels(window, &pw, &ph); pw = std::max(pw, 1); ph = std::max(ph, 1); - g.BindFramebuffer(render::gl::kFramebuffer, 0); + // The game's picture is drawn into a framebuffer of the window's size, then copied to the window: captures + // read it there, whether or not the window can be seen. + if (pictureWidth != pw || pictureHeight != ph) + { + if (!pictureFbo) + { + g.GenFramebuffers(1, &pictureFbo); + g.GenRenderbuffers(1, &pictureColour); + g.GenRenderbuffers(1, &pictureDepth); + } + g.BindRenderbuffer(render::gl::kRenderbuffer, pictureColour); + g.RenderbufferStorage(render::gl::kRenderbuffer, render::gl::kRgba8, pw, ph); + g.BindRenderbuffer(render::gl::kRenderbuffer, pictureDepth); + g.RenderbufferStorage(render::gl::kRenderbuffer, render::gl::kDepth24Stencil8, pw, ph); + g.BindFramebuffer(render::gl::kFramebuffer, pictureFbo); + g.FramebufferRenderbuffer(render::gl::kFramebuffer, render::gl::kColorAttachment0, render::gl::kRenderbuffer, + pictureColour); + g.FramebufferRenderbuffer(render::gl::kFramebuffer, render::gl::kDepthStencilAttachment, + render::gl::kRenderbuffer, pictureDepth); + if (g.CheckFramebufferStatus(render::gl::kFramebuffer) != render::gl::kFramebufferComplete) + { + std::fprintf(stderr, "[window] the %d x %d picture framebuffer is incomplete: drawing to the window\n", pw, ph); + g.DeleteFramebuffers(1, &pictureFbo); + pictureFbo = 0; + } + pictureWidth = pw; + pictureHeight = ph; + } + renderer.setPresentFramebuffer(pictureFbo); + g.BindFramebuffer(render::gl::kFramebuffer, pictureFbo); g.Viewport(0, 0, pw, ph); g.Disable(render::gl::kScissorTest); g.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); @@ -395,6 +429,14 @@ namespace bozo::app else rh = rw / options.aspect; renderer.present((static_cast(pw) - rw) * 0.5f, (static_cast(ph) - rh) * 0.5f, rw, rh); + if (pictureFbo) + { + g.BindFramebuffer(render::gl::kReadFramebuffer, pictureFbo); + g.BindFramebuffer(render::gl::kDrawFramebuffer, 0); + g.BlitFramebuffer(0, 0, pw, ph, 0, 0, pw, ph, render::gl::kColorBufferBit, render::gl::kNearest); + g.BindFramebuffer(render::gl::kFramebuffer, 0); + g.Viewport(0, 0, pw, ph); + } ++presents; ++ratesPresents; @@ -412,7 +454,7 @@ namespace bozo::app { char name[64]; std::snprintf(name, sizeof(name), "frame_%06llu.png", static_cast(framesBefore)); - writer.capture(captureDir + "/" + name, pw, ph); + writer.capture(captureDir + "/" + name, pw, ph, pictureFbo); if (options.onCaptured) options.onCaptured(framesBefore); } @@ -422,7 +464,7 @@ namespace bozo::app ensureDir(intervalDir); char name[64]; std::snprintf(name, sizeof(name), "interval_%08llu.png", ms); - writer.capture(intervalDir + "/" + name, pw, ph); + writer.capture(intervalDir + "/" + name, pw, ph, pictureFbo); } // The overlay's rates, every half second. diff --git a/runtime/include/bozo/render/gl.h b/runtime/include/bozo/render/gl.h index f266446..6409189 100644 --- a/runtime/include/bozo/render/gl.h +++ b/runtime/include/bozo/render/gl.h @@ -144,6 +144,8 @@ namespace bozo::render::gl X(void, FramebufferTexture2D, (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)) \ X(void, FramebufferRenderbuffer, (GLenum target, GLenum attachment, GLenum rbtarget, GLuint renderbuffer)) \ X(GLenum, CheckFramebufferStatus, (GLenum target)) \ + X(void, BlitFramebuffer, (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, \ + GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)) \ X(void, GenRenderbuffers, (GLsizei n, GLuint *renderbuffers)) \ X(void, DeleteRenderbuffers, (GLsizei n, const GLuint *renderbuffers)) \ X(void, BindRenderbuffer, (GLenum target, GLuint renderbuffer)) \ diff --git a/runtime/include/bozo/render/renderer.h b/runtime/include/bozo/render/renderer.h index 556b235..724cca2 100644 --- a/runtime/include/bozo/render/renderer.h +++ b/runtime/include/bozo/render/renderer.h @@ -360,6 +360,9 @@ namespace bozo::render // the window (pixels from its top left; the current framebuffer, its viewport the window); false when there is // nothing to draw yet. bool present(float x, float y, float width, float height); + // The framebuffer present() draws into (0: the window's). A window that captures its pictures presents into one + // of its own: a covered, minimised or sleeping window's own pixels read back undefined (black). + void setPresentFramebuffer(unsigned framebuffer) { m_presentFramebuffer = framebuffer; } // Waits up to timeout seconds for a frame (or a movie picture) published after the one counted in seen, and // counts it there: the window shows each game frame once, on the game's clock. bool waitForFrame(uint64_t &seen, double timeout); @@ -436,6 +439,7 @@ namespace bozo::render std::condition_variable m_publishedChanged; FrameDraws m_draws; std::atomic m_renderScale{1.0f}; + unsigned m_presentFramebuffer = 0; // present thread only std::atomic m_textureUpscale{1u}; // Interpolation's frames (newest last, a few game frames' worth) and the clock they are placed on, under m_mutex. diff --git a/runtime/render/present_gl.cpp b/runtime/render/present_gl.cpp index 857762d..d3275ad 100644 --- a/runtime/render/present_gl.cpp +++ b/runtime/render/present_gl.cpp @@ -2034,7 +2034,7 @@ void main() readDepthTiles(w, h, screen); g.DepthMask(gl::kTrue); g.Disable(gl::kDepthTest); - g.BindFramebuffer(gl::kFramebuffer, 0); + g.BindFramebuffer(gl::kFramebuffer, m_presentFramebuffer); g.Viewport(viewport[0], viewport[1], viewport[2], viewport[3]); // Under the frame, as the display merges it: the picture the game shows through circuit 2 (a menu's movie frame, From 3a1b81ec541c2e8e442bbf6d9b68676afb02f964 Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:42:27 +0100 Subject: [PATCH 2/6] Overlapping native modules: the one loaded over the other's tail wins A game may load a module into another's span (JC2: a battle effect at 0x96B000 over the tail of the Arena's lesson script at 0x96A800). Both headers then match and moduleAt threw "ambiguous native module identity", ending the run. Where two resident modules cover an address, the one starting higher wins; each module keeps the lowest other start inside its span as the limit of the last-module fast path. Same-start ambiguity still throws. Runtime test added. Co-Authored-By: Claude Opus 5.5 --- runtime/core/runtime_core.cpp | 18 ++++++++++++++---- runtime/include/bozo/runtime.h | 5 ++++- tests/runtime/runtime_tests.cpp | 13 +++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/runtime/core/runtime_core.cpp b/runtime/core/runtime_core.cpp index becefd7..08352eb 100644 --- a/runtime/core/runtime_core.cpp +++ b/runtime/core/runtime_core.cpp @@ -69,7 +69,15 @@ namespace bozo if (start >= end || !resident || identity.empty() || identity.size() > uint64_t(end) - start || (count && !functions) || (resumeCount && !resume)) throw std::invalid_argument("invalid native module registration"); - modules_.push_back({start, end, resident, std::move(identity), functions, count, resume, resumeCount}); + uint32_t inner = end; + for (Module &other : modules_) + { + if (other.start > start && other.start < end) + inner = std::min(inner, other.start); + if (start > other.start && start < other.end) + other.inner = std::min(other.inner, start); + } + modules_.push_back({start, end, inner, resident, std::move(identity), functions, count, resume, resumeCount}); modulesLow_ = std::min(modulesLow_, start); modulesHigh_ = std::max(modulesHigh_, end); lastModule_ = nullptr; // the vector may have moved @@ -79,7 +87,7 @@ namespace bozo { if (address < modulesLow_ || address >= modulesHigh_) return nullptr; - if (const Module *last = lastModule_; last && address >= last->start && address < last->end && + if (const Module *last = lastModule_; last && address >= last->start && address < last->inner && std::memcmp(last->resident, last->identity.data(), last->identity.size()) == 0) { reserved = true; @@ -93,9 +101,11 @@ namespace bozo reserved = true; if (std::memcmp(module.resident, module.identity.data(), module.identity.size()) != 0) continue; - if (active) + // Two resident modules over the address: the higher one was loaded over the other's tail. + if (active && active->start == module.start) throw std::runtime_error("ambiguous native module identity"); - active = &module; + if (!active || module.start > active->start) + active = &module; } if (active) lastModule_ = active; diff --git a/runtime/include/bozo/runtime.h b/runtime/include/bozo/runtime.h index 685c7e6..3aff4b6 100644 --- a/runtime/include/bozo/runtime.h +++ b/runtime/include/bozo/runtime.h @@ -82,7 +82,9 @@ namespace bozo void clearOverrides() { overrides_.clear(); } size_t overrideCount() const { return overrides_.size(); } // Statically compiled images sharing a guest address range. A module is callable only while the - // resident identity bytes match. The resident storage and generated tables outlive this table. + // resident identity bytes match. The resident storage and generated tables outlive this table. Modules may + // overlap (a game loads one into another's span, over its tail): where two match, the one starting higher wins, + // its header being inside the other's span means it was loaded over that part. // This selects native code; it never loads or interprets guest instructions. void addModule(uint32_t start, uint32_t end, const uint8_t *resident, std::vector identity, const BozoFunctionEntry *functions, size_t count, @@ -104,6 +106,7 @@ namespace bozo struct Module { uint32_t start, end; + uint32_t inner; // the lowest other module's start inside (start, end), else end: the fast path's limit const uint8_t *resident; std::vector identity; const BozoFunctionEntry *functions; diff --git a/tests/runtime/runtime_tests.cpp b/tests/runtime/runtime_tests.cpp index d743d9c..0580bdb 100644 --- a/tests/runtime/runtime_tests.cpp +++ b/tests/runtime/runtime_tests.cpp @@ -101,6 +101,19 @@ int main() eq("module does not mask resident code", rt->functions.generated(0x100000) == fnA, true); rt->functions.clearModules(); + // A module loaded into another's span (JC2: a battle effect at 0x96B000 over the tail of the Arena's script at + // 0x96A800): where both are resident, the higher one owns its part, also right after the lower one was looked up. + const BozoFunctionEntry lowFns[] = {{0x300000u, fnA}, {0x300140u, fnA}}; + const BozoFunctionEntry highFns[] = {{0x300140u, fnB}}; + uint8_t lowResident[] = {5, 6}, highResident[] = {7, 8}; + rt->functions.addModule(0x300000, 0x300200, lowResident, {5, 6}, lowFns, 2, nullptr, 0); + rt->functions.addModule(0x300100, 0x300180, highResident, {7, 8}, highFns, 1, nullptr, 0); + eq("lower module's own part", rt->functions.generated(0x300000) == fnA, true); + eq("higher module over the lower's tail", rt->functions.generated(0x300140) == fnB, true); + highResident[0] = 0; + eq("the lower module again once the higher is gone", rt->functions.generated(0x300140) == fnA, true); + rt->functions.clearModules(); + // ei / di toggle Status.EIE; mfc0 12 reads Status. bozo_set_interrupts(rt->memory.ram(), &ctx, rt.get(), true); eq("ei", bozo_cop0_read(&ctx, rt.get(), 12), 0x10000); From de65040feca3429337bb92b461f5e9053e112b92 Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:55 +0100 Subject: [PATCH 3/6] Save states: read the pad, mpeg, sif and 989SND sections written before their newer fields States saved before these sections grew fail to load ("section pad ends before its fields"; then mpeg, sif) and the game starts from the boot. JC2's states from before 2026-11-24 hit all four: - pad: libpad2's sockets (pad2Sockets, pad2Next) came after multitapAttached; an older section ends there, and no socket is open. - mpeg: inputEnded (MpegOptions::sdkNodata) came before the sound; an older section has exactly the sound left, and the input goes on. - sif: the IOP side's software registers came before the heap; the older layout is tried first and kept only when it reads the section exactly (Archive::end checks it), with the registers cleared; otherwise the reader rewinds. - snd: a state from before the 989SND driver was saved has "timers" next; the driver stays as it is. Archive::sectionLeft(): the bytes the open section has left when reading. What is written does not change. bozo-state-tests (sectionLeft) passes, with the whole engine suite on jc2/native-irx-host (symbol_maps aside: the build's temp directory has "game" in its path). JC2: s24300_arena.state, saved on the engine before these fields, loads again and the run goes on in the scene it was saved in. Co-Authored-By: Claude Opus 5.5 --- runtime/include/bozo/state.h | 6 ++++ runtime/libs/libraries_state.cpp | 50 ++++++++++++++++++++++++++++---- tests/runtime/state_tests.cpp | 8 +++++ 3 files changed, 58 insertions(+), 6 deletions(-) diff --git a/runtime/include/bozo/state.h b/runtime/include/bozo/state.h index 36f36b0..5fc0fdc 100644 --- a/runtime/include/bozo/state.h +++ b/runtime/include/bozo/state.h @@ -49,6 +49,12 @@ namespace bozo::state Mark mark() const { return {pos_, open_.size()}; } // Reading: whether the next thing is the section `name` (an older layout that has no fields before it). bool nextIs(const char *name) const; + // Reading: the bytes the open section has left (an older layout, shorter by the fields added since); 0 when + // writing or with no section open. + size_t sectionLeft() const + { + return loading_ && !open_.empty() && pos_ < open_.back().second ? open_.back().second - pos_ : 0; + } void rewind(const Mark &m) { pos_ = m.pos; diff --git a/runtime/libs/libraries_state.cpp b/runtime/libs/libraries_state.cpp index 2c52c90..abbbfad 100644 --- a/runtime/libs/libraries_state.cpp +++ b/runtime/libs/libraries_state.cpp @@ -153,7 +153,15 @@ namespace bozo::libs for (auto &port : pad.ports) for (auto &slot : port) pod(a, slot); - fields(a, pad.initialized, pad.reads, pad.socketReads, pad.multitap, pad.multitapAttached, pad.pad2Sockets, pad.pad2Next); + fields(a, pad.initialized, pad.reads, pad.socketReads, pad.multitap, pad.multitapAttached); + // A state written before libpad2's sockets were saved (67c5867) ends here: no socket is open. + if (a.loading() && a.sectionLeft() == 0) + { + pad.pad2Sockets.clear(); + pad.pad2Next = 0; + } + else + fields(a, pad.pad2Sockets, pad.pad2Next); a.end(); a.begin("mc"); @@ -184,16 +192,46 @@ namespace bozo::libs m.pending, m.pendingAt, m.ring, m.ringSize, m.ringBias, m.linearBase, m.programEnd, m.aborted, m.es, m.scanned, m.starts, m.pictureStarts, m.sequenceEnd, m.headerOpen, m.cuts, m.sent, m.flushed, m.callbacksDue, m.waiting, m.delivered, m.base, m.lastShown, m.firstPictureNs, m.soundHeader, - m.soundCarry, m.inputEnded); + m.soundCarry); + // A state written before the SDK's Nodata end (MpegOptions::sdkNodata) has the sound left: the input goes on. + if (a.loading() && a.sectionLeft() == sizeof m.sound) + m.inputEnded = false; + else + fields(a, m.inputEnded); pod(a, m.sound); a.end(); a.begin("sif"); - fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules, sif.iopSreg); - sif.heap.serialize(a); - a.end(); + fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules); + { + // A state written before the IOP side's software registers has the heap next: read it as such when the + // registers then leave bytes over (the section's end checks the layout), with the registers cleared. + const state::Archive::Mark mark = a.mark(); + bool older = false; + if (a.loading()) + try + { + sif.heap.serialize(a); + a.end(); + older = true; + } + catch (const state::Error &) + { + a.rewind(mark); + } + if (older) + std::fill(std::begin(sif.iopSreg), std::end(sif.iopSreg), 0u); + else + { + fields(a, sif.iopSreg); + sif.heap.serialize(a); + a.end(); + } + } - snd.serialize(a, *this); + // A state written before the 989SND driver was saved goes on with the timers: the driver stays as it is. + if (!(a.loading() && a.nextIs("timers"))) + snd.serialize(a, *this); a.begin("timers"); TimerState &t = timers; diff --git a/tests/runtime/state_tests.cpp b/tests/runtime/state_tests.cpp index 1bd069a..65c2639 100644 --- a/tests/runtime/state_tests.cpp +++ b/tests/runtime/state_tests.cpp @@ -152,6 +152,14 @@ namespace check(y.nextIs("s") && !y.nextIs("next") && !y.nextIs("ss"), "nextIs names the coming section"); y.begin("s"); check(!y.nextIs("next"), "nextIs: fields come first"); + uint32_t z1 = 0, z2 = 0; + check(y.sectionLeft() == 8, "sectionLeft: the section's fields"); + state::fields(y, z1); + check(y.sectionLeft() == 4, "sectionLeft: a field is left"); + state::fields(y, z2); + check(y.sectionLeft() == 0 && z2 == 2, "sectionLeft: the section's fields are all read"); + y.end(); + check(y.sectionLeft() == 0, "sectionLeft: no section open"); } } From b1dc62d0026031597db82484276ea5f61bcef287 Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:10:21 +0100 Subject: [PATCH 4/6] libs: IpuStream, a game's own .ipu streams decoded natively (FFmpeg's ipu parser and decoder) For a game that drives the IPU itself to play Sony's ".ipu" files (header "ipum", size, width, height, frame count, then intra-only IPU frames) as animated textures: no IPU, no DMA. open() copies the file and splits its frames with FFmpeg's "ipu" parser; decodeMacroblocks(index, out) gives a frame as the IPU's colour conversion (CSC, RGB32) writes it, 16 x 16 macroblocks in raster order (BT.601 video range), and decodeRaster the picture's rows. Built with BOZO_HAVE_FFMPEG like libmpeg's decoder; without FFmpeg open() fails and the port keeps its own path. JC2 answers its IPU player with it (scene D001's water: 64 x 64, 298 frames decoded into the game's ring). Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 3 +- runtime/include/bozo/libs/ipu_stream.h | 49 ++++++ runtime/libs/ipu_stream.cpp | 214 +++++++++++++++++++++++++ 3 files changed, 265 insertions(+), 1 deletion(-) create mode 100644 runtime/include/bozo/libs/ipu_stream.h create mode 100644 runtime/libs/ipu_stream.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e138030..c5834a7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -38,6 +38,7 @@ add_library(bozo_libs STATIC libs/io.cpp libs/mpeg.cpp libs/mpeg_ffmpeg.cpp + libs/ipu_stream.cpp libs/sif.cpp libs/snd.cpp libs/snd989.cpp) @@ -164,7 +165,7 @@ else() endif() endif() if(BOZO_FFMPEG_FOUND) - set_source_files_properties(libs/mpeg_ffmpeg.cpp PROPERTIES COMPILE_DEFINITIONS BOZO_HAVE_FFMPEG) + set_source_files_properties(libs/mpeg_ffmpeg.cpp libs/ipu_stream.cpp PROPERTIES COMPILE_DEFINITIONS BOZO_HAVE_FFMPEG) message(STATUS "libmpeg: FFmpeg found (native movies)") else() if(BOZO_REQUIRE_FFMPEG) diff --git a/runtime/include/bozo/libs/ipu_stream.h b/runtime/include/bozo/libs/ipu_stream.h new file mode 100644 index 0000000..f7a0a82 --- /dev/null +++ b/runtime/include/bozo/libs/ipu_stream.h @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 The Bozos (boubou666 and Arzaroth). MIT licence (see LICENSE at the repository root). +// +// A game's own IPU streams, decoded natively: the ".ipu" files Sony's IPU sample format defines (header "ipum", u32 file +// size, u16 width, u16 height, u32 frame count, then the frames' IPU bitstream: intra-only MPEG macroblocks). A game +// that drives the IPU itself (BDEC/IDEC commands, the to-IPU and from-IPU DMA channels; JC2's animated textures) can +// answer its decode routine with this instead: no IPU, no DMA. FFmpeg's "ipu" parser splits the frames and its decoder +// decodes them (libavcodec, the same build as libmpeg's; without FFmpeg open() fails and the port keeps its own path). +// +// The output is what the IPU's colour conversion (CSC, RGB32) writes: per 16 x 16 macroblock, in raster order of the +// macroblocks, its 256 pixels row by row, 4 bytes R, G, B, A; or, with decodeRaster, the picture's rows. +#pragma once + +#include +#include +#include + +namespace bozo::libs +{ + class IpuStream + { + public: + IpuStream(); + ~IpuStream(); + IpuStream(const IpuStream &) = delete; + IpuStream &operator=(const IpuStream &) = delete; + + // Whether this build can decode IPU streams (FFmpeg with its "ipu" decoder and parser). + static bool available(); + + // The whole file in memory (copied). False: not an "ipum" file, or no decoder. + bool open(const uint8_t *file, size_t bytes); + bool isOpen() const; + int width() const; + int height() const; + int frames() const; // the frames found in the stream (the header's count when they can all be split) + + // Frame `index` (0-based, any order: IPU frames are intra-only) as RGB32 macroblocks (the CSC's layout above), + // width x height x 4 bytes; alpha is the value given (the CSC's 0x80 when the colour is not under the threshold). + // False: no such frame, or it did not decode (the caller keeps its previous picture). + bool decodeMacroblocks(int index, uint8_t *out, uint8_t alpha = 0x80); + // The same frame as rows of RGBA pixels (width x height x 4 bytes). + bool decodeRaster(int index, uint8_t *out, uint8_t alpha = 0x80); + + private: + struct Impl; + std::unique_ptr impl_; + }; +} diff --git a/runtime/libs/ipu_stream.cpp b/runtime/libs/ipu_stream.cpp new file mode 100644 index 0000000..739feab --- /dev/null +++ b/runtime/libs/ipu_stream.cpp @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 The Bozos (boubou666 and Arzaroth). MIT licence (see LICENSE at the repository root). +// +// A game's own IPU streams (bozo/libs/ipu_stream.h): FFmpeg's "ipu" parser and decoder, built with BOZO_HAVE_FFMPEG +// like libmpeg's decoder (mpeg_ffmpeg.cpp); without FFmpeg, open() fails. +#include "bozo/libs/ipu_stream.h" + +#include +#include +#include + +#ifdef BOZO_HAVE_FFMPEG +extern "C" +{ +#include +#include +} +#endif + +namespace bozo::libs +{ + struct IpuStream::Impl + { + std::vector file; + int width = 0, height = 0; + std::vector> frames; // (offset, bytes) of each frame in `file` +#ifdef BOZO_HAVE_FFMPEG + AVCodecContext *codec = nullptr; + AVPacket *packet = nullptr; + AVFrame *frame = nullptr; + ~Impl() + { + av_frame_free(&frame); + av_packet_free(&packet); + avcodec_free_context(&codec); + } +#endif + }; + + namespace + { + uint32_t le32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24; } + uint16_t le16(const uint8_t *p) { return uint16_t(p[0] | p[1] << 8); } + uint8_t clamp8(int v) { return static_cast(std::clamp(v, 0, 255)); } + + // The IPU's colour conversion (ITU-R BT.601, video range), in 16.16 fixed point. + void yuvToRgb(int y, int cb, int cr, uint8_t *out, uint8_t alpha) + { + const int c = (y - 16) * 76309, d = cb - 128, e = cr - 128; + out[0] = clamp8((c + 104597 * e + 32768) >> 16); + out[1] = clamp8((c - 25675 * d - 53279 * e + 32768) >> 16); + out[2] = clamp8((c + 132201 * d + 32768) >> 16); + out[3] = alpha; + } + } + + IpuStream::IpuStream() = default; + IpuStream::~IpuStream() = default; + + bool IpuStream::available() + { +#ifdef BOZO_HAVE_FFMPEG + return avcodec_find_decoder(AV_CODEC_ID_IPU) != nullptr; +#else + return false; +#endif + } + + bool IpuStream::isOpen() const { return impl_ && !impl_->frames.empty(); } + int IpuStream::width() const { return impl_ ? impl_->width : 0; } + int IpuStream::height() const { return impl_ ? impl_->height : 0; } + int IpuStream::frames() const { return impl_ ? static_cast(impl_->frames.size()) : 0; } + + bool IpuStream::open(const uint8_t *file, size_t bytes) + { + impl_.reset(); +#ifdef BOZO_HAVE_FFMPEG + if (!file || bytes < 16 || std::memcmp(file, "ipum", 4) != 0) + return false; + auto impl = std::make_unique(); + const size_t size = std::min(bytes, std::max(16, le32(file + 4))); + impl->file.assign(file, file + size); + impl->width = le16(file + 8); + impl->height = le16(file + 10); + const uint32_t count = le32(file + 12); + if (impl->width <= 0 || impl->height <= 0 || (impl->width | impl->height) & 15) + return false; + + const AVCodec *decoder = avcodec_find_decoder(AV_CODEC_ID_IPU); + AVCodecParserContext *parser = av_parser_init(AV_CODEC_ID_IPU); + if (!decoder || !parser) + { + if (parser) + av_parser_close(parser); + return false; + } + impl->codec = avcodec_alloc_context3(decoder); + impl->packet = av_packet_alloc(); + impl->frame = av_frame_alloc(); + if (!impl->codec || !impl->packet || !impl->frame) + { + av_parser_close(parser); + return false; + } + impl->codec->width = impl->width; + impl->codec->height = impl->height; + impl->codec->thread_count = 1; + if (avcodec_open2(impl->codec, decoder, nullptr) < 0) + { + av_parser_close(parser); + return false; + } + + // The frames, as the parser splits the stream after the header (as FFmpeg's ipu demuxer feeds it). + const uint8_t *data = impl->file.data() + 16; + size_t left = impl->file.size() - 16, at = 16; + while (true) + { + uint8_t *out = nullptr; + int outBytes = 0; + const int used = av_parser_parse2(parser, impl->codec, &out, &outBytes, left ? data : nullptr, + static_cast(left), AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); + if (used < 0) + break; + if (outBytes > 0 && out) + { + // A frame the parser returns lies in the file (it hands back the input) or in its own buffer when it + // spans calls; find it in the file by its bytes, from where the previous one ended. + const uint8_t *found = std::search(impl->file.data() + at, impl->file.data() + impl->file.size(), out, + out + outBytes); + if (found == impl->file.data() + impl->file.size()) + break; + const size_t offset = static_cast(found - impl->file.data()); + impl->frames.emplace_back(offset, static_cast(outBytes)); + at = offset + static_cast(outBytes); + } + if (!left && outBytes <= 0) + break; + data += used; + left -= static_cast(used); + } + av_parser_close(parser); + if (impl->frames.empty()) + return false; + if (count && impl->frames.size() > count) + impl->frames.resize(count); + impl_ = std::move(impl); + return true; +#else + (void)file; + (void)bytes; + return false; +#endif + } + + bool IpuStream::decodeRaster(int index, uint8_t *out, uint8_t alpha) + { +#ifdef BOZO_HAVE_FFMPEG + if (!isOpen() || index < 0 || index >= frames() || !out) + return false; + Impl &s = *impl_; + const auto [offset, bytes] = s.frames[static_cast(index)]; + if (av_new_packet(s.packet, static_cast(bytes)) < 0) + return false; + std::memcpy(s.packet->data, s.file.data() + offset, bytes); + const int sent = avcodec_send_packet(s.codec, s.packet); + av_packet_unref(s.packet); + if (sent < 0 || avcodec_receive_frame(s.codec, s.frame) < 0) + return false; + const AVFrame &f = *s.frame; + if (f.format != AV_PIX_FMT_YUV420P || f.width < s.width || f.height < s.height) + { + av_frame_unref(s.frame); + return false; + } + for (int y = 0; y < s.height; ++y) + { + const uint8_t *py = f.data[0] + y * f.linesize[0]; + const uint8_t *pu = f.data[1] + (y / 2) * f.linesize[1]; + const uint8_t *pv = f.data[2] + (y / 2) * f.linesize[2]; + uint8_t *row = out + static_cast(y) * s.width * 4; + for (int x = 0; x < s.width; ++x) + yuvToRgb(py[x], pu[x / 2], pv[x / 2], row + x * 4, alpha); + } + av_frame_unref(s.frame); + return true; +#else + (void)index; + (void)out; + (void)alpha; + return false; +#endif + } + + bool IpuStream::decodeMacroblocks(int index, uint8_t *out, uint8_t alpha) + { + if (!isOpen() || !out) + return false; + const int w = impl_->width, h = impl_->height; + std::vector raster(static_cast(w) * h * 4); + if (!decodeRaster(index, raster.data(), alpha)) + return false; + // Macroblocks in raster order, each one's 16 rows of 16 pixels. + uint8_t *dst = out; + for (int my = 0; my < h / 16; ++my) + for (int mx = 0; mx < w / 16; ++mx) + for (int y = 0; y < 16; ++y) + { + std::memcpy(dst, raster.data() + (static_cast(my * 16 + y) * w + mx * 16) * 4, 16 * 4); + dst += 16 * 4; + } + return true; + } +} From 52ac66bb36df0b27f04f6ff023e55db5e588b7be Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:33:52 +0100 Subject: [PATCH 5/6] libs: Libraries::dmaStarted, a port told when the game starts a DMA channel The I/O library completes a channel the game starts (CHCR with STR) at once: no DMA, no VIF, no GIF. A port that needs to know what the game sent can now read the transfer there: dmaStarted(channel, its registers) is called as the channel starts, before the library completes it; unset, nothing changes. JC2 uses it to follow the GS image transfers in its VIF1 and GIF chains (which RAM went to which texture page), for the effects whose texture records are their own. Co-Authored-By: Claude Opus 5.5 --- runtime/include/bozo/libs/libraries.h | 4 ++++ runtime/libs/io.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/runtime/include/bozo/libs/libraries.h b/runtime/include/bozo/libs/libraries.h index 250a14b..1fe712d 100644 --- a/runtime/include/bozo/libs/libraries.h +++ b/runtime/include/bozo/libs/libraries.h @@ -275,6 +275,10 @@ namespace bozo::libs // Optional native audio implementation. Advances to EE time and returns its sample queue. // Unset: the built-in 989SND source. Its lifetime belongs to the port. std::function audioProvider; + // Optional: told when the game starts a DMA channel by its CHCR (channel 0..9 and its registers, STR set), + // before the I/O library completes it. A port reads the transfer's source there (JC2: the GS image transfers + // in its VIF1 and GIF chains, to know which RAM went to which texture page); it must not change them. + std::function dmaStarted; MovieSoundSink *movieSound = nullptr; // the movie's sound (null: dropped) audio::PortStream portStream; IoAccess ioAccess; diff --git a/runtime/libs/io.cpp b/runtime/libs/io.cpp index 544aead..6e8b392 100644 --- a/runtime/libs/io.cpp +++ b/runtime/libs/io.cpp @@ -214,6 +214,8 @@ namespace bozo::libs c.running = false; // STR cleared: the channel stops (TMB stops channel 4 at a movie's end) else if (!c.running) { + if (l.dmaStarted) + l.dmaStarted(static_cast(ch), c); if (ch == 0) l.vu0.kick(v, c.tadr); // VIF0: the microcode image VU0 now holds if (static_cast(ch) == kFromScratchpadChannel || static_cast(ch) == kToScratchpadChannel) From 77096ee2bcdc6cfc1980ca7abafdebc2d28fe21e Mon Sep 17 00:00:00 2001 From: Thomas Martin <304581853+boubou666@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:17:24 +0100 Subject: [PATCH 6/6] Memory cards survive a save state; Archive::end checks before closing A state restored the cards' contents but not their host folder, so a game's saves after --load-state stayed in memory and were lost. Cards kept in a folder are now taken back from the folder when a state loads (a console's memory card is not part of a save state); cards in memory stay the state's. Archive::end closed a section before checking its size: a reader trying an older layout (the libraries' sif section) that failed there rewound into a nameless section and the load failed further on. The check now comes first. Tests for both. Co-Authored-By: Claude Opus 5.5 --- runtime/core/state.cpp | 8 +++++--- runtime/libs/libraries_state.cpp | 9 +++++++++ tests/libs/libs_tests.cpp | 30 ++++++++++++++++++++++++++++++ tests/runtime/state_tests.cpp | 20 ++++++++++++++++++++ 4 files changed, 64 insertions(+), 3 deletions(-) diff --git a/runtime/core/state.cpp b/runtime/core/state.cpp index b5f6985..35b65b7 100644 --- a/runtime/core/state.cpp +++ b/runtime/core/state.cpp @@ -67,15 +67,17 @@ namespace bozo::state if (open_.empty()) throw Error("save state: a section ended twice"); const auto [name, at] = open_.back(); + // Checked before the section is closed: a reader that tries an older layout and rewinds (Mark) finds the + // section still open (closed first, the rewind reopened it as a nameless one ending at 0). + if (loading_ && pos_ != at) + throw Error("save state: section " + name + " has " + std::to_string(at - pos_) + + " bytes its reader did not take (a different build wrote it?)"); open_.pop_back(); if (!loading_) { const uint64_t size = data_.size() - at - sizeof(uint64_t); std::memcpy(data_.data() + at, &size, sizeof size); } - else if (pos_ != at) - throw Error("save state: section " + name + " has " + std::to_string(at - pos_) + - " bytes its reader did not take (a different build wrote it?)"); } void writeFile(const std::string &path, const std::string &game, const Archive &a) diff --git a/runtime/libs/libraries_state.cpp b/runtime/libs/libraries_state.cpp index abbbfad..da9b576 100644 --- a/runtime/libs/libraries_state.cpp +++ b/runtime/libs/libraries_state.cpp @@ -169,6 +169,15 @@ namespace bozo::libs c.serialize(a); fields(a, mc.formatted, mc.slotMask, mc.date, mc.known, mc.unformatted, mc.pending, mc.function, mc.result, mc.files, mc.nextDescriptor, mc.currentDirectory, mc.directoryCursor); + // Cards kept in a host folder stay the folder's, as a console's memory card is not part of a save state: a + // state loaded takes them back from the folder (else the state's card, its host folder unknown, kept the + // game's saves in memory only and lost them). Cards in memory (no folder) are the state's. + if (a.loading() && !mc.hostDirectory.empty()) + { + for (size_t p = 0; p < mc.cards.size(); ++p) + mc.cards[p].format(mc.hostDirectory + "/mc" + std::to_string(p), mc.date); + mc.formatted = true; + } a.end(); a.begin("cd"); diff --git a/tests/libs/libs_tests.cpp b/tests/libs/libs_tests.cpp index df57ac3..500e59e 100644 --- a/tests/libs/libs_tests.cpp +++ b/tests/libs/libs_tests.cpp @@ -363,6 +363,35 @@ void nativeCardFlushPersistence() { std::filesystem::remove(root/"mc0"/"save"); std::filesystem::remove(root/"mc0");std::filesystem::remove(root/"mc1");std::filesystem::remove(root); } +// A card kept in a host folder is not part of a save state: loading a state takes it back from the folder, and the +// game's writes after it reach the folder (a state's card in memory had no folder and lost them). +void nativeCardStateKeepsHostFolder() { + const auto root=std::filesystem::temp_directory_path()/ + ("bozo-mc-state-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::vector saved; + { + Machine m; // the state's machine: a card in memory with a file of its own + m.call("sceMcGetInfo",{0,0,0,0,0});m.result(); + m.string(0x110000,"state-only");m.call("sceMcOpen",{0,0,0x110000,0x203});const auto fd=m.result(); + m.call("sceMcClose",{uint32_t(fd)});m.result(); + bozo::state::Archive w;m.libs.serialize(w);saved=w.data(); + } + { + std::filesystem::create_directories(root/"mc0"); + std::ofstream(root/"mc0"/"kept",std::ios::binary)<<"kept"; + } + { + Machine m;m.libs.mc.hostDirectory=root.string(); + bozo::state::Archive r(saved);m.libs.serialize(r); + eq("folder's file after a state",m.libs.mc.card(0).find("kept")!=nullptr,1); + eq("state's own card dropped",m.libs.mc.card(0).find("state-only")==nullptr,1); + m.string(0x110000,"after");m.call("sceMcOpen",{0,0,0x110000,0x203});const auto fd=m.result(); + m.string(0x111000,"x");m.call("sceMcWrite",{uint32_t(fd),0x111000,1});m.result(); + m.call("sceMcClose",{uint32_t(fd)});m.result(); + eq("write after a state on the host",std::filesystem::exists(root/"mc0"/"after"),1); + } + std::error_code ec;std::filesystem::remove_all(root,ec); +} void liveScriptInput() { const auto path=std::filesystem::temp_directory_path()/ ("bozo-live-pad-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); @@ -991,6 +1020,7 @@ int main() sifAndSnd(); memoryCard(); nativeCardFlushPersistence(); + nativeCardStateKeepsHostFolder(); heapAndRand(); cdStream(); std::printf("%s\n", g_failures ? "FAILED" : "all passed"); diff --git a/tests/runtime/state_tests.cpp b/tests/runtime/state_tests.cpp index 65c2639..e9e5b70 100644 --- a/tests/runtime/state_tests.cpp +++ b/tests/runtime/state_tests.cpp @@ -148,6 +148,26 @@ namespace state::fields(x, rAfter); x.end(); check(r1 == 1 && r2 == 2 && rAfter == 3 && x.atEnd(), "rewound to the mark, read in the older layout"); + // A mark inside a section: a trial read that takes too few bytes fails at the section's end (the libraries' + // sif section tries its older layout so); the section stays open for the rewind and the read goes on. + { + state::Archive inner(old.data()); + uint32_t a1 = 0, a2 = 0, aAfter = 0; + inner.begin("s"); + const state::Archive::Mark at = inner.mark(); + check(throws([&] { + state::fields(inner, a1); + inner.end(); + }), + "a shorter trial read fails at the section's end"); + inner.rewind(at); + state::fields(inner, a1, a2); + inner.end(); + inner.begin("next"); + state::fields(inner, aAfter); + inner.end(); + check(a1 == 1 && a2 == 2 && aAfter == 3 && inner.atEnd(), "rewound inside the section, read on"); + } state::Archive y(old.data()); check(y.nextIs("s") && !y.nextIs("next") && !y.nextIs("ss"), "nextIs names the coming section"); y.begin("s");