270 lines
9.4 KiB
Python
270 lines
9.4 KiB
Python
"""曲包(.zip)讀寫與驗證
|
||
|
||
<id>.zip
|
||
├─ config.json 必要
|
||
├─ easy.json / normal.json / hard.json 至少一個(統一格式:Chart.chart_json)
|
||
├─ music.wav|.ogg|.mp3 / video.mp4 至少一個;只有影片時會從影片抽出 music.wav
|
||
└─ image.png 必要,正方形
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import tempfile
|
||
import zipfile
|
||
|
||
from chart import Chart
|
||
|
||
PACK_FORMAT = 1
|
||
DIFFS = ("easy", "normal", "hard")
|
||
MUSIC_NAMES = ("music.wav", "music.ogg", "music.mp3")
|
||
VIDEO_NAME = "video.mp4"
|
||
IMAGE_NAME = "image.png"
|
||
CONFIG_NAME = "config.json"
|
||
IMAGE_SIZE = 512
|
||
ALLOWED = {CONFIG_NAME, IMAGE_NAME, VIDEO_NAME, *MUSIC_NAMES, *(f"{d}.json" for d in DIFFS)}
|
||
|
||
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,63}$")
|
||
REQUIRED_TEXT = ("id", "name", "artist")
|
||
REQUIRED_NUM = ("bpm", "beat_offset", "offset")
|
||
|
||
|
||
def default_config(**over):
|
||
c = {"format": PACK_FORMAT, "id": "", "name": "", "artist": "", "charter": "",
|
||
"bpm": 120.0, "beat_offset": 0, "offset": 0, "preview_start": 0, "preview_length": 15000}
|
||
c.update(over)
|
||
return c
|
||
|
||
|
||
class SongPack:
|
||
def __init__(self, config=None):
|
||
self.workdir = tempfile.mkdtemp(prefix="rhypack_")
|
||
self.config = config or default_config()
|
||
self.charts = {} # 難度 → Chart
|
||
self.path = None # 對應的 .zip
|
||
|
||
# ---------- 檔案位置 ----------
|
||
def file(self, name):
|
||
return os.path.join(self.workdir, name)
|
||
|
||
@property
|
||
def music(self):
|
||
for n in MUSIC_NAMES:
|
||
if os.path.exists(self.file(n)):
|
||
return self.file(n)
|
||
return None
|
||
|
||
@property
|
||
def video(self):
|
||
return self.file(VIDEO_NAME) if os.path.exists(self.file(VIDEO_NAME)) else None
|
||
|
||
@property
|
||
def image(self):
|
||
return self.file(IMAGE_NAME) if os.path.exists(self.file(IMAGE_NAME)) else None
|
||
|
||
def close(self):
|
||
shutil.rmtree(self.workdir, ignore_errors=True)
|
||
|
||
# ---------- 難度 ----------
|
||
# 「難度存在」= charts 裡有這個 key(曲包內有該檔案,可以是空譜面)
|
||
def enabled(self):
|
||
return [d for d in DIFFS if d in self.charts]
|
||
|
||
def enable(self, diff, num=None):
|
||
self.chart(diff, create=True)
|
||
if num is not None:
|
||
self.config[f"{diff}_num"] = int(num)
|
||
|
||
def disable(self, diff):
|
||
self.charts.pop(diff, None)
|
||
self.config.pop(f"{diff}_num", None)
|
||
|
||
# ---------- 內容 ----------
|
||
def chart(self, diff, create=False):
|
||
if diff not in self.charts and create:
|
||
self.charts[diff] = Chart(self.music or "", float(self.config["bpm"]),
|
||
int(self.config["beat_offset"]), 4, [])
|
||
return self.charts.get(diff)
|
||
|
||
def sync_timing(self):
|
||
"""config 的 bpm / beat_offset 套用到各難度(Maker 格線用)"""
|
||
for c in self.charts.values():
|
||
c.bpm = float(self.config["bpm"])
|
||
c.offset = int(self.config["beat_offset"])
|
||
c.audio = self.music or ""
|
||
|
||
def set_music(self, src):
|
||
ext = os.path.splitext(src)[1].lower()
|
||
name = f"music{ext}"
|
||
if name not in MUSIC_NAMES:
|
||
raise ValueError("音訊只支援 wav / ogg / mp3")
|
||
for n in MUSIC_NAMES:
|
||
if os.path.exists(self.file(n)):
|
||
os.remove(self.file(n))
|
||
shutil.copyfile(src, self.file(name))
|
||
self.sync_timing()
|
||
|
||
def set_video(self, src):
|
||
shutil.copyfile(src, self.file(VIDEO_NAME))
|
||
# 時間以音訊為準:沒有音訊時從影片抽出
|
||
if self.music is None:
|
||
extract_audio(self.file(VIDEO_NAME), self.file("music.wav"))
|
||
self.sync_timing()
|
||
|
||
def set_image(self, src):
|
||
import_image(src, self.file(IMAGE_NAME))
|
||
|
||
|
||
# ---------- 讀寫 ----------
|
||
|
||
def open_pack(zip_path):
|
||
pack = SongPack()
|
||
with zipfile.ZipFile(zip_path) as z:
|
||
for info in z.infolist():
|
||
name = info.filename
|
||
# 只接受白名單檔名(防止 zip 內的路徑寫到別處)
|
||
if name not in ALLOWED:
|
||
continue
|
||
with z.open(info) as src, open(pack.file(name), "wb") as dst:
|
||
shutil.copyfileobj(src, dst)
|
||
|
||
if os.path.exists(pack.file(CONFIG_NAME)):
|
||
pack.config = default_config(**json.load(open(pack.file(CONFIG_NAME), encoding="utf-8")))
|
||
for d in DIFFS:
|
||
p = pack.file(f"{d}.json")
|
||
if os.path.exists(p):
|
||
pack.charts[d] = Chart.from_chart_json(json.load(open(p, encoding="utf-8")),
|
||
pack.config["bpm"], pack.config["beat_offset"],
|
||
pack.music or "")
|
||
pack.path = zip_path
|
||
return pack
|
||
|
||
|
||
def save_pack(pack, zip_path):
|
||
"""驗證通過才寫入;先寫暫存檔再取代,失敗不會弄壞原本的曲包"""
|
||
errors = validate_pack(pack)
|
||
if errors:
|
||
raise ValueError(";".join(errors))
|
||
|
||
pack.config["format"] = PACK_FORMAT
|
||
tmp = zip_path + ".tmp"
|
||
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as z:
|
||
z.writestr(CONFIG_NAME, json.dumps(pack.config, ensure_ascii=False, indent=2))
|
||
# 啟用的難度全部寫入(空譜面也寫,代表這個難度存在)
|
||
for d in pack.enabled():
|
||
z.writestr(f"{d}.json", json.dumps(pack.charts[d].chart_json(), ensure_ascii=False, indent=1))
|
||
# 音訊 / 影片本身已壓縮或很大,不再壓縮
|
||
for path in (pack.music, pack.video):
|
||
if path:
|
||
z.write(path, os.path.basename(path), compress_type=zipfile.ZIP_STORED)
|
||
z.write(pack.image, IMAGE_NAME, compress_type=zipfile.ZIP_STORED)
|
||
os.replace(tmp, zip_path)
|
||
pack.path = zip_path
|
||
|
||
|
||
def validate_pack(pack):
|
||
errors = []
|
||
cfg = pack.config
|
||
|
||
for k in REQUIRED_TEXT:
|
||
if not str(cfg.get(k, "")).strip():
|
||
errors.append(f"config 缺少 {k}")
|
||
if cfg.get("id") and not ID_RE.match(cfg["id"]):
|
||
errors.append("id 只能用小寫英數字與 -(2~64 字)")
|
||
for k in REQUIRED_NUM:
|
||
try:
|
||
float(cfg.get(k))
|
||
except (TypeError, ValueError):
|
||
errors.append(f"config 的 {k} 必須是數字")
|
||
try:
|
||
if float(cfg.get("bpm", 0)) <= 0:
|
||
errors.append("bpm 必須大於 0")
|
||
except (TypeError, ValueError):
|
||
pass
|
||
|
||
present = pack.enabled()
|
||
if not present:
|
||
errors.append("至少需要啟用一個難度")
|
||
for d in present:
|
||
v = cfg.get(f"{d}_num")
|
||
if not isinstance(v, int) or not (1 <= v <= 99):
|
||
errors.append(f"{d} 有譜面,config 需要 {d}_num(1~99 的整數)")
|
||
|
||
if pack.music is None and pack.video is None:
|
||
errors.append("至少需要 music 或 video")
|
||
if pack.image is None:
|
||
errors.append("缺少 image.png")
|
||
else:
|
||
from PIL import Image
|
||
with Image.open(pack.image) as im:
|
||
if im.width != im.height:
|
||
errors.append(f"image.png 必須是正方形(目前 {im.width}x{im.height})")
|
||
return errors
|
||
|
||
|
||
# ---------- 媒體 ----------
|
||
|
||
def import_image(src, dst, size=IMAGE_SIZE):
|
||
"""置中裁成正方形並縮放"""
|
||
from PIL import Image
|
||
with Image.open(src) as im:
|
||
im = im.convert("RGBA")
|
||
side = min(im.size)
|
||
left, top = (im.width - side) // 2, (im.height - side) // 2
|
||
im = im.crop((left, top, left + side, top + side)).resize((size, size), Image.LANCZOS)
|
||
im.save(dst, "PNG")
|
||
|
||
|
||
def convert_audio(src, dst, quality=6):
|
||
"""轉成 Ogg Vorbis(quality 0~10,6 約 192kbps),44.1kHz 雙聲道"""
|
||
import imageio_ffmpeg
|
||
ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
|
||
subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", src, "-vn", "-ac", "2", "-ar", "44100",
|
||
"-c:a", "libvorbis", "-q:a", str(quality), dst], check=True)
|
||
|
||
|
||
def extract_audio(video, dst):
|
||
"""用 imageio-ffmpeg 內附的 ffmpeg 抽出 44.1kHz 雙聲道 wav"""
|
||
import imageio_ffmpeg
|
||
ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
|
||
subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", video, "-vn", "-ac", "2", "-ar", "44100",
|
||
"-f", "wav", dst], check=True)
|
||
|
||
|
||
def create_pack(zip_path, config, media, image, diffs):
|
||
"""建立新曲包並立即存檔(譜面可為空);diffs = {難度: 難度數字}。回傳已開啟的 SongPack"""
|
||
pack = SongPack(default_config(**config))
|
||
try:
|
||
if media.lower().endswith(".mp4"):
|
||
pack.set_video(media)
|
||
else:
|
||
pack.set_music(media)
|
||
pack.set_image(image)
|
||
for d, num in diffs.items():
|
||
pack.enable(d, num)
|
||
save_pack(pack, zip_path)
|
||
except Exception:
|
||
pack.close()
|
||
raise
|
||
return pack
|
||
|
||
|
||
# ---------- 遷移 ----------
|
||
|
||
def pack_from_lanes(lanes_by_diff, image_src, **config):
|
||
"""把舊的 *.lanes.json(每難度一份)轉成曲包;音訊取第一份的 audio"""
|
||
pack = SongPack()
|
||
first = None
|
||
for d, path in lanes_by_diff.items():
|
||
c = Chart.load(path)
|
||
if first is None:
|
||
first = (c, path)
|
||
pack.charts[d] = c
|
||
c0, p0 = first
|
||
audio = c0.audio if os.path.isabs(c0.audio) else os.path.join(os.path.dirname(p0), c0.audio)
|
||
pack.config = default_config(bpm=c0.bpm, beat_offset=c0.offset, **config)
|
||
pack.set_music(audio)
|
||
pack.set_image(image_src)
|
||
return pack
|