// libmpeg (libraries.md section 9): sceMpegInit, sceMpegCreate, sceMpegDelete, sceMpegReset, sceMpegAddCallback, // sceMpegAddStrCallback, sceMpegDemuxPssRing, sceMpegGetPicture, sceMpegIsEnd, and the reference's stub of the game's // own videoCallback. Every rule here was settled on the call logs (the records are named in libraries.md). #include "bozo/libs/libraries.h" #include "bozo/render/movie.h" #include "bozo/ee/dispatcher.h" #include #include #include #include #include namespace bozo::libs { namespace { constexpr uint32_t kFieldsPerPicture = 2; // TMB's movies: 29.97 pictures a second, two fields each constexpr uint32_t kCbNodata = 1; // sceMpegAddCallback type constexpr uint32_t kStrVideo = 0, kStrPcm = 2; // sceMpegAddStrCallback types // A demux call after a refused sound packet: 0.2 ms of the EE (the console's player spends at least that a turn). constexpr uint64_t kRefusedDemuxCycles = 294912000u / 5000u; MpegState &state(Libraries &l) { return l.mpeg; } // ---- The picture as the game receives it ---- uint8_t clamp(int v) { return static_cast(v < 0 ? 0 : v > 255 ? 255 : v); } // RGBA32, alpha 0x80, in 16 x 16 macroblocks in column-major order (macroblock (x, y) at x * rows + y), each // pixel from its Y and its 2 x 2 block's Cb and Cr with the reference's fixed-point terms (13 fraction bits, // each product shifted on its own). std::vector toGame(const YuvPicture &p) { const int w = p.width, h = p.height, mbw = w / 16, mbh = h / 16; std::vector out(static_cast(w) * h * 4); size_t o = 0; for (int mx = 0; mx < mbw; ++mx) for (int my = 0; my < mbh; ++my) for (int yy = 0; yy < 16; ++yy) for (int xx = 0; xx < 16; ++xx) { const int x = mx * 16 + xx, y = my * 16 + yy; const int Y = p.y[static_cast(y) * w + x]; const size_t ci = static_cast(y / 2) * (w / 2) + x / 2; const int U = p.u[ci] - 128, V = p.v[ci] - 128; const int l = (9539 * (Y - 16)) >> 13; out[o++] = clamp(l + ((13074 * V) >> 13)); out[o++] = clamp(l + ((-3210 * U) >> 13) + ((-6660 * V) >> 13)); out[o++] = clamp(l + ((16524 * U) >> 13)); out[o++] = 0x80; } return out; } // ---- The video elementary stream ---- // New bytes of the video stream: its start codes counted (pictures and the sequence end, once whole in the // stream) and the cuts into coded pictures (each picture's data begins at its first sequence or GOP header, else // at its picture header). void scan(MpegState &s) { size_t i = s.scanned; while (i + 4 <= s.es.size()) { if (s.es[i] == 0 && s.es[i + 1] == 0 && s.es[i + 2] == 1) { const uint8_t code = s.es[i + 3]; if (code == 0x00) { if (!s.headerOpen) s.cuts.push_back(i); s.headerOpen = false; ++s.starts; ++s.pictureStarts; } else if (code == 0xB3 || code == 0xB8) { if (!s.headerOpen) s.cuts.push_back(i); s.headerOpen = true; } else if (code == 0xB7) { ++s.starts; s.sequenceEnd = true; } i += 4; continue; } ++i; } s.scanned = i; } bool ended(const MpegState &s) { return s.sequenceEnd || s.programEnd || s.inputEnded; } // Whether display picture k can be decoded: its data and the next picture's are whole (the decoder holds one // picture back), or the stream has ended and its data is whole. bool available(const MpegState &s, uint32_t k) { if (ended(s)) return true; // past the last picture: an empty delivery (libraries.md section 9) const uint32_t complete = s.starts ? s.starts - 1 : 0; return k + 1 < complete; } // Coded pictures to the decoder as their data becomes whole; at the end, the rest and a flush. void pump(MpegState &s) { if (!s.decoder) return; while (s.sent + 1 < s.cuts.size()) { s.decoder->picture(s.es.data() + s.cuts[s.sent], s.cuts[s.sent + 1] - s.cuts[s.sent]); ++s.sent; } if (ended(s) && !s.flushed) { if (s.sent < s.cuts.size()) { s.decoder->picture(s.es.data() + s.cuts[s.sent], s.es.size() - s.cuts[s.sent]); ++s.sent; } s.decoder->flush(); s.flushed = true; } YuvPicture p; while (s.decoder->next(p)) s.decoded.push_back(std::move(p)); } // ---- The sound stream ---- uint32_t le32(const uint8_t *p) { return p[0] | (p[1] << 8) | (p[2] << 16) | (static_cast(p[3]) << 24); } void sound(Libraries &l, MpegState &s, const uint8_t *payload, size_t bytes, int64_t pts) { if (bytes < 4) return; const uint8_t *p = payload + 4; // the sub-stream header size_t n = bytes - 4; if (!s.soundHeader && n >= 40 && std::memcmp(p, "SShd", 4) == 0) { s.sound.format = le32(p + 8); s.sound.rate = le32(p + 12); s.sound.channels = le32(p + 16); s.sound.interleave = le32(p + 20); s.soundHeader = true; if (l.movieSound) l.movieSound->format(s.sound); const size_t header = 8 + le32(p + 4) + 8; // SShd and its size, then "SSbd" and its size p += header; n -= std::min(n, header); } if (!l.movieSound || !s.soundHeader || s.sound.channels == 0 || s.sound.interleave == 0) return; s.soundCarry.insert(s.soundCarry.end(), p, p + n); const size_t block = static_cast(s.sound.interleave) * s.sound.channels; const size_t blocks = s.soundCarry.size() / block; if (!blocks) return; const size_t perChannel = s.sound.interleave / 2; std::vector frames(blocks * perChannel * s.sound.channels); for (size_t b = 0; b < blocks; ++b) for (size_t c = 0; c < s.sound.channels; ++c) for (size_t i = 0; i < perChannel; ++i) { const uint8_t *q = s.soundCarry.data() + b * block + c * s.sound.interleave + i * 2; frames[(b * perChannel + i) * s.sound.channels + c] = static_cast(q[0] | (q[1] << 8)); } s.soundCarry.erase(s.soundCarry.begin(), s.soundCarry.begin() + static_cast(blocks * block)); l.movieSound->samples(frames.data(), blocks * perChannel, pts); } // ---- The demux ---- // The stream callbacks' entries (MpegState::entriesInUse): the first of the work area's last kEntries x 32 bytes, // or none (0) when the reference's layout is wanted or the work area is too small to give them. uint32_t entryPool(const Libraries &l, const MpegState &s) { constexpr uint32_t bytes = MpegState::kEntries * 0x20u; if (l.mpegOptions.referenceLayout || !s.work || s.size < 4u * bytes) return 0; return (s.work + s.size - bytes) & ~0xFu; } // A callback entry: a free one of the work area's, else (the reference's layout, or all of them waiting) 32 bytes // of the game's heap. uint32_t takeEntry(Libraries &l, MpegState &s) { if (const uint32_t pool = entryPool(l, s)) for (uint32_t k = 0; k < MpegState::kEntries; ++k) if (!(s.entriesInUse & (1ull << k))) { s.entriesInUse |= 1ull << k; return pool + 0x20u * k; } return l.gameHeap().allocate(0x20); } void releaseEntry(Libraries &l, MpegState &s, uint32_t entry) { const uint32_t pool = entryPool(l, s); if (pool && entry >= pool && entry < pool + MpegState::kEntries * 0x20u) s.entriesInUse &= ~(1ull << ((entry - pool) / 0x20u)); else l.gameHeap().release(entry); } int64_t timestamp(const uint8_t *b) { return (static_cast((b[0] >> 1) & 7) << 30) | (static_cast(b[1]) << 22) | (static_cast(b[2] >> 1) << 15) | (static_cast(b[3]) << 7) | (b[4] >> 1); } // The decoder's or the sound sink's share of a stream packet. void take(Libraries &l, MpegState &s, uint8_t id, const uint8_t *data, size_t length, int64_t pts) { if (id == 0xE0) { s.es.insert(s.es.end(), data, data + length); scan(s); } else if (id == 0xBD) sound(l, s, data, length, pts); } // A stream packet whole in the demux: its callback, if the game registered one for its stream (its data, the // callback queued as a handler on the calling thread, kind 4), and the decoder's or the sound sink's share of it // (with MpegOptions::sdkDemux, held until the callback took the packet). void packet(Libraries &l, Guest &g, MpegState &s, uint64_t at, uint8_t id, size_t payload, size_t length, int64_t pts, int64_t dts) { const uint8_t *data = s.pending.data() + (at - s.pendingAt) + payload; const int type = id == 0xE0 ? static_cast(kStrVideo) : id == 0xBD ? static_cast(kStrPcm) : -1; const bool callback = type >= 0 && s.strCallbacks[type].set; if (callback && l.mpegOptions.sdkDemux) { s.heldAt = at; s.heldId = id; s.held.assign(data, data + length); s.heldPts = pts; } else take(l, s, id, data, length, pts); if (!callback) return; const MpegState::Callback &cb = s.strCallbacks[type]; const uint64_t streamAt = at + payload; const uint32_t pointer = s.ring ? s.ring + static_cast((streamAt + s.ringBias) % s.ringSize) : static_cast(s.linearBase + streamAt); // The callback's data: 32 bytes given back as its handler ends; from the game's heap with the reference's // layout (its addresses show where the game's own blocks are), else from the work area (takeEntry). const uint32_t entry = takeEntry(l, s); uint8_t e[32] = {}; const uint32_t words[4] = {static_cast(type), 0, pointer, static_cast(length)}; std::memcpy(e, words, 16); std::memcpy(e + 16, &pts, 8); std::memcpy(e + 24, &dts, 8); g.write(entry, e, 32); ee::QueuedHandler h; h.kind = ee::kInvokeRpcCallback; h.pc = cb.function; h.a[0] = s.mp; h.a[1] = entry; h.a[2] = cb.data; h.gp = cb.gp; h.completion = true; s.callbacksDue.push_back({h, entry}); // queued once the call's demux is done } // Whole packets out of the bytes taken so far (none after the program end). void parse(Libraries &l, Guest &g, MpegState &s) { size_t i = 0; const std::vector &p = s.pending; if (s.programEnd) i = p.size(); while (!s.programEnd && i + 4 <= p.size()) { if (!(p[i] == 0 && p[i + 1] == 0 && p[i + 2] == 1)) { ++i; continue; } const uint8_t id = p[i + 3]; size_t total = 0; if (id == 0xBA) { if (i + 14 > p.size()) break; total = (p[i + 4] >> 6) == 1 ? 14 + (p[i + 13] & 7) : 12; } else if (id == 0xB9) { // The program end: counted as one more start towards the demux's limit; what follows is not read. s.programEnd = true; ++s.starts; i = p.size(); break; } else if (id >= 0xBB) { if (i + 6 > p.size()) break; total = 6 + ((p[i + 4] << 8) | p[i + 5]); } else { ++i; continue; } if (i + total > p.size()) break; if (id == 0xE0 || id == 0xBD || (id >= 0xC0 && id < 0xE0)) { const uint8_t flags = p[i + 7]; const size_t payload = 9 + p[i + 8]; const int64_t pts = (flags & 0x80) ? timestamp(&p[i + 9]) : -1; const int64_t dts = (flags & 0x40) ? timestamp(&p[i + 14]) : -1; packet(l, g, s, s.pendingAt + i, id, payload, total - payload, pts, dts); } i += total; if (l.mpegOptions.sdkDemux && !s.callbacksDue.empty()) break; // the callback runs before the demux goes on } s.pending.erase(s.pending.begin(), s.pending.begin() + static_cast(i)); s.pendingAt += i; } // ---- The functions ---- // sceMpegInit(): 0 (the SDK's 1 off the reference layout). Nothing is reset: a game may call it from its Nodata // callback, in the middle of a stream. void init(Libraries &l, Guest &g) { g.ret(l.mpegOptions.referenceLayout ? 0 : 1); } // sceMpegCreate(mp, work, size): the sceMpeg and its work area as the reference sets them, 0x600 bytes from the // game's heap; returns work + 0x118. void create(Libraries &l, Guest &g) { MpegState &s = state(l); const uint32_t mp = g.arg(0), work = g.arg(1), size = g.arg(2); s = MpegState{}; s.active = true; s.mp = mp; s.work = work; s.size = size; s.decoder = makeVideoDecoder(); if (!l.mpegOptions.referenceLayout) { if (l.movieSound) l.movieSound->start(); g.ret(1); return; } s.block = l.gameHeap().allocate(0x600); const uint32_t table[9] = {0x171A50, 0x171C58, 0x171CC0, 0x171D28, 0x171D90, 0x171AB8, 0x171B20, 0x171B88, 0x171BF0}; g.write32(0x1717BC, mp); g.write(0x171800, table, sizeof(table)); g.fill(mp, 0, 8); g.fill(mp + 0x10, 0xFF, 16); g.fill(mp + 0x28, 0xFF, 16); g.write32(mp + 0x40, work); g.write32(work + 0x1C, 0x1209F8); g.write32(work + 0x24, 0x120A08); g.write32(work + 0x44, s.block); g.write32(work + 0x80, 0xFFFFFFFFu); g.fill(work + 0x94, 0xFF, 12); g.write8(work + 0xB0, 1); g.write32(work + 0xD8, 0); g.write32(work + 0xE4, 0); g.fill(work + 0xF0, 0xFF, 8); g.write32(work + 0x108, work + 0x118); g.write32(work + 0x10C, size - 0x118); g.write32(work + 0x110, work + 0x118); g.write32(work + 0x114, work + 0x118); if (l.movieSound) l.movieSound->start(); g.retU(work + 0x118); } // sceMpegDelete(mp): 0 (the SDK's 1 off the reference layout). void destroy(Libraries &l, Guest &g) { MpegState &s = state(l); s.active = false; s.decoder.reset(); s.decoded.clear(); if (l.movieSound) l.movieSound->stop(); g.ret(l.mpegOptions.referenceLayout ? 0 : 1); } // sceMpegReset(mp): the picture count and libmpeg's static word at 0x171904 cleared (no result). void reset(Libraries &l, Guest &g) { g.write32(g.arg(0) + 8, 0); if (l.mpegOptions.referenceLayout) g.write32(0x171904, 0); } // sceMpegAddCallback(mp, type, function, data): how many callbacks are set (1, 2, ...). void addCallback(Libraries &l, Guest &g) { MpegState &s = state(l); const uint32_t type = g.arg(1); const uint32_t previous = type < 8 ? s.callbacks[type].function : 0; if (type < 8) s.callbacks[type] = {g.arg(2), g.arg(3), g.context()->r[28].uw[0], true}; ++s.callbacksAdded; if (l.mpegOptions.referenceLayout) g.ret(static_cast(s.callbacksAdded)); else g.retU(previous); // the SDK's: the callback the type had } // sceMpegAddBs(mp, data, bytes): coded video for the decoder, as the game reads it (no program stream). The // SDK sends ((bytes + 19) >> 4) << 4 bytes to the IPU, so as many are taken. 1. void addBs(Libraries &l, Guest &g) { MpegState &s = state(l); const uint32_t data = g.arg(1), bytes = ((g.arg(2) + 19u) >> 4) << 4; const size_t at = s.es.size(); s.es.resize(at + bytes); for (uint32_t k = 0; k < bytes; ++k) s.es[at + k] = g.read8(data + k); scan(s); if (s.waiting && available(s, s.delivered)) { l.dispatcher()->kernel().wake(s.waiting, 0, true, ee::kWaitMpeg); s.waiting = 0; } g.ret(1); } // sceMpegAddStrCallback(mp, type, channel, function, data): 0. void addStrCallback(Libraries &l, Guest &g) { MpegState &s = state(l); const uint32_t type = g.arg(1); if (type < 8) s.strCallbacks[type] = {g.arg(3), g.arg(4), g.context()->r[28].uw[0], true}; g.ret(0); } // What the demux counts as read ahead: the coded pictures begun (a picture's data begins at its sequence or GOP // header when it has one, so a header whole in the stream counts its picture before the picture start code // arrives: stage-level0 #11640007, the Suburbs movie, stops at 0xd000 bytes where the header of picture 42 is // whole and its start code not yet), the sequence end and the program end. uint32_t ahead(const MpegState &s) { return static_cast(s.cuts.size()) + (s.sequenceEnd ? 1u : 0u) + (s.programEnd ? 1u : 0u); } // sceMpegDemuxPssRing(mp, data, bytes, ring, ringSize): with ring 0 (sceMpegDemuxPss) `data` is read straight // and ringSize is not an argument. A sector at a time while fewer than MpegOptions::picturesAhead // pictures are ahead of the game (ahead(): the coded pictures begun, the sequence end and the program end, less // those delivered; nothing after the program end is read); each whole packet of a registered stream gets its // callback. Returns the bytes taken. void demuxOn(Libraries &l, Guest &g, uint32_t bytes); // Stream bytes [from, from + n) appended to the pending bytes: read from the ring (in one or two runs, where it // wraps) or from the call's data, a run at a time (a byte at a time took most of a movie's time: the SDK demux // reads again what follows the last whole packet at each call). void appendStream(Guest &g, MpegState &s, uint64_t from, uint32_t n) { if (s.ring) { uint32_t at = static_cast((from + s.ringBias) % s.ringSize); while (n) { const uint32_t run = std::min(n, s.ringSize - at); const uint8_t *p = g.in(s.ring + at, run); s.pending.insert(s.pending.end(), p, p + run); n -= run; at = 0; } } else if (n) { const uint8_t *p = g.in(static_cast(s.linearBase + from), n); s.pending.insert(s.pending.end(), p, p + n); } } void demux(Libraries &l, Guest &g) { MpegState &s = state(l); if (s.demuxResuming) // the same call again after its callback (MpegOptions::callbacksOnCaller) { s.demuxResuming = false; demuxOn(l, g, s.demuxBytes); return; } const uint32_t data = g.arg(1), bytes = g.arg(2); s.ring = g.arg(3); s.ringSize = s.ring ? g.arg(4) : 0; if (s.ring && !s.ringSize) { g.ret(0); return; } if (s.ring) s.ringBias = static_cast(((data - s.ring) + s.ringSize - (s.consumed % s.ringSize)) % s.ringSize); else s.linearBase = data - s.consumed; if (l.mpegOptions.sdkDemux) { // A demux call after one a sound packet's callback refused (the game's sound ring full) costs EE time: // on the console the player's turn between them (the demux, the IPU's decoding) takes some, here none, // and a player spinning until its sound thread makes room called the callback about 9,000 times a // field (Shinobido's movies ran at 60% speed, the host's time spent in the handlers). if (s.refused) g.cycles = l.callCycles(kRefusedDemuxCycles); s.callAt = s.consumed; s.refused = false; demuxOn(l, g, bytes); return; } uint32_t taken = 0; while (taken + 0x800 <= bytes && ahead(s) < s.delivered + l.mpegOptions.picturesAhead) { appendStream(g, s, s.consumed, 0x800); s.consumed += 0x800; taken += 0x800; parse(l, g, s); } // A thread waiting for the data that is now there is woken first, then the packets' callbacks are queued. if (s.waiting && available(s, s.delivered)) { l.dispatcher()->kernel().wake(s.waiting, 0, true, ee::kWaitMpeg); s.waiting = 0; } for (const MpegState::DueCallback &c : s.callbacksDue) { const uint32_t entry = c.entry; if (l.mpegOptions.callbacksOnCaller) l.queueHandlerOn(c.handler, l.dispatcher()->kernel().running(), Resume{kResumeMpegRelease, {entry}}); else l.queueHandler(c.handler, Resume{kResumeMpegRelease, {entry}}); } s.callbacksDue.clear(); g.ret(static_cast(taken)); } // The SDK's demux (MpegOptions::sdkDemux), from the call's start or as its thread resumes after a callback: // the bytes given read as the packets need them (while fewer than picturesAhead pictures are ahead), each // packet with a callback stopping the demux until its handler ends (the thread waits for it), a packet refused // ending the call before it. The call returns the bytes of the whole packets taken; what follows them is read // again by the next call. void demuxOn(Libraries &l, Guest &g, uint32_t bytes) { MpegState &s = state(l); while (!s.refused) { parse(l, g, s); if (!s.callbacksDue.empty()) { const MpegState::DueCallback c = s.callbacksDue.front(); s.callbacksDue.clear(); const int32_t thread = l.dispatcher()->kernel().running(); if (l.mpegOptions.callbacksOnCaller) { // On this thread, as the SDK calls it; the call is made again after it and goes on from here. l.queueHandlerOn(c.handler, thread, Resume{kResumeMpegDemuxCallbackEnd, {0u, c.entry}}); s.demuxResuming = true; s.demuxBytes = bytes; l.restartCall(); return; } l.queueHandler(c.handler, Resume{kResumeMpegDemuxCallbackEnd, {static_cast(thread), c.entry}}); l.waitFor(ee::kWaitMpeg, 2, s.mp, 0, Resume{kResumeMpegDemuxNext, {bytes}}); return; } const uint64_t read = s.consumed - s.callAt; if (s.programEnd || read >= bytes || ahead(s) >= s.delivered + l.mpegOptions.picturesAhead) break; const uint32_t chunk = static_cast(std::min(0x800, bytes - read)); appendStream(g, s, s.consumed, chunk); s.consumed += chunk; } // A part packet stays in the ring. s.pending.clear(); s.consumed = s.pendingAt; if (s.waiting && available(s, s.delivered)) { l.dispatcher()->kernel().wake(s.waiting, 0, true, ee::kWaitMpeg); s.waiting = 0; } g.ret(static_cast(s.pendingAt - s.callAt)); } // sceMpegIsEnd(mp): 1 once the stream has ended, every picture was delivered and the last one's display time is // over (the vblank count past the first's plus two fields a picture); until then a sceMpegGetPicture gets an // empty delivery. When the game took the last picture late (story's seventh movie, played one picture a game // frame: picture 45 at base + 91; #11644213: 0 at base + 92, then an empty delivery and #11644909: 1), not before // an empty delivery (boot, match1p and story's other movies took theirs at base + 2 x n or earlier). Once the // port says the playback was aborted (a skipped movie), 1 (story #9723824: the abort, a // picture delivered, then 1 with 7 of the stream's pictures never delivered). void isEnd(Libraries &l, Guest &g) { const MpegState &s = state(l); if (!l.mpegOptions.paced) { // The game paces itself: the end once the input has ended and every picture has gone out. g.ret(s.aborted || (ended(s) && s.flushed && s.decoded.empty() && s.delivered >= s.pictureStarts) ? 1 : 0); return; } const uint64_t endsAt = s.base + static_cast(kFieldsPerPicture) * s.pictureStarts; // A last picture the game took late (after its two fields' slot: base + 2 x its number) is still on screen: // 0 until an empty delivery has counted one more slot. const bool late = s.lastShown > s.base + static_cast(kFieldsPerPicture) * s.delivered; g.ret(s.aborted || (ended(s) && s.delivered >= s.pictureStarts && !late && l.dispatcher()->kernel().vblankCount() > endsAt) ? 1 : 0); } // The picture to the game: its pixels, the sceMpeg's size and picture index, the work area's buffer and size. void deliver(Libraries &l, Guest &g, uint32_t rgb, uint32_t mbcount) { MpegState &s = state(l); pump(s); if (!s.decoded.empty()) // none past the last picture: an empty delivery { const YuvPicture &p = s.decoded.front(); if (std::getenv("BOZO_TIMING_LOG")) { const int64_t ns = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()).count(); if (!s.firstPictureNs) s.firstPictureNs = ns; if (s.delivered % 30u == 0u) std::fprintf(stderr, "[mpeg:clock] picture %u at %.6f s, vblank %llu, EE %.6f s\n", s.delivered, (ns - s.firstPictureNs) / 1e9, static_cast(l.dispatcher()->kernel().vblankCount()), l.dispatcher()->now() / 294912000.0); } const std::vector pixels = toGame(p); g.write(rgb, pixels.data(), static_cast(pixels.size())); // A port that shows the movie itself (bozo/render/movie.h) gets the picture in rows. if (const bozo::render::MoviePictureHook hook = bozo::render::moviePictureHook()) { const int w = p.width, h = p.height, mbh = h / 16; std::vector rows(pixels.size()); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { const size_t from = ((static_cast(x / 16) * mbh + y / 16) * 256 + (y % 16) * 16 + x % 16) * 4; std::memcpy(&rows[(static_cast(y) * w + x) * 4], &pixels[from], 4); } hook(rgb, static_cast(w), static_cast(h), rows.data()); } g.write32(s.mp, static_cast(p.width)); g.write32(s.mp + 4, static_cast(p.height)); s.decoded.pop_front(); s.lastShown = l.dispatcher()->kernel().vblankCount(); } if (s.delivered == 0) s.base = l.dispatcher()->kernel().vblankCount() - 1; g.write32(s.mp + 8, s.delivered); g.write32(s.work + 0xD8, rgb); g.write32(s.work + 0xE4, mbcount); ++s.delivered; g.ret(0); } void getPictureOn(Libraries &l, Guest &g, uint32_t rgb, uint32_t mbcount); // sceMpegGetPicture(mp, rgb32, mbcount): the next picture. Not decodable yet: the game's nodata callback is queued // as a library handler (kind 7) and the thread waits for libmpeg's picture (its end wakes it; as it resumes // this is decided again). Not due yet (two fields a picture from the first): a vblank wait, the picture // delivered as the thread resumes. Else delivered now; 0. void getPicture(Libraries &l, Guest &g) { getPictureOn(l, g, g.arg(1), g.arg(2)); } void getPictureOn(Libraries &l, Guest &g, uint32_t rgb, uint32_t mbcount) { MpegState &s = state(l); ee::Kernel &k = l.dispatcher()->kernel(); if (!available(s, s.delivered)) { const uint8_t data[32] = {static_cast(kCbNodata)}; const bool reference = l.mpegOptions.referenceLayout, sdk = l.mpegOptions.sdkNodata; // The callback's data: from the game's heap (the reference's), or the work area's first bytes. const uint32_t entry = reference ? l.gameHeap().allocate(0x20) : s.work; g.write(entry, data, 32); const MpegState::Callback &cb = s.callbacks[kCbNodata]; ee::QueuedHandler h; h.kind = ee::kInvokeLibraryCall; h.pc = cb.function; h.a[0] = s.mp; h.a[1] = entry; if (sdk) h.a[2] = cb.data; h.gp = cb.gp; h.completion = true; const int32_t thread = k.running(); // Its end wakes the thread, unless a demux already did. With the SDK's callback, a 0 it returns ends the // input. a[2] flags (0 keeps the reference's behaviour): 1 the entry is the work area (nothing to // release), 2 the SDK's callback (its 0 ends the input). const uint32_t flags = (reference ? 0u : 1u) | (sdk ? 2u : 0u); if (l.mpegOptions.callbacksOnCaller) { // On this thread, as the SDK's sceMpegGetPicture calls it while no picture is decodable; the call // is made again after it (and calls it again, until a picture is there). l.queueHandlerOn(h, thread, Resume{kResumeMpegNodataEnd, {0u, entry, flags}}); l.io.ipuDemand = true; l.restartCall(); return; } l.queueHandler(h, Resume{kResumeMpegNodataEnd, {static_cast(thread), entry, flags}}); l.io.ipuDemand = true; // the IPU's input was taken (libraries.md section 11) s.waiting = thread; l.waitFor(ee::kWaitMpeg, 1, s.mp, 0, Resume{kResumeMpegGetPicture, {rgb, mbcount}}); return; } if (l.mpegOptions.paced && s.delivered > 0 && !(ended(s) && s.delivered >= s.pictureStarts)) // the empty delivery is not paced { const uint64_t due = s.base + kFieldsPerPicture * s.delivered; if (k.vblankCount() <= due) { l.waitVblank(due, -1, Resume{kResumeMpegDeliver, {rgb, mbcount}}); return; } } deliver(l, g, rgb, mbcount); } // The reference's stub of TMB's videoCallback (the game's own, 0x1ec2c8): 1, nothing copied (the decoder takes // the video from the demux). void videoCallback(Libraries &, Guest &g) { g.ret(1); } } // The movie library's continuations (libraries.h ResumeKind). void mpegResume(Libraries &l, Guest &g, const Resume &r) { switch (r.kind) { case kResumeMpegRelease: releaseEntry(l, state(l), r.a[0]); break; case kResumeMpegNodataEnd: { const int32_t thread = static_cast(r.a[0]); if (!(r.a[2] & 1u)) l.gameHeap().release(r.a[1]); MpegState &s = state(l); if ((r.a[2] & 2u) && g.context()->r[2].uw[0] == 0) s.inputEnded = true; if (thread && s.waiting == thread) { s.waiting = 0; l.dispatcher()->kernel().wake(thread, 0, true, ee::kWaitMpeg); } break; } case kResumeMpegGetPicture: getPictureOn(l, g, r.a[0], r.a[1]); break; case kResumeMpegDeliver: deliver(l, g, r.a[0], r.a[1]); break; case kResumeMpegDemuxCallbackEnd: { // A stream callback's end (MpegOptions::sdkDemux): a packet taken goes to the decoder or the sound sink; a // sound packet refused (0) ends the demux call before it. The demuxing thread is woken either way. MpegState &s = state(l); releaseEntry(l, s, r.a[1]); // The video is the decoder's from the demux: the game's own copy (its IPU input, which nothing drains // without an IPU) refusing it does not stop the stream. if (g.context()->r[2].uw[0] != 0 || s.heldId == 0xE0) take(l, s, s.heldId, s.held.data(), s.held.size(), s.heldPts); else { s.pending.clear(); s.pendingAt = s.heldAt; s.consumed = s.heldAt; s.refused = true; } s.held.clear(); if (r.a[0]) // the thread waiting for it (with callbacksOnCaller none: the call is made again) l.dispatcher()->kernel().wake(static_cast(r.a[0]), 0, true, ee::kWaitMpeg); break; } case kResumeMpegDemuxNext: demuxOn(l, g, r.a[0]); break; } } void addMpeg(std::vector &out) { if (!haveVideoDecoder()) return; // sceIpuInit: the IPU's reset (IPU_CTRL's RST, then a wait on its busy bit). There is no IPU: what a game then // asks of it is answered where it asks (libmpeg's functions here; a port's own IPU use, Amplitude's menus). out.push_back({"sceIpuInit", kMpeg, [](Libraries &, Guest &g) { g.ret(0); }}); out.push_back({"sceMpegInit", kMpeg, init}); out.push_back({"sceMpegCreate", kMpeg, create}); out.push_back({"sceMpegDelete", kMpeg, destroy}); out.push_back({"sceMpegReset", kMpeg, reset}); out.push_back({"sceMpegAddCallback", kMpeg, addCallback}); out.push_back({"sceMpegAddStrCallback", kMpeg, addStrCallback}); out.push_back({"sceMpegDemuxPssRing", kMpeg, demux}); out.push_back({"sceMpegAddBs", kMpeg, addBs}); out.push_back({"sceMpegGetPicture", kMpeg, getPicture}); out.push_back({"sceMpegIsEnd", kMpeg, isEnd}); out.push_back({"videoCallback__FP7sceMpegP16sceMpegCbDataStrPv", kMpeg, videoCallback}); } }