Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,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)
Expand Down Expand Up @@ -165,7 +166,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)
Expand Down
18 changes: 14 additions & 4 deletions runtime/core/runtime_core.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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;
Expand Down
8 changes: 5 additions & 3 deletions runtime/core/state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
49 changes: 49 additions & 0 deletions runtime/include/bozo/libs/ipu_stream.h
Original file line number Diff line number Diff line change
@@ -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 <cstddef>
#include <cstdint>
#include <memory>

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> impl_;
};
}
4 changes: 4 additions & 0 deletions runtime/include/bozo/libs/libraries.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<audio::Mixer *(uint64_t)> 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<void(uint32_t channel, const IoState::Channel &)> dmaStarted;
MovieSoundSink *movieSound = nullptr; // the movie's sound (null: dropped)
audio::PortStream portStream;
IoAccess ioAccess;
Expand Down
5 changes: 4 additions & 1 deletion runtime/include/bozo/runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint8_t> identity, const BozoFunctionEntry *functions, size_t count,
Expand All @@ -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<uint8_t> identity;
const BozoFunctionEntry *functions;
Expand Down
6 changes: 6 additions & 0 deletions runtime/include/bozo/state.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions runtime/libs/io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint32_t>(ch), c);
if (ch == 0)
l.vu0.kick(v, c.tadr); // VIF0: the microcode image VU0 now holds
if (static_cast<uint32_t>(ch) == kFromScratchpadChannel || static_cast<uint32_t>(ch) == kToScratchpadChannel)
Expand Down
214 changes: 214 additions & 0 deletions runtime/libs/ipu_stream.cpp
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cstring>
#include <vector>

#ifdef BOZO_HAVE_FFMPEG
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/frame.h>
}
#endif

namespace bozo::libs
{
struct IpuStream::Impl
{
std::vector<uint8_t> file;
int width = 0, height = 0;
std::vector<std::pair<size_t, size_t>> 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<uint8_t>(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<int>(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<Impl>();
const size_t size = std::min<size_t>(bytes, std::max<size_t>(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<int>(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<size_t>(found - impl->file.data());
impl->frames.emplace_back(offset, static_cast<size_t>(outBytes));
at = offset + static_cast<size_t>(outBytes);
}
if (!left && outBytes <= 0)
break;
data += used;
left -= static_cast<size_t>(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<size_t>(index)];
if (av_new_packet(s.packet, static_cast<int>(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<size_t>(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<uint8_t> raster(static_cast<size_t>(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<size_t>(my * 16 + y) * w + mx * 16) * 4, 16 * 4);
dst += 16 * 4;
}
return true;
}
}
Loading
Loading