1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use std::io::Read;

use log::debug;

use arrow2::{
	array::StructArray,
	io::ipc::read::{read_stream_metadata, StreamReader, StreamState},
};

use crate::{
	frame::{immutable::Frame, mutable::Frame as MutableFrame},
	game::{self, immutable::Game, port_occupancy},
	io::{expect_bytes, peppi, slippi, Result},
};

type JsMap = serde_json::Map<String, serde_json::Value>;

/// Options for parsing Peppi games.
#[derive(Clone, Debug, Default)]
pub struct Opts {
	/// Skip all frame data when parsing a replay for speed
	/// (when you only need start/end/metadata).
	pub skip_frames: bool,
}

fn read_arrow_frames<R: Read>(mut r: R, version: slippi::Version) -> Result<Frame> {
	// magic number `ARROW1\0\0`
	expect_bytes(&mut r, &[65, 82, 82, 79, 87, 49, 0, 0])?;
	let metadata = read_stream_metadata(&mut r)?;
	let reader = StreamReader::new(r, metadata, None);
	let mut frame: Option<Frame> = None;
	for result in reader {
		match result? {
			StreamState::Some(chunk) => match frame {
				None => {
					let f = chunk.arrays()[0]
						.as_any()
						.downcast_ref::<StructArray>()
						.expect("expected a `StructArray`");
					frame = Some(Frame::from_struct_array(f.clone(), version))
				}
				Some(_) => return Err(err!("multiple batches")),
			},
			StreamState::Waiting => std::thread::sleep(std::time::Duration::from_millis(1000)),
		}
	}
	match frame {
		Some(f) => Ok(f),
		_ => Err(err!("no batches")),
	}
}

fn read_peppi_start<R: Read>(mut r: R) -> Result<game::Start> {
	let mut buf = Vec::new();
	r.read_to_end(&mut buf)?;
	slippi::de::game_start(&mut &buf[..])
}

fn read_peppi_end<R: Read>(mut r: R) -> Result<game::End> {
	let mut buf = Vec::new();
	r.read_to_end(&mut buf)?;
	slippi::de::game_end(&mut &buf[..])
}

fn read_peppi_metadata<R: Read>(r: R) -> Result<JsMap> {
	let json_object: serde_json::Value = serde_json::from_reader(r)?;
	match json_object {
		serde_json::Value::Object(map) => Ok(map),
		obj => Err(err!("expected map, got: {:?}", obj)),
	}
}

fn read_peppi_gecko_codes<R: Read>(mut r: R) -> Result<game::GeckoCodes> {
	let mut actual_size = [0; 4];
	r.read_exact(&mut actual_size)?;
	let mut bytes = Vec::new();
	r.read_to_end(&mut bytes)?;
	Ok(game::GeckoCodes {
		actual_size: u32::from_le_bytes(actual_size),
		bytes: bytes,
	})
}

/// Reads a Peppi (`.slpp`) replay from `r`.
pub fn read<R: Read>(r: R, opts: Option<&Opts>) -> Result<Game> {
	let mut start: Option<game::Start> = None;
	let mut end: Option<game::End> = None;
	let mut metadata: Option<JsMap> = None;
	let mut gecko_codes: Option<game::GeckoCodes> = None;
	let mut frames: Option<Frame> = None;
	let mut peppi: Option<peppi::Peppi> = None;
	for entry in tar::Archive::new(r).entries()? {
		let file = entry?;
		let path = file.path()?;
		debug!("processing file: {}", path.display());
		match path.file_name().and_then(|n| n.to_str()) {
			Some("peppi.json") => {
				let p: peppi::Peppi = serde_json::from_reader::<_, peppi::Peppi>(file)?;
				// TODO: support reading v1
				super::assert_current_version(p.version)?;
				peppi = Some(p);
			}
			Some("start.raw") => start = Some(read_peppi_start(file)?),
			Some("end.raw") => end = Some(read_peppi_end(file)?),
			Some("metadata.json") => metadata = Some(read_peppi_metadata(file)?),
			Some("gecko_codes.raw") => gecko_codes = Some(read_peppi_gecko_codes(file)?),
			Some("frames.arrow") => {
				let version = start
					.as_ref()
					.map(|s| s.slippi.version)
					.ok_or(err!("no start"))?;
				frames = Some(match opts.map_or(false, |o| o.skip_frames) {
					true => {
						let start = start.as_ref().ok_or(err!("missing start"))?;
						MutableFrame::with_capacity(0, start.slippi.version, &port_occupancy(start))
							.into()
					}
					_ => read_arrow_frames(file, version)?,
				});
				break;
			}
			_ => debug!("=> skipping"),
		};
	}

	let peppi = peppi.ok_or(err!("missing peppi"))?;
	Ok(Game {
		metadata: metadata,
		start: start.ok_or(err!("missing start"))?,
		end: end,
		gecko_codes: gecko_codes,
		frames: frames.ok_or(err!("missing frames"))?,
		hash: peppi.slp_hash,
		quirks: peppi.quirks,
	})
}