feat(review): save reviews as WebM or MP4 video
public
feat(review): save reviews as WebM or MP4 video Frames come from the timeline via the video exporter, audio is muxed in (Opus copied into WebM, AAC for MP4) and the PGN goes into the PGN metadata tag. Rendering runs in a thread. End bar uses a CenterBox: the balancing spacer forced the window to twice the button width.
| Changeset | edd0b797e29bc8f1dc7ca7e4cf3689280899fcb7 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | 7e411757db8b |
| Children | 05e3473ace04 |
| Pushlog | by timo via ssh by timo via ssh |
modified roadmap/nachbesprechung.md +4 −1
| @@ -71,7 +71,10 @@ Spielfarben auf der Partie, nur in Varianten getönt (im Nachspielen dagegen immer getönt). | ||
| 71 | 71 | Esc beendet die Aufnahme nicht; beim Schließen fragt die App. „Fertig“ speichert eine |
| 72 | 72 | Opus-Datei mit der PGN samt Zeitleiste darin (`schach/recording.py`, `schach/review.py`). |
| 73 | 73 | |
| 74 | -Offen: Video (WebM/MP4) aus Zeitleiste und Ton, über den Video-Export und ffmpeg. | |
| 74 | +Beim Speichern lässt sich statt Opus auch WebM oder MP4 wählen (braucht ffmpeg): Die Bilder | |
| 75 | +entstehen aus der Zeitleiste über den Video-Export (Schritte gleiten, Sprünge nicht, Varianten | |
| 76 | +getönt), der Ton kommt dazu (WebM: Opus unverändert, MP4: AAC), die PGN als Metadaten `PGN`. | |
| 77 | +Das Video entsteht im Hintergrund. | |
| 75 | 78 | |
| 76 | 79 | ### Bisheriger Plan |
| 77 | 80 | |
modified schach/endbar.py +11 −14
| @@ -17,7 +17,7 @@ CSS = b""" | ||
| 17 | 17 | padding: 6px; |
| 18 | 18 | } |
| 19 | 19 | .end-bar:backdrop { background-color: color-mix(in srgb, #7d7d83 15%, var(--window-bg-color)); } |
| 20 | -.end-bar:backdrop > label, .end-bar:backdrop > box { filter: opacity(0.5); } | |
| 20 | +.end-bar:backdrop > box { filter: opacity(0.5); } | |
| 21 | 21 | """ |
| 22 | 22 | |
| 23 | 23 | |
| @@ -28,22 +28,19 @@ class EndBar(Gtk.Revealer): | ||
| 28 | 28 | provider.load_from_data(CSS) |
| 29 | 29 | Gtk.StyleContext.add_provider_for_display(self.get_display(), provider, |
| 30 | 30 | Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) |
| 31 | - bar = Gtk.Box(spacing=6, css_classes=["end-bar"]) | |
| 32 | - # links so viel Platz wie rechts die Knöpfe brauchen: der Text steht in der Mitte des Fensters | |
| 33 | - self._balance = Gtk.SizeGroup(mode=Gtk.SizeGroupMode.HORIZONTAL) | |
| 34 | - spacer = Gtk.Box() | |
| 35 | - self.label = Gtk.Label(hexpand=True, wrap=True, justify=Gtk.Justification.CENTER, | |
| 36 | - margin_start=6, margin_end=6) | |
| 31 | + # CenterBox: Text in der Mitte des Fensters, solange Platz ist; sonst rückt er zur Seite | |
| 32 | + # (eine Box mit gleich breitem Platzhalter links verlangte die doppelte Knopfbreite) | |
| 33 | + bar = Gtk.CenterBox(css_classes=["end-bar"]) | |
| 34 | + middle = Gtk.Box(spacing=6) | |
| 35 | + self.label = Gtk.Label(wrap=True, justify=Gtk.Justification.CENTER, margin_start=6, margin_end=6) | |
| 37 | 36 | self.label.add_css_class("heading") |
| 38 | 37 | self.level = Gtk.LevelBar(min_value=0.0, max_value=1.0, width_request=80, valign=Gtk.Align.CENTER, |
| 39 | 38 | visible=False, tooltip_text="Mikrofon-Pegel") |
| 40 | - self.buttons = Gtk.Box(spacing=6, halign=Gtk.Align.END) | |
| 41 | - self._balance.add_widget(spacer) | |
| 42 | - self._balance.add_widget(self.buttons) | |
| 43 | - bar.append(spacer) | |
| 44 | - bar.append(self.label) | |
| 45 | - bar.append(self.level) | |
| 46 | - bar.append(self.buttons) | |
| 39 | + self.buttons = Gtk.Box(spacing=6, halign=Gtk.Align.END, margin_start=6) | |
| 40 | + middle.append(self.label) | |
| 41 | + middle.append(self.level) | |
| 42 | + bar.set_center_widget(middle) | |
| 43 | + bar.set_end_widget(self.buttons) | |
| 47 | 44 | self.set_child(bar) |
| 48 | 45 | self._shown = None |
| 49 | 46 | |
modified schach/export.py +70 −7
| @@ -1272,11 +1272,68 @@ def _video_timeline(state, opts): | ||
| 1272 | 1272 | |
| 1273 | 1273 | |
| 1274 | 1274 | def _to_video(fmt, state, opts): |
| 1275 | - problem = video_problem(fmt, opts.ffmpeg) | |
| 1275 | + timeline, end = _video_timeline(state, opts) | |
| 1276 | + return _encode_video(fmt, timeline, end, opts.ffmpeg) | |
| 1277 | + | |
| 1278 | + | |
| 1279 | +def review_timeline(state, frames, end, opts): | |
| 1280 | + """Bildfolge einer Nachbesprechung: [(diagramm, start_ms)] aus der Zeitleiste | |
| 1281 | + [(ms, Zugfolge, Zeichnung)] (recording.decode). Einzelne Schritte nach vorn gleiten | |
| 1282 | + (VIDEO_MOVE_MS ab dem Zeitpunkt des Zugs), Sprünge nicht. Varianten sind getönt wie im | |
| 1283 | + Fenster, die Partie bleibt in den Spielfarben.""" | |
| 1284 | + root, main = state.board.root(), list(state.board.move_stack) | |
| 1285 | + names = None | |
| 1286 | + if opts.players: | |
| 1287 | + i = info(state) | |
| 1288 | + names = {chess.WHITE: i.white, chess.BLACK: i.black} | |
| 1289 | + timeline, previous = [], None | |
| 1290 | + for index, (start, path, shapes) in enumerate(frames): | |
| 1291 | + board = root.copy() | |
| 1292 | + try: | |
| 1293 | + for move in path: | |
| 1294 | + board.push(move) | |
| 1295 | + except AssertionError: | |
| 1296 | + continue # Zug passt nicht (Datei verändert?): Bild auslassen | |
| 1297 | + diagram_ = Diagram(board, theme=opts.theme, scheme=opts.scheme, flipped=opts.flipped, | |
| 1298 | + last_move=opts.last_move, names=names) | |
| 1299 | + diagram_.drawn = tuple(shapes) | |
| 1300 | + diagram_.imagined = list(path) != main[:len(path)] | |
| 1301 | + following = frames[index + 1][0] if index + 1 < len(frames) else end | |
| 1302 | + motion = None | |
| 1303 | + if previous is not None and len(path) == len(previous) + 1 and tuple(path[:-1]) == tuple(previous): | |
| 1304 | + before = board.copy() | |
| 1305 | + before.pop() | |
| 1306 | + motion = move_motion(before, path[-1]) | |
| 1307 | + moving = min(VIDEO_MOVE_MS, (following - start) // 2) if motion else 0 | |
| 1308 | + if moving > 0: | |
| 1309 | + steps = max(1, round(moving * VIDEO_FPS / 1000)) | |
| 1310 | + for j in range(steps): | |
| 1311 | + frame = copy.copy(diagram_) | |
| 1312 | + frame._anim = {**motion, "progress": ease_out((j + 1) / steps)} # pylint: disable=protected-access | |
| 1313 | + timeline.append((frame, start + j * moving // steps)) | |
| 1314 | + timeline.append((diagram_, start + moving)) | |
| 1315 | + else: | |
| 1316 | + timeline.append((diagram_, start)) | |
| 1317 | + previous = path | |
| 1318 | + return timeline | |
| 1319 | + | |
| 1320 | + | |
| 1321 | +def review_video(fmt, state, frames, end, audio, pgn, opts): | |
| 1322 | + """Nachbesprechung als WebM oder MP4: Bilder aus der Zeitleiste, Ton aus ``audio`` (Opus), | |
| 1323 | + die PGN samt Zeitleiste als Metadaten ``PGN`` (die App öffnet das Video wieder).""" | |
| 1324 | + return _encode_video(fmt, review_timeline(state, frames, end, opts), end, opts.ffmpeg, audio=audio, | |
| 1325 | + metadata={"PGN": pgn}) | |
| 1326 | + | |
| 1327 | + | |
| 1328 | +AUDIO_CODECS = {"webm": ["-c:a", "copy"], "mp4": ["-c:a", "aac", "-b:a", "96k"]} # Opus passt nur in WebM | |
| 1329 | + | |
| 1330 | + | |
| 1331 | +def _encode_video(fmt, timeline, end, ffmpeg="", audio=None, metadata=None): | |
| 1332 | + """Video aus [(diagramm, start_ms)] bis ``end`` über ffmpeg; dazu optional eine Tonspur und Metadaten.""" | |
| 1333 | + problem = video_problem(fmt, ffmpeg) | |
| 1276 | 1334 | if problem: |
| 1277 | 1335 | raise ExportError(problem) |
| 1278 | 1336 | encoder, args = VIDEO_CODECS[fmt] |
| 1279 | - timeline, end = _video_timeline(state, opts) | |
| 1280 | 1337 | width = APNG_WIDTH |
| 1281 | 1338 | height = math.ceil(width * timeline[0][0].aspect()) |
| 1282 | 1339 | height += height % 2 # 4:2:0 braucht gerade Maße |
| @@ -1284,8 +1341,10 @@ def _to_video(fmt, state, opts): | ||
| 1284 | 1341 | |
| 1285 | 1342 | def rendered(): |
| 1286 | 1343 | for index, (diagram_, start) in enumerate(timeline): |
| 1344 | + left = starts[index + 1] - start | |
| 1345 | + if left <= 0: | |
| 1346 | + continue # gleichzeitig ersetzt (z. B. Zug und Pfeil im selben Augenblick) | |
| 1287 | 1347 | pixels, stride = _paint(diagram_, width, height) |
| 1288 | - left = starts[index + 1] - start | |
| 1289 | 1348 | while left > 0: # lange Ruhe in Stücken, siehe VIDEO_HOLD_MS |
| 1290 | 1349 | part = min(VIDEO_HOLD_MS, left) |
| 1291 | 1350 | yield pixels, stride, width, height, part |
| @@ -1298,11 +1357,15 @@ def _to_video(fmt, state, opts): | ||
| 1298 | 1357 | with open(source, "wb") as fh: |
| 1299 | 1358 | fh.write(_apng(rendered(), min_delay=1, merge=False, level=1)) # Zwischendatei: schnell statt klein |
| 1300 | 1359 | out = os.path.join(tmp, f"partie.{fmt}") |
| 1301 | - command = [find_ffmpeg(opts.ffmpeg), "-hide_banner", "-loglevel", "error", "-y", | |
| 1302 | - "-f", "apng", "-i", source, "-fps_mode", "vfr", "-enc_time_base:v", "1:1000", | |
| 1303 | - "-c:v", encoder, *args, "-pix_fmt", "yuv420p", out] | |
| 1360 | + sound = ["-i", audio, "-map", "0:v", "-map", "1:a", *AUDIO_CODECS[fmt]] if audio else [] | |
| 1361 | + tags = [item for key, value in (metadata or {}).items() for item in ("-metadata", f"{key}={value}")] | |
| 1362 | + if tags and fmt == "mp4": | |
| 1363 | + args = [("+faststart+use_metadata_tags" if a == "+faststart" else a) for a in args] | |
| 1364 | + command = [find_ffmpeg(ffmpeg), "-hide_banner", "-loglevel", "error", "-y", | |
| 1365 | + "-f", "apng", "-i", source, *sound, "-fps_mode", "vfr", "-enc_time_base:v", "1:1000", | |
| 1366 | + "-c:v", encoder, *args, "-pix_fmt", "yuv420p", *tags, out] | |
| 1304 | 1367 | try: |
| 1305 | - done = subprocess.run(command, capture_output=True, text=True, timeout=900, **_NO_WINDOW) | |
| 1368 | + done = subprocess.run(command, capture_output=True, text=True, timeout=1800, **_NO_WINDOW) | |
| 1306 | 1369 | except (OSError, subprocess.SubprocessError) as exc: |
| 1307 | 1370 | raise ExportError(f"ffmpeg ließ sich nicht ausführen: {exc}") from exc |
| 1308 | 1371 | if done.returncode != 0 or not os.path.exists(out): |
modified schach/recording.py +9 −0
| @@ -249,6 +249,15 @@ def read_matroska_tags(data): | ||
| 249 | 249 | return found |
| 250 | 250 | |
| 251 | 251 | |
| 252 | +def duration_ms(data): | |
| 253 | + """Länge einer Opus-Datei in ms (Granulposition der letzten Seite, 48 kHz, ohne Vorlauf).""" | |
| 254 | + pages = _pages(data) | |
| 255 | + packets, _ = _packets(pages, 1) | |
| 256 | + pre_skip = struct.unpack_from("<H", packets[0], 10)[0] if packets[0].startswith(b"OpusHead") else 0 | |
| 257 | + granule = max((struct.unpack_from("<q", head, 6)[0] for head, _l, _b in pages), default=0) | |
| 258 | + return max(0, (granule - pre_skip) * 1000 // 48000) | |
| 259 | + | |
| 260 | + | |
| 252 | 261 | def write_pgn(data, pgn): |
| 253 | 262 | """Opus-Datei (Bytes) mit der PGN im Vorbis-Kommentar; die Tonspur bleibt unverändert.""" |
| 254 | 263 | pages = _pages(data) |
modified schach/review.py +69 −17
| @@ -10,6 +10,7 @@ import datetime | ||
| 10 | 10 | import io |
| 11 | 11 | import os |
| 12 | 12 | import re |
| 13 | +import threading | |
| 13 | 14 | from struct import error as struct_error |
| 14 | 15 | |
| 15 | 16 | import chess |
| @@ -144,38 +145,89 @@ class ReviewMixin: | ||
| 144 | 145 | return f'{header}\n[Replay "{timeline.encode()}"]\n\n{moves}' |
| 145 | 146 | |
| 146 | 147 | def _review_save(self, path, timeline): |
| 148 | + """Speichern-Dialog: Opus (nur Ton, die PGN darin) oder WebM/MP4 (Video mit Ton, braucht ffmpeg).""" | |
| 149 | + pgn = self._review_pgn(timeline) | |
| 147 | 150 | try: |
| 148 | 151 | with open(path, "rb") as f: |
| 149 | - data = recording.write_pgn(f.read(), self._review_pgn(timeline)) | |
| 150 | - except (OSError, ValueError) as error: | |
| 152 | + audio = f.read() | |
| 153 | + data = recording.write_pgn(audio, pgn) | |
| 154 | + except (OSError, ValueError, struct_error) as error: | |
| 151 | 155 | self.toasts.add_toast(Adw.Toast(title=f"Aufnahme unbrauchbar: {error}")) |
| 152 | 156 | return |
| 153 | 157 | name = re.sub(r'[/\\:*?"<>|]', "-", self.save_name or "Partie") |
| 154 | 158 | dialog = Gtk.FileDialog(title="Nachbesprechung speichern", initial_name=f"Nachbesprechung {name}.opus") |
| 155 | - audio = Gtk.FileFilter(name="Opus-Audio") | |
| 156 | - audio.add_suffix("opus") | |
| 157 | 159 | filters = Gio.ListStore.new(Gtk.FileFilter) |
| 158 | - filters.append(audio) | |
| 160 | + for label, suffix in (("Opus-Audio (für die App)", "opus"), ("WebM-Video", "webm"), ("MP4-Video", "mp4")): | |
| 161 | + choice = Gtk.FileFilter(name=label) | |
| 162 | + choice.add_suffix(suffix) | |
| 163 | + filters.append(choice) | |
| 159 | 164 | dialog.set_filters(filters) |
| 160 | 165 | |
| 166 | + def retry(): | |
| 167 | + toast = Adw.Toast(title="Nachbesprechung nicht gespeichert", button_label="Doch speichern", timeout=0) | |
| 168 | + toast.connect("button-clicked", lambda *_: self._review_save(path, timeline)) | |
| 169 | + self.toasts.add_toast(toast) | |
| 170 | + | |
| 161 | 171 | def done(dialog, result): |
| 162 | 172 | try: |
| 163 | - target = dialog.save_finish(result) | |
| 173 | + target = dialog.save_finish(result).get_path() | |
| 164 | 174 | except GLib.Error: |
| 165 | - toast = Adw.Toast(title="Nachbesprechung nicht gespeichert", button_label="Doch speichern", | |
| 166 | - timeout=0) | |
| 167 | - toast.connect("button-clicked", lambda *_: self._review_save(path, timeline)) | |
| 168 | - self.toasts.add_toast(toast) | |
| 175 | + retry() | |
| 176 | + return | |
| 177 | + fmt = os.path.splitext(target)[1].lower().lstrip(".") | |
| 178 | + if fmt not in ("webm", "mp4"): | |
| 179 | + self._review_write(target, data, path) | |
| 169 | 180 | return |
| 181 | + frames = recording.decode(timeline.encode()) | |
| 182 | + end = max(recording.duration_ms(audio), frames[-1][0] + 1000 if frames else 0) | |
| 183 | + self._review_render(fmt, target, frames, end, path, pgn, retry) | |
| 184 | + dialog.save(self, None, done) | |
| 185 | + | |
| 186 | + def _review_write(self, target, data, temp): | |
| 187 | + try: | |
| 188 | + with open(target, "wb") as f: | |
| 189 | + f.write(data) | |
| 190 | + except OSError as error: | |
| 191 | + self.toasts.add_toast(Adw.Toast(title=f"Speichern fehlgeschlagen: {error}")) | |
| 192 | + return False | |
| 193 | + try: | |
| 194 | + os.remove(temp) | |
| 195 | + except OSError: | |
| 196 | + pass | |
| 197 | + self.toasts.add_toast(Adw.Toast(title="Nachbesprechung gespeichert", timeout=3)) | |
| 198 | + return True | |
| 199 | + | |
| 200 | + def _review_render(self, fmt, target, frames, end, temp, pgn, retry): | |
| 201 | + """Video im Hintergrund erstellen (dauert je nach Länge eine Weile), dann schreiben.""" | |
| 202 | + from . import export | |
| 203 | + opts = export.Options(theme=self.settings["theme"], scheme=self.settings["scheme"], | |
| 204 | + flipped=self.view.flipped, ffmpeg=self.settings.get("ffmpeg", "")) | |
| 205 | + problem = export.video_problem(fmt, opts.ffmpeg) | |
| 206 | + if problem: | |
| 207 | + self.toasts.add_toast(Adw.Toast(title=problem)) | |
| 208 | + retry() | |
| 209 | + return | |
| 210 | + state = self.state(variations=True) | |
| 211 | + busy = Adw.Toast(title="Video wird erstellt …", timeout=0) | |
| 212 | + self.toasts.add_toast(busy) | |
| 213 | + | |
| 214 | + def work(): | |
| 170 | 215 | try: |
| 171 | - with open(target.get_path(), "wb") as f: | |
| 172 | - f.write(data) | |
| 173 | - os.remove(path) | |
| 174 | - except OSError as error: | |
| 175 | - self.toasts.add_toast(Adw.Toast(title=f"Speichern fehlgeschlagen: {error}")) | |
| 216 | + result = export.review_video(fmt, state, frames, end, temp, pgn, opts) | |
| 217 | + except export.ExportError as error: | |
| 218 | + GLib.idle_add(finished, None, str(error)) | |
| 176 | 219 | return |
| 177 | - self.toasts.add_toast(Adw.Toast(title="Nachbesprechung gespeichert", timeout=3)) | |
| 178 | - dialog.save(self, None, done) | |
| 220 | + GLib.idle_add(finished, result, None) | |
| 221 | + | |
| 222 | + def finished(result, error): | |
| 223 | + busy.dismiss() | |
| 224 | + if error is not None: | |
| 225 | + self.toasts.add_toast(Adw.Toast(title=error)) | |
| 226 | + retry() | |
| 227 | + else: | |
| 228 | + self._review_write(target, result, temp) | |
| 229 | + return GLib.SOURCE_REMOVE | |
| 230 | + threading.Thread(target=work, daemon=True).start() | |
| 179 | 231 | |
| 180 | 232 | def _review_confirm_close(self): |
| 181 | 233 | """Fenster schließen, während aufgenommen wird: erst fragen.""" |
modified tests/test_recording.py +31 −0
| @@ -69,3 +69,34 @@ class WebmTest(unittest.TestCase): | ||
| 69 | 69 | "color=s=64x64:d=1", "-c:a", "libopus", "-c:v", "libvpx-vp9", "-shortest", |
| 70 | 70 | "-metadata", f"PGN={pgn}", path], check=True) |
| 71 | 71 | self.assertEqual(recording.read_pgn(path), pgn) |
| 72 | + | |
| 73 | + | |
| 74 | +@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("gst-launch-1.0"), "ffmpeg oder GStreamer fehlt") | |
| 75 | +class ReviewVideoTest(unittest.TestCase): | |
| 76 | + def test_video_with_sound_and_pgn(self): | |
| 77 | + import io | |
| 78 | + import subprocess | |
| 79 | + import chess.pgn | |
| 80 | + from schach import export, savegames | |
| 81 | + board = chess.Board() | |
| 82 | + for san in ("e4", "e5", "Bc4"): | |
| 83 | + board.push_san(san) | |
| 84 | + state = savegames.GameState(board=board, human=chess.WHITE, elo=600) | |
| 85 | + with tempfile.TemporaryDirectory() as folder: | |
| 86 | + audio = os.path.join(folder, "ton.opus") | |
| 87 | + subprocess.run(["gst-launch-1.0", "-q", "audiotestsrc", "num-buffers=100", "!", "audioconvert", "!", | |
| 88 | + "opusenc", "!", "oggmux", "!", "filesink", f"location={audio}"], check=True) | |
| 89 | + with open(audio, "rb") as f: | |
| 90 | + length = recording.duration_ms(f.read()) | |
| 91 | + self.assertGreater(length, 1500) | |
| 92 | + timeline = "0 =;300 >e2e4;900 >e7e5;1200 #Rf7;1500 =e2e4" | |
| 93 | + pgn = savegames.to_pgn(state).replace("\n\n", f'\n[Replay "{timeline}"]\n\n', 1) | |
| 94 | + frames = recording.decode(chess.pgn.read_headers(io.StringIO(pgn))["Replay"]) | |
| 95 | + data = export.review_video("webm", state, frames, length, audio, pgn, export.Options()) | |
| 96 | + path = os.path.join(folder, "video.webm") | |
| 97 | + with open(path, "wb") as f: | |
| 98 | + f.write(data) | |
| 99 | + self.assertEqual(recording.read_pgn(path), pgn) | |
| 100 | + streams = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", | |
| 101 | + path], capture_output=True, text=True).stdout.split() | |
| 102 | + self.assertEqual(sorted(streams), ["audio", "video"]) | |