Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_fmv/
player.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! A streaming STR player a game can call: [`play`] streams one movie from
3//! the disc at double speed, decodes it through the MDEC and shows it, with
4//! its interleaved XA audio going straight from the drive to the SPU.
5//!
6//! The pipeline is the `hello-fmv` console test's, without the test's
7//! sector stamps and overlay:
8//!
9//! 1. A polled pump drains every sector the drive has ready into a ring of
10//!    three frame slots. It runs between every unit of work, including
11//!    every wait and every two macroblocks of the bitstream decode.
12//! 2. [`crate::bitstream::decode_frame`] turns the next frame's bitstream into one
13//!    of two run-length buffers while the MDEC decodes the previous frame
14//!    from the other.
15//! 3. The whole decoded frame comes back over one DMA1 transfer into one of
16//!    two RAM frame buffers, so the MDEC's output never waits for the CPU to
17//!    start the next column. Its 16-pixel columns then go to a free display
18//!    buffer over DMA2 while the MDEC decodes the next frame into the other
19//!    RAM buffer.
20//! 4. The flip is queued to the VBlank handler. There are three display
21//!    buffers, so the MDEC can start the next frame while the last one
22//!    waits for its flip.
23//!
24//! Pacing follows the drive, not the VBlank: a frame is shown
25//! [`Config::latency_vblanks`] after its last sector arrived. The audio
26//! plays as its sectors arrive, so picture and sound keep a fixed offset
27//! for the whole movie whatever the display's refresh rate, and a 25 fps
28//! PAL movie plays at 25 fps on a 60 Hz display. A frame completed while an
29//! older one still waits for the decoder replaces it (counted in
30//! [`Outcome::skipped`]).
31//!
32//! Why whole frames: at 24 bits a 320x192 frame is 46,080 words and the
33//! console MDEC returns a word every 24 cycles, 1,106,000 cycles, which is
34//! nearly all of the 1,130,000 that two VBlanks give a 30 fps movie. Fetching a
35//! column at a time left the MDEC idle until the CPU noticed each column had
36//! arrived (about 7,500 cycles a column, 150,000 a frame), so the player fell
37//! behind and dropped a tenth of the frames. One transfer per frame leaves the
38//! MDEC no gap; the price is two RAM frame buffers (about 360 KB at 320x192 and
39//! 24 bits) instead of two column buffers.
40//!
41//! Memory comes from the caller ([`memory_words`] says how much), so a
42//! game lends a buffer that is idle while the movie plays, such as a level
43//! buffer at boot. The player takes over the CD drive, the MDEC, DMA
44//! channels 0 to 2, root counter 2, the display and the VRAM under
45//! [`Config::buffers`] while it runs. No frame of the caller's may be in
46//! flight on the GPU when it starts, and the SPU must already be
47//! initialised.
48
49use core::ptr::addr_of_mut;
50
51use psx_gpu::prim::FillRect;
52use psx_gpu::Gpu;
53use psx_hw::gpu::gp1;
54use psx_hw::mdec::{DECODE_15BPP, DECODE_24BPP};
55use psx_io::periph::{Cd, GpuDma, MdecDma};
56use psx_pack::cd::{SectorReader, SECTOR_WORDS};
57use psx_rt::{interrupts, Peripherals};
58use psx_spu::CdVolume;
59use psx_vram::VramRect;
60
61use crate::mdec::Mdec;
62use crate::stream::{Chunk, FrameAssembler, CHUNK_PAYLOAD_BYTES, MAX_CHUNKS};
63use crate::{bitstream, mdec};
64
65/// One movie on the disc, as the build measured it.
66#[derive(Copy, Clone, Debug)]
67pub struct Movie {
68    /// First sector of the file.
69    pub lba: u32,
70    /// Frames in the movie; the stream ends after the last.
71    pub frames: u32,
72    /// Picture width, a multiple of 16.
73    pub width: u16,
74    /// Picture height, a multiple of 16.
75    pub height: u16,
76    /// Most sectors any frame spans.
77    pub max_chunks: u16,
78    /// Most run-length words any frame decodes to
79    /// ([`crate::bitstream::decode_frame`]'s result).
80    pub rle_words: usize,
81    /// XA audio file and channel to play, or `None` for a silent movie.
82    pub xa: Option<(u8, u8)>,
83}
84
85/// Display buffers at (0, 0), (0, 256) and (512, 0): room for 320 pixels
86/// at 24 bits (480 halfwords) by up to 256 lines each.
87pub const DEFAULT_BUFFERS: [(u16, u16); 3] = [(0, 0), (0, 256), (512, 0)];
88
89/// Colour depth of the decoded picture.
90#[derive(Copy, Clone, Debug, PartialEq, Eq)]
91pub enum Depth {
92    /// 15-bit: the GPU can still draw over the movie (subtitles, a skip
93    /// prompt), at the price of 5-bit banding on smooth gradients.
94    Rgb15,
95    /// 24-bit, as most commercial players show their movies: no banding,
96    /// 1.5 times the MDEC output and VRAM upload, and the display runs in
97    /// 24-bit mode, where the GPU cannot draw. The player switches the
98    /// display mode for the movie and restores it on return.
99    Rgb24,
100}
101
102/// Where and how to show it.
103#[derive(Copy, Clone, Debug)]
104pub struct Config {
105    /// Output depth.
106    pub depth: Depth,
107    /// VRAM origins (halfword x, line y) of the three display buffers, each
108    /// `screen_width` pixels by `screen_height` lines; the movie is centred
109    /// in them over black. [`DEFAULT_BUFFERS`] suits a 320-wide display.
110    pub buffers: [(u16, u16); 3],
111    /// The display's size.
112    pub screen_width: u16,
113    /// Display height.
114    pub screen_height: u16,
115    /// VBlanks from a frame's last sector to its flip: the decoder's
116    /// headroom, and the fixed lag of the picture behind the sound.
117    pub latency_vblanks: u32,
118    /// End the stream if no sector arrives for this many VBlanks.
119    pub stall_vblanks: u32,
120}
121
122/// Why [`play`] returned.
123#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
124pub enum Stop {
125    /// The last frame was shown.
126    #[default]
127    End,
128    /// The caller's poll asked to stop.
129    Skipped,
130    /// No sector for [`Config::stall_vblanks`].
131    Stall,
132    /// The drive reported an error.
133    CdError,
134    /// The MDEC failed [`WEDGE_ERRORS`] frames in a row.
135    Wedged,
136    /// Setup failed (drive, MDEC or memory); nothing played.
137    Setup,
138}
139
140/// What happened, for logs and tests.
141#[derive(Copy, Clone, Debug, Default)]
142pub struct Outcome {
143    /// Why it ended.
144    pub stop: Stop,
145    /// Frames shown.
146    pub shown: u32,
147    /// Frames replaced before the decoder reached them.
148    pub skipped: u32,
149    /// Frames shown later than their due VBlank, and the worst lateness.
150    pub late: u32,
151    /// Most VBlanks any frame was shown after it was due.
152    pub worst_late_vblanks: u32,
153    /// Frames abandoned with sectors missing, and bitstream or MDEC
154    /// failures.
155    pub dropped: u32,
156    /// Frames the bitstream decoder or the MDEC failed.
157    pub decode_errors: u32,
158    /// Number of the last complete frame the stream delivered.
159    pub last_frame: u32,
160    /// VBlanks from the start of the stream to the return.
161    pub vblanks: u32,
162    /// CPU per decoded frame, in kilocycles: bitstream decode, MDEC and
163    /// upload, and waiting.
164    pub kcyc_vlc: u32,
165    /// MDEC and upload time not overlapped with the bitstream decode.
166    pub kcyc_mdec: u32,
167    /// Waiting for sectors or the flip.
168    pub kcyc_wait: u32,
169}
170
171/// Consecutive MDEC failures that end a movie as [`Stop::Wedged`].
172pub const WEDGE_ERRORS: u32 = 8;
173/// Frame slots: one filling, one ready, one being decoded.
174const SLOTS: usize = 3;
175/// Words of bitstream one sector carries.
176const CHUNK_WORDS: usize = CHUNK_PAYLOAD_BYTES / 4;
177/// Longest a frame may take from its decode command to its last column in
178/// VRAM before it counts as a decode error.
179const DECODE_TIMEOUT_VBLANKS: u32 = 30;
180/// Macroblocks between pumps inside the bitstream decode.
181const PUMP_MACROBLOCKS: u32 = 2;
182/// Double speed, XA-ADPCM to the SPU, file/channel filter.
183const MODE_XA: u8 = 0x80 | 0x40 | 0x08;
184/// Double speed, data only.
185const MODE_DATA: u8 = 0x80;
186/// Non-video sectors in a row that end the stream: past the file's end,
187/// when the last frame never completed.
188const FOREIGN_SECTORS: u32 = 32;
189/// GP1(08h), display mode, and its 24-bit colour bit.
190const GP1_DISPLAY_MODE: u32 = 0x0800_0000;
191const DISPLAY_24BIT: u32 = 1 << 4;
192
193/// The current GP1(08h) parameter, rebuilt from GPUSTAT bits 16..22.
194fn display_mode() -> u32 {
195    let stat = psx_io::gpu::status().bits();
196    ((stat >> 17) & 3)
197        | ((stat >> 19) & 1) << 2
198        | ((stat >> 20) & 1) << 3
199        | ((stat >> 21) & 1) << 4
200        | ((stat >> 22) & 1) << 5
201        | ((stat >> 16) & 1) << 6
202        | ((stat >> 14) & 1) << 7
203}
204
205/// Display buffers: one shown, one decoded and waiting for its flip, one
206/// the MDEC decodes into. With two, the MDEC would sit idle from a frame's
207/// end until that frame's flip, which a 24-bit movie cannot afford.
208const BUFFERS: usize = 3;
209
210fn slot_words(m: &Movie) -> usize {
211    m.max_chunks as usize * CHUNK_WORDS
212}
213
214/// Run-length buffer words: the measured maximum, rounded up to whole DMA
215/// blocks.
216fn rle_words(m: &Movie) -> usize {
217    m.rle_words.div_ceil(mdec::DMA_BLOCK_WORDS) * mdec::DMA_BLOCK_WORDS
218}
219
220/// VRAM halfwords one decoded pixel takes.
221fn halfwords_x2(depth: Depth) -> u16 {
222    match depth {
223        Depth::Rgb15 => 2,
224        Depth::Rgb24 => 3,
225    }
226}
227
228/// One column, 16 pixels wide: 16 * height pixels of 2 or 3 bytes.
229fn column_words(m: &Movie, depth: Depth) -> usize {
230    4 * halfwords_x2(depth) as usize * m.height as usize
231}
232
233/// One decoded frame: every column, in the order the MDEC returns them.
234fn frame_words(m: &Movie, depth: Depth) -> usize {
235    (m.width as usize / 16) * column_words(m, depth)
236}
237
238/// Words of memory [`play`] needs for `movie` at `depth`.
239pub fn memory_words(movie: &Movie, depth: Depth) -> usize {
240    SLOTS * slot_words(movie) + 2 * rle_words(movie) + 2 * frame_words(movie, depth)
241}
242
243/// Root counter 2 (system clock / 8) accounting of where the time goes.
244const PHASE_VLC: usize = 0;
245const PHASE_MDEC: usize = 1;
246const PHASE_WAIT: usize = 2;
247
248struct Clock {
249    phase: usize,
250    last: u16,
251    acc: [u32; 3],
252}
253
254impl Clock {
255    fn switch(&mut self, next: usize) {
256        let now = psx_io::timers::counter(psx_io::timers::Timer::Timer2);
257        self.acc[self.phase] += now.wrapping_sub(self.last) as u32;
258        self.last = now;
259        self.phase = next;
260    }
261}
262
263/// Raw views of the caller's memory. The pieces are disjoint; the player
264/// hands each to one user at a time (see `Stream` and `Player`).
265#[derive(Copy, Clone)]
266struct Buffers {
267    slots: *mut u32,
268    slot_words: usize,
269    rle: *mut u32,
270    rle_words: usize,
271    frames: *mut u32,
272    column_words: usize,
273    frame_words: usize,
274}
275
276impl Buffers {
277    fn slot(&self, i: usize) -> &'static mut [u8] {
278        // SAFETY: slot `i` lies inside the caller's buffer (memory_words),
279        // and the stream fills only the slot the decoder is not reading.
280        unsafe {
281            core::slice::from_raw_parts_mut(
282                self.slots.add(i * self.slot_words) as *mut u8,
283                self.slot_words * 4,
284            )
285        }
286    }
287    fn rle(&self, i: usize) -> &'static mut [u32] {
288        // SAFETY: as above; the bitstream decoder writes one buffer while
289        // DMA0 reads the other.
290        unsafe { core::slice::from_raw_parts_mut(self.rle.add(i * self.rle_words), self.rle_words) }
291    }
292    fn rle16(&self, i: usize) -> &'static mut [u16] {
293        let words = self.rle(i);
294        // SAFETY: the same buffer as halfwords.
295        unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr() as *mut u16, words.len() * 2) }
296    }
297    fn frame(&self, i: usize) -> *mut u32 {
298        // SAFETY: frame buffer `i` lies inside the caller's buffer.
299        unsafe { self.frames.add(i * self.frame_words) }
300    }
301    fn column(&self, frame: usize, c: u16) -> *mut u32 {
302        // SAFETY: column `c` of frame buffer `frame` lies inside it.
303        unsafe { self.frame(frame).add(c as usize * self.column_words) }
304    }
305}
306
307static mut READER: Option<SectorReader> = None;
308static mut MDEC: Option<Mdec> = None;
309static mut SECTOR: [u32; SECTOR_WORDS] = [0; SECTOR_WORDS];
310
311/// Own the drive and the MDEC from here on, replacing any earlier owner.
312fn install_devices(cd: Cd, mdec: MdecDma) {
313    // SAFETY: single-threaded; nothing holds a reference from before.
314    unsafe {
315        *addr_of_mut!(READER) = Some(SectorReader::with_cd(cd));
316        *addr_of_mut!(MDEC) = Some(Mdec::new(mdec));
317    }
318}
319
320fn reader() -> &'static mut SectorReader {
321    // SAFETY: single-threaded; only the player uses its reader, and no
322    // caller keeps the reference across a call that takes another.
323    unsafe { (*addr_of_mut!(READER)).as_mut().expect("reader installed") }
324}
325
326fn mdec() -> &'static mut Mdec {
327    // SAFETY: as `reader`.
328    unsafe { (*addr_of_mut!(MDEC)).as_mut().expect("mdec installed") }
329}
330
331/// Read one sector synchronously into the player's sector buffer.
332fn read_one(lba: u32) -> Option<&'static [u8]> {
333    let r = reader();
334    // SAFETY: single-threaded use of the reader and its sector buffer.
335    unsafe {
336        if !r.start_read(lba) {
337            return None;
338        }
339        let ok = r.read_sector(&mut *addr_of_mut!(SECTOR));
340        r.stop();
341        if !ok {
342            return None;
343        }
344        Some(core::slice::from_raw_parts(
345            addr_of_mut!(SECTOR) as *const u8,
346            SECTOR_WORDS * 4,
347        ))
348    }
349}
350
351/// Find a file in the disc's root directory by name: `(lba, bytes)`.
352/// Takes the drive over (data mode, double speed) and leaves it stopped.
353pub fn find_root_file(name: &str) -> Option<(u32, u32)> {
354    // SAFETY: the caller is not using the drive or the MDEC, as the module
355    // docs say; the player takes them over for as long as it runs.
356    let devices = unsafe { Peripherals::steal() };
357    install_devices(devices.cd, devices.mdec_dma);
358    if !reader().prepare() {
359        return None;
360    }
361    let (root, _) = crate::iso::root_directory(read_one(crate::iso::PVD_LBA)?)?;
362    crate::iso::find_in_directory(read_one(root)?, name)
363}
364
365/// The drive side: sectors into frame slots.
366struct Stream {
367    buf: Buffers,
368    last_frame: u32,
369    frames: u32,
370    done: bool,
371    cd_error: bool,
372    started: bool,
373    /// Sectors in a row that were not video.
374    foreign: u32,
375    filling: usize,
376    /// A complete frame waiting for the decoder: (slot, bytes, VBlank its
377    /// last sector arrived).
378    ready: Option<(usize, u32, u32)>,
379    decoding: Option<usize>,
380    asm: FrameAssembler,
381    skipped: u32,
382    last_sector_vblank: u32,
383}
384
385impl Stream {
386    fn pump(&mut self) {
387        while !self.done {
388            // SAFETY: single-threaded use of the player's reader and sector.
389            let got = unsafe { reader().try_read_sector(&mut *addr_of_mut!(SECTOR)) };
390            match got {
391                Ok(true) => {}
392                Ok(false) => return,
393                Err(()) => {
394                    self.cd_error = true;
395                    self.done = true;
396                    return;
397                }
398            }
399            let now = interrupts::vblank_count();
400            self.last_sector_vblank = now;
401            // SAFETY: SECTOR as bytes.
402            let sector = unsafe {
403                core::slice::from_raw_parts(addr_of_mut!(SECTOR) as *const u8, SECTOR_WORDS * 4)
404            };
405            if Chunk::parse(sector).is_none() {
406                // A movie may carry empty data sectors in its audio slots
407                // (WipEout's last seconds are silent), but a long run of
408                // them means the drive has read past the file's end.
409                self.foreign += 1;
410                if self.started && self.foreign > FOREIGN_SECTORS {
411                    self.done = true;
412                }
413                continue;
414            }
415            self.foreign = 0;
416            self.started = true;
417            if let Some(frame) = self.asm.add(sector, self.buf.slot(self.filling)) {
418                self.last_frame = frame.number;
419                if frame.number >= self.frames {
420                    self.done = true;
421                }
422                let done = self.filling;
423                let next = match self.ready.replace((done, frame.size, now)) {
424                    Some((stale, _, _)) => {
425                        self.skipped += 1;
426                        stale
427                    }
428                    None => (0..SLOTS)
429                        .find(|&s| s != done && Some(s) != self.decoding)
430                        .unwrap_or(done),
431                };
432                self.filling = next;
433            }
434        }
435    }
436}
437
438/// A decoded frame's trip from its RAM buffer to a display buffer, one
439/// column at a time over DMA2.
440struct Columns {
441    /// Left edge and column width, in VRAM halfwords.
442    x: u16,
443    step: u16,
444    y: u16,
445    count: u16,
446    next: u16,
447    /// The RAM frame buffer the columns come from.
448    frame: usize,
449    /// A column copy is in flight on channel 2.
450    uploading: bool,
451    started: u32,
452}
453
454impl Columns {
455    fn start(x: u16, step: u16, y: u16, count: u16, frame: usize) -> Self {
456        Columns {
457            x,
458            step,
459            y,
460            count,
461            next: 0,
462            frame,
463            uploading: false,
464            started: interrupts::vblank_count(),
465        }
466    }
467
468    /// Move the copies along; `true` once every column is in VRAM.
469    fn service(&mut self, dma: &mut GpuDma, buf: &Buffers, height: u16) -> bool {
470        if self.uploading && psx_vram::dma_copy_to_vram_done() {
471            self.uploading = false;
472        }
473        if !self.uploading && self.next < self.count {
474            let c = self.next;
475            let rect = VramRect::new(self.x + c * self.step, self.y, self.step, height);
476            let src = buf.column(self.frame, c);
477            // SAFETY: the column's words lie in RAM frame buffer `frame`,
478            // which the MDEC does not write while this frame uploads. Nothing
479            // else uses GP0 or channel 2 while a frame uploads: the player
480            // only draws between frames, after `uploading` is clear.
481            if unsafe { psx_vram::dma_copy_to_vram_start(dma, rect, src) } {
482                self.uploading = true;
483            } else {
484                // SAFETY: the column holds `column_words` words.
485                let words = unsafe { core::slice::from_raw_parts(src, buf.column_words) };
486                psx_vram::upload_words(rect, words);
487            }
488            self.next += 1;
489        }
490        self.next == self.count && !self.uploading
491    }
492}
493
494struct Player {
495    /// The GPU's channel 2: the column uploads and the flip's GP0(1Fh) go
496    /// through it.
497    dma: GpuDma,
498    st: Stream,
499    buf: Buffers,
500    movie: Movie,
501    /// Movie's left edge and column width in VRAM halfwords.
502    x: u16,
503    step: u16,
504    y_offset: u16,
505    latency: u32,
506    /// The three display buffers' VRAM origins.
507    origins: [(u16, u16); BUFFERS],
508    /// The buffer on screen.
509    front: usize,
510    /// The MDEC's frame: (RLE buffer, display buffer, due VBlank).
511    decoding: Option<(usize, usize, u32)>,
512    /// The RAM frame buffer the MDEC is writing, and the VBlank it began.
513    mdec_frame: usize,
514    mdec_started: u32,
515    /// A decoded frame in RAM waiting for the copy to VRAM:
516    /// (RAM frame buffer, display buffer, due VBlank).
517    to_upload: Option<(usize, usize, u32)>,
518    /// The frame being copied to its display buffer, and its copy.
519    upload: Option<(usize, usize, u32)>,
520    cols: Columns,
521    /// Decoded frames waiting for their flip, oldest first: (display
522    /// buffer, due VBlank).
523    waiting: [Option<(usize, u32)>; 2],
524    /// The buffer whose flip is queued, until the VBlank handler applies it.
525    queued: Option<usize>,
526    /// A bitstream-decoded frame waiting for the MDEC: (RLE buffer, words,
527    /// due VBlank).
528    pending: Option<(usize, usize, u32)>,
529    shown: u32,
530    late: u32,
531    worst_late: u32,
532    errors: u32,
533    in_a_row: u32,
534    wedged: bool,
535    clock: Clock,
536}
537
538impl Player {
539    fn idle_phase(&self) -> usize {
540        if self.decoding.is_some() {
541            PHASE_MDEC
542        } else {
543            PHASE_WAIT
544        }
545    }
546
547    /// A display buffer that is neither shown, nor waiting for or queued to
548    /// its flip, nor being decoded or copied into.
549    fn free_buffer(&self) -> Option<usize> {
550        (0..BUFFERS).find(|&b| {
551            b != self.front
552                && self.queued != Some(b)
553                && self.decoding.map(|d| d.1) != Some(b)
554                && self.to_upload.map(|d| d.1) != Some(b)
555                && self.upload.map(|d| d.1) != Some(b)
556                && self.waiting.iter().all(|w| w.map(|w| w.0) != Some(b))
557        })
558    }
559
560    /// A RAM frame buffer the MDEC may write: not the one it is writing, and
561    /// not one still waiting for or in the middle of its copy.
562    fn free_frame(&self) -> Option<usize> {
563        (0..2).find(|&f| {
564            (self.decoding.is_none() || self.mdec_frame != f)
565                && self.to_upload.map(|u| u.0) != Some(f)
566                && self.upload.map(|u| u.0) != Some(f)
567        })
568    }
569
570    /// Nothing decoded, decoding or waiting to be shown.
571    fn drained(&self) -> bool {
572        self.decoding.is_none()
573            && self.to_upload.is_none()
574            && self.upload.is_none()
575            && self.pending.is_none()
576            && self.waiting[0].is_none()
577            && self.queued.is_none()
578    }
579
580    /// Drain the drive, move the MDEC's transfers along, and queue or
581    /// retire flips.
582    fn tick(&mut self) {
583        // Sample the clock at least once per pump: root counter 2 wraps
584        // after 65,536 * 8 cycles, less than one bitstream decode.
585        self.clock.switch(self.clock.phase);
586        self.st.pump();
587        if let Some(b) = self.queued {
588            if !interrupts::is_display_control_queued() {
589                self.front = b;
590                self.queued = None;
591                self.shown += 1;
592            }
593        }
594        if let Some((_, b, due)) = self.decoding {
595            // The whole frame is in RAM once DMA1 has drained the MDEC.
596            if mdec().column_done() {
597                self.decoding = None;
598                if mdec().decode_finish() {
599                    self.in_a_row = 0;
600                    self.to_upload = Some((self.mdec_frame, b, due));
601                } else {
602                    self.decode_failed();
603                }
604            } else if interrupts::vblank_count().wrapping_sub(self.mdec_started)
605                > DECODE_TIMEOUT_VBLANKS
606            {
607                mdec().abort_decode();
608                self.decoding = None;
609                self.decode_failed();
610            }
611        }
612        if self.upload.is_none() {
613            if let Some((f, b, due)) = self.to_upload.take() {
614                let (x, y) = self.origins[b];
615                self.cols = Columns::start(
616                    x + self.x,
617                    self.step,
618                    y + self.y_offset,
619                    self.movie.width / 16,
620                    f,
621                );
622                self.upload = Some((f, b, due));
623            }
624        }
625        if let Some((_, b, due)) = self.upload {
626            if self
627                .cols
628                .service(&mut self.dma, &self.buf, self.movie.height)
629            {
630                self.upload = None;
631                let slot = if self.waiting[0].is_none() { 0 } else { 1 };
632                self.waiting[slot] = Some((b, due));
633            } else if interrupts::vblank_count().wrapping_sub(self.cols.started)
634                > DECODE_TIMEOUT_VBLANKS
635            {
636                psx_io::dma::abort(psx_io::dma::Channel::Gpu);
637                // GP1(01h): drop a VRAM copy the abort left waiting for
638                // pixels.
639                psx_io::gpu::write_display_control(gp1::RESET_CMD_BUFFER);
640                self.cols.uploading = false;
641                self.upload = None;
642                self.decode_failed();
643            }
644        }
645        if self.queued.is_none() {
646            if let Some((b, due)) = self.waiting[0] {
647                let now = interrupts::vblank_count();
648                let edge = now.wrapping_add(1);
649                // Due at the next edge, or behind: more decoded frames
650                // already wait, so show this one now rather than skip one
651                // later.
652                let behind = self.waiting[1].is_some()
653                    || (self.pending.is_some() && self.st.ready.is_some());
654                // GP0 is free only between column copies.
655                let gp0_free = !self.cols.uploading && psx_vram::dma_copy_to_vram_done();
656                if gp0_free && (behind || edge.wrapping_sub(due) as i32 >= 0) {
657                    // The VBlank handler flips only once GPUSTAT bit 24 says
658                    // the GPU got past this frame's uploads: GP0(1Fh) after
659                    // them, acknowledged afresh now that no flip is queued.
660                    let gpu = Gpu::from_dma_mut(&mut self.dma);
661                    gpu.arm_draw_done();
662                    gpu.signal_draw_done();
663                    let (x, y) = self.origins[b];
664                    interrupts::queue_display_control_at_vblank(gp1::display_start(
665                        x as u32, y as u32,
666                    ));
667                    let late = edge.wrapping_sub(due) as i32;
668                    if late > 0 {
669                        self.late += 1;
670                        self.worst_late = self.worst_late.max(late as u32);
671                    }
672                    self.queued = Some(b);
673                    self.waiting = [self.waiting[1], None];
674                }
675            }
676        }
677    }
678
679    fn decode_failed(&mut self) {
680        self.errors += 1;
681        self.in_a_row += 1;
682        if self.in_a_row >= WEDGE_ERRORS {
683            self.wedged = true;
684        }
685        let _ = setup_mdec();
686    }
687}
688
689fn setup_mdec() -> bool {
690    mdec().reset() && mdec().load_tables().is_some_and(|t| t.enable_writes != 0)
691}
692
693/// Every display buffer black. A 24-bit line is 1.5 times as wide in VRAM
694/// halfwords.
695fn clear_buffers(dma: &mut GpuDma, config: &Config) {
696    let gpu = Gpu::from_dma_mut(dma);
697    // A frame the caller kicked before the movie may still be walking.
698    gpu.wait_idle();
699    let line = config.screen_width * halfwords_x2(config.depth) / 2;
700    for &(x, y) in &config.buffers {
701        gpu.draw(&FillRect::new(
702            (x, y),
703            (line, config.screen_height),
704            (0, 0, 0),
705        ));
706    }
707    gpu.wait_idle();
708}
709
710/// Hand the display back in the caller's `mode`, over black when the movie
711/// ran at 24 bits: that picture read as 15-bit pixels would be noise.
712fn leave_display(dma: &mut GpuDma, config: &Config, mode: u32) {
713    if config.depth == Depth::Rgb24 {
714        clear_buffers(dma, config);
715        psx_io::gpu::write_display_control(GP1_DISPLAY_MODE | mode);
716    }
717}
718
719fn setup_failed() -> Outcome {
720    Outcome {
721        stop: Stop::Setup,
722        ..Outcome::default()
723    }
724}
725
726/// Play `movie` until it ends or `poll` returns `true` (checked once per
727/// VBlank, e.g. for a skip button). `memory` must hold at least
728/// [`memory_words`] words and is free again on return. At 15 bits the last
729/// frame stays on screen (the display start may be any of the three
730/// buffers); at 24 bits every buffer is cleared to black and the caller's
731/// display mode is restored. The drive is stopped
732/// and the CD audio volume left at 0.
733pub fn play(
734    movie: &Movie,
735    config: &Config,
736    memory: &mut [u32],
737    poll: &mut dyn FnMut() -> bool,
738) -> Outcome {
739    if memory.len() < memory_words(movie, config.depth)
740        || movie.width == 0
741        || movie.height == 0
742        || !movie.width.is_multiple_of(16)
743        || !movie.height.is_multiple_of(16)
744        || movie.width > config.screen_width
745        || movie.height > config.screen_height
746        || movie.max_chunks == 0
747        || movie.max_chunks > MAX_CHUNKS
748    {
749        return setup_failed();
750    }
751    let base = memory.as_mut_ptr();
752    let sw = slot_words(movie);
753    let rw = rle_words(movie);
754    let buf = Buffers {
755        slots: base,
756        slot_words: sw,
757        // SAFETY: offsets inside `memory` (checked against memory_words).
758        rle: unsafe { base.add(SLOTS * sw) },
759        rle_words: rw,
760        // SAFETY: as above.
761        frames: unsafe { base.add(SLOTS * sw + 2 * rw) },
762        column_words: column_words(movie, config.depth),
763        frame_words: frame_words(movie, config.depth),
764    };
765
766    // SAFETY: the player takes over the drive, the MDEC and the GPU's DMA
767    // channel, as its doc says; nothing else drives them until it returns.
768    let devices = unsafe { Peripherals::steal() };
769    install_devices(devices.cd, devices.mdec_dma);
770    let mut dma = devices.gpu_dma;
771
772    let r = reader();
773    // The player owns the drive until it returns; prepare takes it over from
774    // whatever used it before. Unmute: a muted drive plays no XA.
775    let ready = {
776        match movie.xa {
777            Some((file, channel)) => {
778                r.prepare_mode(MODE_XA) && r.unmute() && r.set_filter(file, channel)
779            }
780            None => r.prepare_mode(MODE_DATA),
781        }
782    };
783    if !ready || !setup_mdec() {
784        return setup_failed();
785    }
786    if movie.xa.is_some() {
787        reader().cd_mut().set_audio_mixer(0x80, 0, 0x80, 0);
788        psx_spu::set_cd_volume(CdVolume::MAX, CdVolume::MAX);
789        psx_spu::enable_cd_audio(true);
790    }
791
792    // Every display buffer black, the first one shown, in 24-bit mode if the
793    // movie is.
794    let x2 = halfwords_x2(config.depth);
795    let _ = interrupts::take_queued_display_control();
796    clear_buffers(&mut dma, config);
797    let (x0, y0) = config.buffers[0];
798    psx_io::gpu::write_display_control(gp1::display_start(x0 as u32, y0 as u32));
799    let mode = display_mode();
800    if config.depth == Depth::Rgb24 {
801        psx_io::gpu::write_display_control(GP1_DISPLAY_MODE | mode | DISPLAY_24BIT);
802    }
803
804    // The reader was prepared above.
805    if !r.start_read(movie.lba) {
806        leave_display(&mut dma, config, mode);
807        return setup_failed();
808    }
809
810    psx_io::timers::set_mode(psx_io::timers::Timer::Timer2, 0x0200);
811    let start = interrupts::vblank_count();
812    let mut p = Player {
813        dma,
814        st: Stream {
815            buf,
816            last_frame: 0,
817            frames: movie.frames,
818            done: false,
819            cd_error: false,
820            started: false,
821            foreign: 0,
822            filling: 0,
823            ready: None,
824            decoding: None,
825            asm: FrameAssembler::new(),
826            skipped: 0,
827            last_sector_vblank: start,
828        },
829        buf,
830        movie: *movie,
831        x: (config.screen_width - movie.width) / 2 * x2 / 2,
832        step: 8 * x2,
833        y_offset: (config.screen_height - movie.height) / 2,
834        latency: config.latency_vblanks,
835        origins: config.buffers,
836        front: 0,
837        decoding: None,
838        mdec_frame: 0,
839        mdec_started: 0,
840        to_upload: None,
841        upload: None,
842        cols: Columns::start(0, 0, 0, 0, 0),
843        waiting: [None, None],
844        queued: None,
845        pending: None,
846        shown: 0,
847        late: 0,
848        worst_late: 0,
849        errors: 0,
850        in_a_row: 0,
851        wedged: false,
852        clock: Clock {
853            phase: PHASE_WAIT,
854            last: psx_io::timers::counter(psx_io::timers::Timer::Timer2),
855            acc: [0; 3],
856        },
857    };
858    let mut polled = start;
859    let mut skipped = false;
860    let rows = movie.height as u32 / 16;
861    let macroblocks = movie.width as u32 / 16 * rows;
862    loop {
863        p.tick();
864        if p.wedged {
865            break;
866        }
867        let now = interrupts::vblank_count();
868        if now != polled {
869            polled = now;
870            if poll() {
871                skipped = true;
872                break;
873            }
874        }
875        // Decode the next frame's bitstream while the MDEC works on this one.
876        if p.pending.is_none() {
877            if let Some((slot, bytes, arrived)) = p.st.ready.take() {
878                p.clock.switch(PHASE_VLC);
879                p.st.decoding = Some(slot);
880                let rle = match p.decoding {
881                    Some((r, _, _)) => 1 - r,
882                    None => 0,
883                };
884                let frame_bytes = &p.buf.slot(slot)[..(bytes as usize).min(p.buf.slot_words * 4)];
885                let out = p.buf.rle16(rle);
886                let decoded = bitstream::decode_frame(
887                    frame_bytes,
888                    out,
889                    macroblocks,
890                    PUMP_MACROBLOCKS,
891                    &mut || p.tick(),
892                );
893                p.st.decoding = None;
894                match decoded {
895                    Ok(words) => p.pending = Some((rle, words, arrived.wrapping_add(p.latency))),
896                    Err(_) => p.errors += 1,
897                }
898                let phase = p.idle_phase();
899                p.clock.switch(phase);
900                continue;
901            }
902        }
903        if p.decoding.is_none() && p.pending.is_some() {
904            if let (Some(b), Some(f)) = (p.free_buffer(), p.free_frame()) {
905                let Some((rle, words, due)) = p.pending.take() else {
906                    continue;
907                };
908                p.clock.switch(PHASE_MDEC);
909                let depth = match config.depth {
910                    Depth::Rgb15 => DECODE_15BPP,
911                    Depth::Rgb24 => DECODE_24BPP,
912                };
913                // SAFETY: the bitstream decoder writes only the other buffer
914                // until this decode is finished or given up.
915                if unsafe { mdec().decode_start(p.buf.rle(rle), words, depth) }.is_err() {
916                    // Nothing the decoder wrote can be sent (no whole block):
917                    // nothing started, the frame is lost.
918                    p.errors += 1;
919                    continue;
920                }
921                // SAFETY: frame buffer `f` is free (see `free_frame`) and holds
922                // `frame_words` words; it stays untouched until DMA1 finishes
923                // or is aborted.
924                if unsafe { mdec().read_column_start(p.buf.frame(f), p.buf.frame_words) } {
925                    p.mdec_frame = f;
926                    p.mdec_started = interrupts::vblank_count();
927                    p.decoding = Some((rle, b, due));
928                } else {
929                    // A frame the MDEC channel cannot express: abandon it as
930                    // a decode error rather than spin on it.
931                    mdec().abort_decode();
932                    p.decode_failed();
933                }
934                continue;
935            }
936        }
937        let idle = now.wrapping_sub(p.st.last_sector_vblank);
938        if p.drained() && p.st.ready.is_none() && (p.st.done || idle > config.stall_vblanks) {
939            break;
940        }
941        let phase = p.idle_phase();
942        p.clock.switch(phase);
943    }
944    // A flip still queued would land after we hand the display back.
945    let _ = interrupts::take_queued_display_control();
946    mdec().abort_decode();
947    psx_io::dma::abort(psx_io::dma::Channel::Gpu);
948    if p.cols.uploading {
949        // The abort cut a VRAM copy short: drop the transfer the GPU still
950        // waits to receive.
951        psx_io::gpu::write_display_control(gp1::RESET_CMD_BUFFER);
952    }
953    // Stop the stream we started (also ends the XA audio).
954    reader().stop();
955    if movie.xa.is_some() {
956        psx_spu::set_cd_volume(CdVolume(0), CdVolume(0));
957    }
958    if config.depth == Depth::Rgb24 {
959        leave_display(&mut p.dma, config, mode);
960    }
961    let stop = if skipped {
962        Stop::Skipped
963    } else if p.wedged {
964        Stop::Wedged
965    } else if p.st.cd_error {
966        Stop::CdError
967    } else if p.st.done {
968        Stop::End
969    } else {
970        Stop::Stall
971    };
972    let per = (p.shown + p.st.skipped).max(1);
973    let kcyc = |phase: usize| p.clock.acc[phase] / per * 8 / 1000;
974    Outcome {
975        stop,
976        shown: p.shown,
977        skipped: p.st.skipped,
978        late: p.late,
979        worst_late_vblanks: p.worst_late,
980        dropped: p.st.asm.dropped,
981        decode_errors: p.errors,
982        last_frame: p.st.last_frame,
983        vblanks: interrupts::vblank_count().wrapping_sub(start),
984        kcyc_vlc: kcyc(PHASE_VLC),
985        kcyc_mdec: kcyc(PHASE_MDEC),
986        kcyc_wait: kcyc(PHASE_WAIT),
987    }
988}