Spaces:
Sleeping
Sleeping
File size: 16,465 Bytes
f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 67e71f2 f20b6e7 | 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | """
Optional size reduction for an RPG Maker MV/MZ www/ folder, run by
build_pipeline right after the game is copied in.
Images: every picture under www/img/ is re-encoded as WebP under the SAME
name and at the SAME pixel size. Chromium (Android WebView) decodes images
by content, not by name or Content-Type, for both plain files and the
untyped Blobs RPG Maker builds from decrypted ones
(tools/webp_chromium_check.py proves both). RPG Maker's own encrypted
images (.rpgmvp on MV, .png_ on MZ) are decrypted with the game's key,
converted and encrypted again, using the same scheme as EncryptedAssets.kt.
Whatever cannot be handled with certainty (no key, unknown header, broken
image, too little gain) is left exactly as it was.
"""
from __future__ import annotations
import io
import json
import os
import re
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Literal, Optional
# The fixed 16-byte header RPG Maker MV/MZ puts before encrypted files
# (EncryptedAssets.kt RPG_HEADER). Only the "RPGMV" signature is checked
# when reading, the original header is written back unchanged.
RPG_HEADER = bytes.fromhex("5250474d560000000003010000000000")
RPG_SIGNATURE = b"RPGMV"
RPG_KEY_SIZE = 16
PLAIN_IMAGE_EXT = (".png", ".jpg", ".jpeg")
ENCRYPTED_IMAGE_EXT = (".rpgmvp", ".png_")
# Folders whose pictures are big, painted artwork: the only place lossy WebP
# is used. Everything else (system/ text colours are read from Window.png
# pixels, sprite sheets, tilesets, plugin folders) is always lossless.
LOSSY_DIRS = frozenset({
"pictures", "parallaxes", "titles1", "titles2", "battlebacks1", "battlebacks2", "enemies",
})
KEEP_RATIO = 0.85 # the new file must be at most 85 % of the old one
MIN_BYTES = 12 * 1024 # smaller files are not worth the work
WEBP_MAX_SIDE = 16383 # WebP's own limit
LOSSY_QUALITY = 88 # same as the Ren'Py packer (aerokey/optimize.py)
Mode = Literal["lossless", "lossy"]
@dataclass
class StepResult:
processed: int = 0
changed: int = 0
skipped: int = 0
before: int = 0 # bytes of the changed files, before
after: int = 0 # ... and after
errors: list = field(default_factory=list)
@property
def saved(self) -> int:
return max(0, self.before - self.after)
def human(n: float) -> str:
for unit in ("B", "KB", "MB", "GB"):
if abs(n) < 1024 or unit == "GB":
return ("{:.0f} {}" if unit == "B" else "{:.1f} {}").format(n, unit)
n /= 1024.0
return str(n)
# ----------------------------------------------------------------------
# RPG Maker encryption
# ----------------------------------------------------------------------
def rpg_key(www_dir: Path) -> Optional[bytes]:
"""The game's 16-byte key from data/System.json, or None."""
try:
text = (www_dir / "data" / "System.json").read_bytes().decode("utf-8-sig")
key = str(json.loads(text).get("encryptionKey", ""))
if len(key) != RPG_KEY_SIZE * 2:
return None
return bytes.fromhex(key)
except (OSError, ValueError, AttributeError):
return None
def _xor_head(body: bytes, key: bytes) -> bytes:
head = bytes(b ^ k for b, k in zip(body[:RPG_KEY_SIZE], key))
return head + body[RPG_KEY_SIZE:]
def decrypt_rpg(data: bytes, key: bytes) -> Optional[bytes]:
"""Plain bytes of an RPG Maker encrypted file; None if it has no RPGMV header."""
if len(data) < len(RPG_HEADER) or not data.startswith(RPG_SIGNATURE):
return None
return _xor_head(data[len(RPG_HEADER):], key)
def encrypt_rpg(plain: bytes, key: bytes, header: bytes = RPG_HEADER) -> bytes:
return header + _xor_head(plain, key)
# ----------------------------------------------------------------------
# Images
# ----------------------------------------------------------------------
def is_lossy_candidate(rel_posix: str) -> bool:
parts = rel_posix.lower().split("/")
return len(parts) >= 3 and parts[0] == "img" and parts[1] in LOSSY_DIRS
def _few_colours(img) -> bool:
try:
return img.getcolors(256) is not None
except Exception: # noqa: BLE001
return False
# Pillow converts these faithfully; anything else (16-bit, CMYK, float...)
# is left exactly as it is rather than risk a wrong-looking picture.
_SAFE_MODES = ("RGB", "RGBA", "L", "LA", "P", "PA", "1")
def _safe_to_convert(img) -> bool:
if img.mode not in _SAFE_MODES:
return False
try:
# Chromium applies the EXIF orientation; WebP output would drop it.
if img.getexif().get(0x0112, 1) != 1:
return False
except Exception: # noqa: BLE001
return False
return True
def _encode_webp(img, lossless: bool) -> bytes:
# Same encoder settings as the Ren'Py packer's webp_kodla().
# "transparency" also covers colour-key (tRNS) RGB/L PNGs, not only P.
alpha = img.mode in ("RGBA", "LA", "PA") or "transparency" in img.info
icc = img.info.get("icc_profile")
img = img.convert("RGBA" if alpha else "RGB")
extra = {"icc_profile": icc} if icc else {}
buf = io.BytesIO()
if lossless:
img.save(buf, format="WEBP", lossless=True, quality=100, method=5, **extra)
else:
img.save(buf, format="WEBP", quality=LOSSY_QUALITY, alpha_quality=100, method=5, **extra)
return buf.getvalue()
def _visible_rgba(img) -> bytes:
"""RGBA bytes, ignoring the colour hidden under fully transparent pixels."""
from PIL import Image
img = img.convert("RGBA")
mask = img.getchannel("A").point(lambda v: 255 if v else 0)
return Image.composite(img, Image.new("RGBA", img.size, (0, 0, 0, 0)), mask).tobytes()
def _lossless_matches(img, webp: bytes) -> bool:
"""Safety net: a lossless result must decode to the very same picture."""
from PIL import Image
with Image.open(io.BytesIO(webp)) as out:
out.load()
return out.size == img.size and _visible_rgba(out) == _visible_rgba(img)
def _write_replace(path: Path, data: bytes) -> None:
tmp = path.with_name(path.name + ".riaslink-tmp")
tmp.write_bytes(data)
os.replace(tmp, path)
# (before, after, changed, skipped, error)
_Outcome = tuple
def _convert_one(job: tuple) -> _Outcome:
"""Worker: converts one file in place. Module-level so a process pool can pickle it."""
from PIL import Image
path_str, rel, key, mode = job
path = Path(path_str)
try:
size = path.stat().st_size
if size < MIN_BYTES:
return (0, 0, False, True, None)
data = path.read_bytes()
encrypted = path.suffix.lower() in ENCRYPTED_IMAGE_EXT
if encrypted:
plain = decrypt_rpg(data, key) if key else None
if plain is None:
return (0, 0, False, True, None)
else:
plain = data
with Image.open(io.BytesIO(plain)) as img:
if img.format == "WEBP" or getattr(img, "is_animated", False):
return (0, 0, False, True, None)
if img.width > WEBP_MAX_SIDE or img.height > WEBP_MAX_SIDE:
return (0, 0, False, True, None)
img.load()
if not _safe_to_convert(img):
return (0, 0, False, True, None)
lossless = (
mode == "lossless"
or not is_lossy_candidate(rel)
or _few_colours(img)
or (img.format == "PNG" and img.width * img.height <= 256 * 256)
)
webp = _encode_webp(img, lossless)
if lossless and not _lossless_matches(img, webp):
return (0, 0, False, True, None)
new = encrypt_rpg(webp, key, data[: len(RPG_HEADER)]) if encrypted else webp
if len(new) > size * KEEP_RATIO:
return (0, 0, False, True, None)
_write_replace(path, new)
return (size, len(new), True, False, None)
except Exception as exc: # noqa: BLE001 — a bad file must never stop the build
return (0, 0, False, False, f"{rel}: {exc}")
def available_cpus(cgroup_cpu_max: Path = Path("/sys/fs/cgroup/cpu.max")) -> int:
"""CPUs this process may really use.
os.cpu_count() reports the host's cores (64 here) even when the container
is limited to 8 vCPUs; one worker per host core would decode that many
large images at once and run out of memory. The cgroup v2 quota wins.
"""
try:
cpus = len(os.sched_getaffinity(0))
except (AttributeError, OSError):
cpus = os.cpu_count() or 1
try:
quota, period = cgroup_cpu_max.read_text().split()[:2]
if quota != "max":
cpus = min(cpus, max(1, -(-int(quota) // int(period))))
except (OSError, ValueError):
pass
return max(1, cpus)
def _image_files(www_dir: Path) -> list[Path]:
root = www_dir / "img"
if not root.is_dir():
return []
wanted = PLAIN_IMAGE_EXT + ENCRYPTED_IMAGE_EXT
return sorted(p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in wanted)
def optimize_images(
www_dir: Path,
mode: Mode,
workers: Optional[int] = None,
log: Optional[Callable[[str], None]] = None,
) -> StepResult:
"""Re-encodes www/img/** as WebP in place; see the module docstring."""
key = rpg_key(www_dir)
jobs = [(str(p), p.relative_to(www_dir).as_posix(), key, mode) for p in _image_files(www_dir)]
result = StepResult()
workers = workers or available_cpus()
def collect(outcomes) -> None:
for before, after, changed, skipped, error in outcomes:
result.processed += 1
if error:
result.errors.append(error)
elif changed:
result.changed += 1
result.before += before
result.after += after
elif skipped:
result.skipped += 1
if log and result.processed % 200 == 0:
log(f" … {result.processed}/{len(jobs)} görsel işlendi")
if workers == 1 or len(jobs) < 2:
collect(map(_convert_one, jobs))
else:
with ProcessPoolExecutor(max_workers=workers) as pool:
collect(pool.map(_convert_one, jobs, chunksize=4))
return result
# ----------------------------------------------------------------------
# Audio / video twins
# ----------------------------------------------------------------------
# RPG Maker ships every sound twice (.ogg and .m4a) and often every movie
# twice (.webm and .mp4), then picks one format at run time. On Android the
# other copy is never read, so it can stay out of the APK. Which one is used
# is read from the game's own engine code: only the stock implementations
# below are trusted, anything changed or overridden by a plugin is skipped.
_ENGINE_FILES = {
"mv": ("js/rpg_core.js", "js/rpg_managers.js", "js/rpg_objects.js"),
"mz": ("js/rmmz_core.js", "js/rmmz_managers.js", "js/rmmz_objects.js"),
}
# Stock bodies (rpgtkoolmv/corescript for MV, rmmz v1.3.3 for MZ; see
# tests/fixtures/engine) and what they return inside Android WebView.
# MV: Utils.isMobileDevice() matches "Android". MZ: Chromium answers
# "probably" to canPlayType('video/webm; codecs="vp8, vorbis"').
_STOCK = {
"mv": {
"audio": ("AudioManager.audioFileExt", """
if (WebAudio.canPlayOgg() && !Utils.isMobileDevice()) {
return '.ogg';
} else {
return '.m4a';
}""", ".m4a"),
"video": ("Game_Interpreter.prototype.videoFileExt", """
if (Graphics.canPlayVideoType('video/webm') && !Utils.isMobileDevice()) {
return '.webm';
} else {
return '.mp4';
}""", ".mp4"),
},
"mz": {
"audio": ("AudioManager.audioFileExt", 'return ".ogg";', ".ogg"),
"video": ("Game_Interpreter.prototype.videoFileExt", """
if (Utils.canPlayWebm()) {
return ".webm";
} else {
return ".mp4";
}""", ".webm"),
},
}
_STOCK_CAN_PLAY_WEBM = """
if (!Utils._videoElement) {
Utils._videoElement = document.createElement("video");
}
return !!(
Utils._videoElement &&
Utils._videoElement.canPlayType('video/webm; codecs="vp8, vorbis"')
);"""
# Engine functions a plugin may replace, per decision.
_DEPENDS = {
"mv": {"audio": ("audioFileExt", "isMobileDevice"), "video": ("videoFileExt", "isMobileDevice")},
"mz": {"audio": ("audioFileExt",), "video": ("videoFileExt", "canPlayWebm")},
}
_MEDIA = {
"audio": ("audio", {".ogg": (".ogg", ".rpgmvo", ".ogg_"), ".m4a": (".m4a", ".rpgmvm", ".m4a_")}),
"video": ("movies", {".webm": (".webm",), ".mp4": (".mp4",)}),
}
def engine_kind(www_dir: Path) -> Optional[str]:
if (www_dir / "js" / "rmmz_core.js").is_file():
return "mz"
if (www_dir / "js" / "rpg_core.js").is_file():
return "mv"
return None
def _normalise_js(code: str) -> str:
return re.sub(r"\s+", "", code).replace('"', "'")
def _function_body(source: str, name: str) -> Optional[str]:
"""Body of `<name> = function() { ... }` (braces matched), or None."""
found = re.search(re.escape(name) + r"\s*=\s*function\s*\(\s*\)\s*\{", source)
if not found:
return None
depth, start = 1, found.end()
for i in range(start, len(source)):
if source[i] == "{":
depth += 1
elif source[i] == "}":
depth -= 1
if depth == 0:
return source[start:i]
return None
def mobile_formats(www_dir: Path) -> tuple[Optional[dict], str]:
"""({"audio": ext, "video": ext} for what the engine plays on Android, why anything is missing)."""
kind = engine_kind(www_dir)
if kind is None:
return None, "motor (MV/MZ) tanınmadı"
source = "\n".join(
(www_dir / rel).read_text(encoding="utf-8", errors="replace")
for rel in _ENGINE_FILES[kind] if (www_dir / rel).is_file()
)
plugins = "\n".join(
p.read_text(encoding="utf-8", errors="replace")
for p in sorted((www_dir / "js" / "plugins").glob("*.js"))
) if (www_dir / "js" / "plugins").is_dir() else ""
formats: dict = {}
reasons: list[str] = []
mobile_ok = kind != "mv" or "Android" in (_function_body(source, "Utils.isMobileDevice") or "")
webm_ok = kind != "mz" or (
_normalise_js(_function_body(source, "Utils.canPlayWebm") or "") == _normalise_js(_STOCK_CAN_PLAY_WEBM)
)
for media, (name, stock_body, ext) in _STOCK[kind].items():
overridden = [f for f in _DEPENDS[kind][media] if re.search(r"\b" + f + r"\s*=", plugins)]
body = _function_body(source, name)
if overridden:
reasons.append(f"{media}: bir eklenti {', '.join(overridden)} işlevini değiştiriyor")
elif body is None or _normalise_js(body) != _normalise_js(stock_body):
reasons.append(f"{media}: motorun {name} kodu standart değil")
elif not mobile_ok or (media == "video" and not webm_ok):
reasons.append(f"{media}: motorun cihaz algılama kodu standart değil")
else:
formats[media] = ext
return formats, "; ".join(reasons)
def drop_unused_media(www_dir: Path, log: Optional[Callable[[str], None]] = None) -> StepResult:
"""Deletes the audio/video copies Android never loads (only when the used twin exists)."""
result = StepResult()
formats, reason = mobile_formats(www_dir)
if reason and log:
log(f" Atlandı — {reason}.")
for media, keep in (formats or {}).items():
folder, groups = _MEDIA[media]
root = www_dir / folder
if not root.is_dir():
continue
keep_exts = groups[keep]
drop_exts = tuple(e for ext, group in groups.items() if ext != keep for e in group)
for path in sorted(root.rglob("*")):
if not path.is_file() or path.suffix.lower() not in drop_exts:
continue
result.processed += 1
stem = path.with_suffix("")
if not any(stem.with_name(stem.name + ext).is_file() for ext in keep_exts):
result.skipped += 1
continue
size = path.stat().st_size
path.unlink()
result.changed += 1
result.before += size
return result
|