From eeb08578c95870ef6e00ef16d00a021e7f34b8d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrew=20Beveridge=20=E2=98=84=EF=B8=8F?= Date: Thu, 15 Oct 2026 15:02:24 -0400 Subject: [PATCH] feat(tenant-theme): CD+G tab in the theme editor with real CD+G previews (v0.274.0) (#1164) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why Commercial producers (Vocal Star first) care a lot about their CD+G output, but the tenant theme editor only covered the MP4 title card / lyrics / end screen. CD+G styling needed an admin to hand-edit the theme JSON. ## What **New "CD+G" tab** (only on portals with `features.enable_cdg` and a `cdg` theme section): - **Up card**: image, title/artist colours, title/artist sizes, separator text between them (e.g. "MADE FAMOUS BY") + its colour, text position from top (keeps text below a logo baked into the image), title–artist gap. - **Lyrics**: sung / unsung / screen / border colours, size, outline width + colour, lyrics font ("Same as main font" or a distinct one, e.g. condensed Oswald). - **Instrumental breaks**: image, text, colour. **Closing screen**: image, line colours. **Real previews**: on the CD+G tab the preview request sets `include_cdg`; the backend composes a short CDG with the real `CDGGenerator` from the draft's `cdg` section and renders the up card + a part-sung lyrics page with the new `karaoke_gen/.../cdg_decoder.py` (single pass, multi-frame; moved out of the CDG test). 300×216 upscaled 3× with hard pixels, ~1 s. Other tabs never pay for it. **Images**: uploads from the CD+G tab are fitted (letterboxed) to 300×216 PNG (`purpose=cdg`); the CD+G dropdowns only offer 300×216 images (`cdg_images` from the editor GET, header-only reads); save/preview reject other sizes since the CDG renderer never resizes. All 4 existing themes' CD+G images verified 300×216. **Validation**: `cdg` hex colours, numeric bounds, single-line text limits; distinct CDG font resolved for the preview the same way renders do (`cdg_font` asset), title/outro use the main font. ## Tests - Backend: CDG validation/fit/size-check/upload/editor list (tenant_theme_service), real CD+G preview renders incl. colour change + distinct font + missing asset + timeout (theme_preview_service), route include_cdg + upload purpose. CDG title-card tests now use the shared decoder. - Frontend: new `TenantThemeEditorCdg.test.tsx` (10): tab gating, includeCdg only on that tab, edits map to `cdg`, outline applies to both strokes, font follow/distinct, fitted upload, CD+G-sized image list, pixelated 300/216 previews. Full jest 1716 pass. - Backend suite: all pass except `test_emulator_integration.py`, which fails identically on main locally (a stray local Firestore emulator enables it); CI runs emulator tests separately. - 32 locales translated. CodeRabbit: 2 minor findings fixed. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Gp5fBmsmWJxgkEHb4JfhXR --------- Co-authored-by: Claude Opus 5.5 --- backend/api/routes/tenant_theme.py | 22 ++- backend/services/tenant_theme_service.py | 104 ++++++++++- backend/services/theme_preview_service.py | 164 ++++++++++++++++- backend/tests/test_tenant_theme_route.py | 30 +++ backend/tests/test_tenant_theme_service.py | 115 ++++++++++++ backend/tests/test_theme_preview_service.py | 126 +++++++++++++ .../tenant-theme/TenantThemeEditorDialog.tsx | 172 ++++++++++++++++-- .../__tests__/TenantThemeEditorCdg.test.tsx | 168 +++++++++++++++++ frontend/lib/api.ts | 16 +- frontend/messages/ar.json | 36 +++- frontend/messages/ca.json | 36 +++- frontend/messages/cs.json | 36 +++- frontend/messages/da.json | 36 +++- frontend/messages/de.json | 36 +++- frontend/messages/el.json | 36 +++- frontend/messages/en.json | 34 +++- frontend/messages/es.json | 36 +++- frontend/messages/fi.json | 36 +++- frontend/messages/fr.json | 36 +++- frontend/messages/he.json | 36 +++- frontend/messages/hi.json | 36 +++- frontend/messages/hr.json | 36 +++- frontend/messages/hu.json | 36 +++- frontend/messages/id.json | 36 +++- frontend/messages/it.json | 36 +++- frontend/messages/ja.json | 36 +++- frontend/messages/ko.json | 36 +++- frontend/messages/ms.json | 36 +++- frontend/messages/nb.json | 36 +++- frontend/messages/nl.json | 36 +++- frontend/messages/pl.json | 36 +++- frontend/messages/pt.json | 36 +++- frontend/messages/ro.json | 36 +++- frontend/messages/ru.json | 36 +++- frontend/messages/sk.json | 36 +++- frontend/messages/sv.json | 36 +++- frontend/messages/th.json | 36 +++- frontend/messages/tl.json | 36 +++- frontend/messages/tr.json | 36 +++- frontend/messages/uk.json | 36 +++- frontend/messages/vi.json | 36 +++- frontend/messages/zh.json | 36 +++- .../lyrics_transcriber/output/cdg_decoder.py | 100 ++++++++++ pyproject.toml | 2 +- .../output/test_cdg_title_card.py | 35 +--- tests/unit/test_render_video_worker_gce.py | 9 + 46 files changed, 2118 insertions(+), 131 deletions(-) create mode 100644 frontend/components/tenant-theme/__tests__/TenantThemeEditorCdg.test.tsx create mode 100644 karaoke_gen/lyrics_transcriber/output/cdg_decoder.py diff --git a/backend/api/routes/tenant_theme.py b/backend/api/routes/tenant_theme.py index dc232a6b..8eb4bc7a 100644 --- a/backend/api/routes/tenant_theme.py +++ b/backend/api/routes/tenant_theme.py @@ -12,7 +12,7 @@ import logging from concurrent.futures import ThreadPoolExecutor from typing import Any, Dict, List, Optional -from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile +from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile from fastapi.concurrency import run_in_threadpool from pydantic import BaseModel, Field, constr @@ -73,6 +73,8 @@ class ThemeResponse(BaseModel): style_params: Dict[str, Any] images: List[str] fonts: List[str] + # The images that fit the 300x216 CD+G screen (offered on the CD+G tab). + cdg_images: List[str] = Field(default_factory=list) class PreviewSample(BaseModel): @@ -84,6 +86,8 @@ class PreviewSample(BaseModel): class PreviewRequest(BaseModel): style_params: Dict[str, Any] sample: PreviewSample = Field(default_factory=PreviewSample) + # Also render the CD+G up card + a lyrics page (slower; the editor asks on its CD+G tab). + include_cdg: bool = False class PreviewResponse(BaseModel): @@ -91,6 +95,9 @@ class PreviewResponse(BaseModel): title_card: Optional[str] = None karaoke_frame: str end_screen: Optional[str] = None + # data:image/png;base64,... — only when include_cdg was requested. + cdg_title_card: Optional[str] = None + cdg_lyrics: Optional[str] = None class SaveRequest(BaseModel): @@ -110,7 +117,13 @@ def get_theme(config: TenantConfig = Depends(require_tenant_member)): @router.post("/assets", response_model=AssetResponse) -async def upload_asset(file: UploadFile = File(...), config: TenantConfig = Depends(require_tenant_member)): +async def upload_asset( + file: UploadFile = File(...), + purpose: Optional[str] = Form(None), + config: TenantConfig = Depends(require_tenant_member), +): + if purpose not in (None, "", "cdg"): + raise HTTPException(status_code=400, detail="Unknown upload purpose.") # Read in chunks and stop as soon as the limit is exceeded, so an oversized # upload never gets materialised in memory in full. chunks, size = [], 0 @@ -126,7 +139,9 @@ async def upload_asset(file: UploadFile = File(...), config: TenantConfig = Depe if not data: raise HTTPException(status_code=400, detail="The file is empty.") try: - name = await run_in_threadpool(store_uploaded_asset, config, file.filename or "asset", data) + name = await run_in_threadpool( + lambda: store_uploaded_asset(config, file.filename or "asset", data, purpose=purpose or None) + ) except TenantValidationError as exc: _raise_http(exc) return AssetResponse(name=name) @@ -149,6 +164,7 @@ async def preview_theme(body: PreviewRequest, config: TenantConfig = Depends(req artist=body.sample.artist, title=body.sample.title, lyrics=body.sample.lyrics, + include_cdg=body.include_cdg, ), ) # The slot is released only when the render really finishes — a timed-out diff --git a/backend/services/tenant_theme_service.py b/backend/services/tenant_theme_service.py index be2381bd..9b3d955d 100644 --- a/backend/services/tenant_theme_service.py +++ b/backend/services/tenant_theme_service.py @@ -87,6 +87,15 @@ NUMERIC_BOUNDS = { ("karaoke", "max_line_length"): (10, 80), ("karaoke", "outline"): (0, 20), ("karaoke", "shadow"): (0, 20), + ("cdg", "font_size"): (8, 40), + ("cdg", "stroke_width"): (0, 4), + ("cdg", "title_font_size"): (8, 60), + ("cdg", "artist_font_size"): (8, 60), + ("cdg", "title_separator_font_size"): (6, 40), + ("cdg", "title_block_top"): (0, 180), + ("cdg", "title_max_height"): (30, 216), + ("cdg", "title_artist_gap"): (0, 80), + ("cdg", "outro_line1_line2_gap"): (0, 80), ("intro", "video_duration"): (1, 30), ("end", "video_duration"): (1, 30), } @@ -98,6 +107,21 @@ HEX_COLOR_FIELDS = ( ("end", "background_color"), ("end", "title_color"), ("end", "artist_color"), ("end", "extra_text_color"), ("karaoke", "background_color"), ) +# CD+G colours are plain hex; the screen is 300x216 with a 16-colour palette. +CDG_HEX_COLOR_FIELDS = tuple( + ("cdg", f) for f in ( + "background_color", "border_color", "title_color", "artist_color", "title_separator_color", + "active_fill", "active_stroke", "inactive_fill", "inactive_stroke", "instrumental_font_color", + "outro_line1_color", "outro_line2_color", + ) +) +CDG_TEXT_FIELDS = { # field: max length (rendered on the 300px-wide CDG screen) + "title_separator_text": 40, + "instrumental_text": 40, + "outro_text_line1": 80, + "outro_text_line2": 80, +} +CDG_IMAGE_SIZE = (300, 216) RGBA_COLOR_FIELDS = ( ("karaoke", "primary_color"), ("karaoke", "secondary_color"), ("karaoke", "outline_color"), ("karaoke", "back_color"), @@ -218,7 +242,7 @@ def sanitize_style_params( if isinstance(value, bool) or not isinstance(value, (int, float)) or not lo <= value <= hi: raise TenantValidationError(f"{section}.{field} must be a number between {lo} and {hi}.") - for section, field in HEX_COLOR_FIELDS: + for section, field in HEX_COLOR_FIELDS + CDG_HEX_COLOR_FIELDS: value = styles[section].get(field) if value is not None and not _HEX.match(str(value)): raise TenantValidationError(f"{section}.{field} must be a colour like #ff5bb8.") @@ -230,9 +254,54 @@ def sanitize_style_params( for section, field in REGION_FIELDS: _check_region(styles[section].get(field), f"{section}.{field}") + for field, max_len in CDG_TEXT_FIELDS.items(): + value = styles["cdg"].get(field) + if value is None: + continue + if not isinstance(value, str) or len(value) > max_len or any(c in value for c in "\r\n"): + raise TenantValidationError(f"cdg.{field} must be a single line of up to {max_len} characters.") + return styles, font +def check_cdg_image_sizes(styles: Dict, theme_id: str, storage: StorageService) -> None: + """CD+G backgrounds aren't resized by the CDG renderer: they must be 300x216.""" + from PIL import Image + + from backend.services.theme_preview_service import CDG_IMAGE_FIELDS + + for section, field in CDG_IMAGE_FIELDS: + name = (styles.get(section) or {}).get(field) + if not name: + continue + try: + data = storage.download_bytes(f"{THEMES_PREFIX}/{theme_id}/assets/{name}") + with Image.open(io.BytesIO(data)) as img: + size = img.size + except Exception as exc: + raise TenantValidationError(f"CD+G image '{name}' couldn't be read.") from exc + if size != CDG_IMAGE_SIZE: + raise TenantValidationError( + f"CD+G image '{name}' is {size[0]}x{size[1]}; CD+G screens must be exactly 300x216 pixels. " + "Upload it from the CD+G tab and it will be fitted automatically." + ) + + +def fit_cdg_image(data: bytes) -> bytes: + """Fit an uploaded image to the 300x216 CD+G screen (letterboxed on black) as PNG.""" + from PIL import Image, ImageOps + + with Image.open(io.BytesIO(data)) as img: + img = img.convert("RGB") + if img.size == CDG_IMAGE_SIZE: + fitted = img + else: + fitted = ImageOps.pad(img, CDG_IMAGE_SIZE, method=Image.LANCZOS, color=(0, 0, 0)) + buf = io.BytesIO() + fitted.save(buf, "PNG") + return buf.getvalue() + + def _font_local_path(storage: StorageService, theme_id: str, font: str, workdir: str) -> str: blob_path = f"{THEMES_PREFIX}/{theme_id}/assets/{font}" if storage.file_exists(blob_path): @@ -271,13 +340,34 @@ def get_theme_for_editor(config, storage: Optional[StorageService] = None) -> Di assets = _theme_assets(storage, theme_id) fonts = sorted(set(bundled_fonts()) | {a for a in assets if a.lower().endswith((".ttf", ".otf"))}) images = [a for a in assets if a.rsplit(".", 1)[-1].lower() in IMAGE_CONTENT_TYPES] - return {"theme_id": theme_id, "style_params": style_params, "images": images, "fonts": fonts} + return { + "theme_id": theme_id, "style_params": style_params, "images": images, "fonts": fonts, + "cdg_images": [name for name in images if _is_cdg_sized(storage, theme_id, name)], + } + + +def _is_cdg_sized(storage: StorageService, theme_id: str, name: str) -> bool: + """True if the image is exactly 300x216 (reads only the file header).""" + from PIL import Image + + try: + blob = storage.bucket.get_blob(f"{THEMES_PREFIX}/{theme_id}/assets/{name}") + if blob is None: + return False + head = blob.download_as_bytes(start=0, end=64 * 1024 - 1) + with Image.open(io.BytesIO(head)) as img: + return img.size == CDG_IMAGE_SIZE + except Exception: # noqa: BLE001 - unreadable header = not offered for CD+G + return False def store_uploaded_asset( - config, filename: str, data: bytes, storage: Optional[StorageService] = None + config, filename: str, data: bytes, storage: Optional[StorageService] = None, *, purpose: Optional[str] = None ) -> str: - """Store an uploaded image/font content-addressed; return its basename.""" + """Store an uploaded image/font content-addressed; return its basename. + + ``purpose="cdg"``: an image is fitted to the 300x216 CD+G screen and stored as PNG. + """ storage = storage or StorageService() ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "" if ext not in UPLOAD_EXTENSIONS: @@ -303,6 +393,10 @@ def store_uploaded_asset( raise TenantValidationError( f"That image is too large ({width}x{height}). Use up to {MAX_IMAGE_SIDE}x{MAX_IMAGE_SIDE} pixels." ) + if purpose == "cdg": + data = fit_cdg_image(data) + ext = "png" + filename = f"{filename.rsplit('.', 1)[0]}-cdg.png" stem = _safe_asset_name(filename).rsplit(".", 1)[0][:60] or "asset" digest = hashlib.sha256(data).hexdigest()[:8] @@ -322,6 +416,7 @@ def prepare_preview_styles(config, style_params: object, storage: Optional[Stora storage = storage or StorageService() theme_id = _editable_theme_id(config) styles, _font = sanitize_style_params(style_params, available_assets=_theme_assets(storage, theme_id)) + check_cdg_image_sizes(styles, theme_id, storage) return styles @@ -330,6 +425,7 @@ def save_tenant_theme(config, style_params: object, storage: Optional[StorageSer storage = storage or StorageService() theme_id = _editable_theme_id(config) styles, font = sanitize_style_params(style_params, available_assets=_theme_assets(storage, theme_id)) + check_cdg_image_sizes(styles, theme_id, storage) assets: Dict[str, Tuple[bytes, str]] = {} with tempfile.TemporaryDirectory() as workdir: diff --git a/backend/services/theme_preview_service.py b/backend/services/theme_preview_service.py index 6f152dfe..91b2fb7f 100644 --- a/backend/services/theme_preview_service.py +++ b/backend/services/theme_preview_service.py @@ -14,9 +14,15 @@ uses, fed the draft ``style_params`` exactly the way a render job would see them filter + background handling as ``lyrics_transcriber.output.video.VideoGenerator``, at a moment when the second line is part-way sung (sung = primary colour). +- **CD+G** (on request): the real ``CDGGenerator`` composes a short CDG from the + theme's ``cdg`` section and sample lyrics; ``cdg_decoder`` renders the up card and a + lyrics page from the packets (300x216, shown upscaled with hard pixels). + Theme assets are resolved like ``style_loader.update_asset_paths``: background images per section, and the single ``font`` asset (``intro.font``) applied to -intro.font / karaoke.font_path / end.font / cdg.font_path. +intro.font / karaoke.font_path / end.font / cdg.font_path (+ cdg.title_font_path) — +except a distinct CDG lyrics font (``cdg.font_path``), which the render pipeline ships +as its own ``cdg_font`` asset. """ import base64 @@ -93,13 +99,19 @@ class PreviewImages: title_card: Optional[bytes] karaoke_frame: bytes end_screen: Optional[bytes] = None + # PNGs (CD+G frames, upscaled with hard pixels). Only rendered on request. + cdg_title_card: Optional[bytes] = None + cdg_lyrics: Optional[bytes] = None def as_data_urls(self) -> Dict[str, Optional[str]]: enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() if b else None # noqa: E731 + png = lambda b: "data:image/png;base64," + base64.b64encode(b).decode() if b else None # noqa: E731 return { "title_card": enc(self.title_card), "karaoke_frame": enc(self.karaoke_frame), "end_screen": enc(self.end_screen), + "cdg_title_card": png(self.cdg_title_card), + "cdg_lyrics": png(self.cdg_lyrics), } @@ -108,6 +120,9 @@ class PreviewImages: # --------------------------------------------------------------------------- _BG_FIELDS = (("intro", "background_image"), ("karaoke", "background_image"), ("end", "background_image")) +CDG_IMAGE_FIELDS = ( + ("cdg", "title_screen_background"), ("cdg", "outro_background"), ("cdg", "instrumental_background"), +) _FONT_TARGETS = (("intro", "font"), ("karaoke", "font_path"), ("end", "font"), ("cdg", "font_path")) _download_lock = threading.Lock() @@ -172,8 +187,16 @@ def _local_theme_asset(storage: StorageService, theme_id: str, basename: str) -> return local +def _resolve_font(storage: StorageService, theme_id: str, font: str) -> Optional[str]: + base = os.path.basename(font) + local = _local_theme_asset(storage, theme_id, base) + if not local and base in bundled_fonts(): + local = os.path.join(BUNDLED_FONTS_DIR, base) + return local + + def resolve_assets( - style_params: Dict, theme_id: str, storage: Optional[StorageService] = None + style_params: Dict, theme_id: str, storage: Optional[StorageService] = None, *, include_cdg: bool = False ) -> Dict: """Return a deep copy of style_params with asset basenames replaced by local paths. @@ -193,17 +216,33 @@ def resolve_assets( raise ThemePreviewError(f"Background image '{value}' ({section}) was not found in the theme's assets.") styles[section][field] = local + if include_cdg and isinstance(styles.get("cdg"), dict): + for section, field in CDG_IMAGE_FIELDS: + value = styles["cdg"].get(field) + if not value: + continue + local = _local_theme_asset(storage, theme_id, os.path.basename(value)) + if not local: + raise ThemePreviewError(f"CD+G image '{value}' was not found in the theme's assets.") + styles["cdg"][field] = local + + # A distinct CDG lyrics font travels as its own "cdg_font" asset in real renders. + cdg_font = (styles.get("cdg") or {}).get("font_path") if isinstance(styles.get("cdg"), dict) else None font = (styles.get("intro") or {}).get("font") if font: - base = os.path.basename(font) - local = _local_theme_asset(storage, theme_id, base) - if not local and base in bundled_fonts(): - local = os.path.join(BUNDLED_FONTS_DIR, base) + local = _resolve_font(storage, theme_id, font) if not local: raise ThemePreviewError(f"Font '{font}' was not found in the theme's assets.") for section, field in _FONT_TARGETS: if isinstance(styles.get(section), dict): styles[section][field] = local + if isinstance(styles.get("cdg"), dict): + styles["cdg"]["title_font_path"] = local + if include_cdg and cdg_font and os.path.basename(cdg_font) != os.path.basename(font): + cdg_local = _resolve_font(storage, theme_id, cdg_font) + if not cdg_local: + raise ThemePreviewError(f"CD+G font '{cdg_font}' was not found in the theme's assets.") + styles["cdg"]["font_path"] = cdg_local # libass selects by family name — same value save_tenant_theme persists. if isinstance(styles.get("karaoke"), dict): try: @@ -412,6 +451,112 @@ def render_karaoke_frame( return _to_jpeg(out_png) +CDG_COLOR_LIMIT = 300 * 216 +CDG_PREVIEW_SCALE = 3 # 300x216 -> 900x648, nearest-neighbour (keeps the pixel look) +CDG_TIMEOUT_S = 60 + + +def _cdg_png(frame: Image.Image) -> bytes: + big = frame.resize((frame.width * CDG_PREVIEW_SCALE, frame.height * CDG_PREVIEW_SCALE), Image.NEAREST) + buf = io.BytesIO() + big.save(buf, "PNG", optimize=True) + return buf.getvalue() + + +def _lrc_timestamp(seconds: float) -> str: + minutes, secs = divmod(seconds, 60) + return f"[{int(minutes):02d}:{secs:06.3f}]" + + +def _pick_lyrics_frame(frames: List[Image.Image], cdg_styles: Dict) -> Image.Image: + """The first frame showing both sung and unsung lyrics (else the busiest one).""" + from karaoke_gen.lyrics_transcriber.output.cdg_decoder import cdg_color + + try: + sung = cdg_color(cdg_styles.get("active_fill") or "#000000") + unsung = cdg_color(cdg_styles.get("inactive_fill") or "#000000") + except (ValueError, TypeError): + sung = unsung = None + best, best_score = frames[-1], -1 + for frame in frames: + counts = {rgb: n for n, rgb in (frame.getcolors(CDG_COLOR_LIMIT) or [])} + if sung and unsung and sung != unsung: + s, u = counts.get(sung, 0), counts.get(unsung, 0) + if s > 150 and u > 150: + return frame + background = _dominant(counts) + lit = sum(n for rgb, n in counts.items() if rgb != background) + if lit > best_score: + best, best_score = frame, lit + return best + + +def _dominant(counts: Dict) -> tuple: + return max(counts, key=counts.get) if counts else (0, 0, 0) + + +def render_cdg_previews( + styles: Dict, artist: str, title: str, lines: List[str], workdir: str +) -> Tuple[bytes, bytes]: + """(up card, lyrics page) PNGs from a real CDG composed with the theme's cdg styles.""" + from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator + from karaoke_gen.lyrics_transcriber.output.cdg_decoder import decode_cdg_frames + + cdg_styles = dict(styles.get("cdg") or {}) + if not cdg_styles.get("font_path"): + raise ThemePreviewError("CD+G styles need a font.") + + intro = float(cdg_styles.get("intro_duration_seconds") or 5.0) + buffer = float(cdg_styles.get("first_syllable_buffer_seconds") or 0.0) + start = intro + buffer + 1.0 # first sung syllable, after the up card + line_gap = 2.0 + + lrc_lines = [] + for i, line in enumerate(lines): + t = start + i * line_gap + words = line.upper().split() + step = (line_gap * 0.8) / max(len(words), 1) + for j, word in enumerate(words): + prefix = "/" if j == 0 else "" + lrc_lines.append(f"{_lrc_timestamp(t + j * step)}1:{prefix}{word} ") + lrc = os.path.join(workdir, "preview.lrc") + with open(lrc, "w", encoding="utf-8") as fh: + fh.write("\n".join(lrc_lines) + "\n") + + audio = os.path.join(workdir, "silence.mp3") + duration = start + len(lines) * line_gap + 2.0 + try: + result = subprocess.run( + ["ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo", + "-t", f"{duration:.1f}", "-q:a", "9", audio], + capture_output=True, text=True, timeout=FFMPEG_TIMEOUT_S, + ) + except subprocess.TimeoutExpired as exc: + raise ThemePreviewError("CD+G preview audio timed out.") from exc + if result.returncode != 0: + raise ThemePreviewError(f"CD+G preview audio failed: {result.stderr.strip()[:200]}") + + out_dir = os.path.join(workdir, "cdg") + os.makedirs(out_dir, exist_ok=True) + try: + cdg_file, _mp3, _zip = CDGGenerator(output_dir=out_dir, logger=logger).generate_cdg_from_lrc( + lrc, audio, title, artist, cdg_styles + ) + except Exception as exc: + raise ThemePreviewError(f"CD+G preview failed: {exc}") from exc + + with open(cdg_file, "rb") as fh: + data = fh.read() + # The up card is fully drawn well before the intro ends. The lyrics page is the + # frame part-way through the first line (sung + unsung colours both visible); + # the composer offsets lyrics by the intro and lead-in, so search for it. + candidates = [start + intro + i * 0.25 for i in range(int(line_gap * 2 * 4))] + frames = decode_cdg_frames(data, [max(intro - 0.5, 1.0)] + candidates) + title_card, lyric_frames = frames[0], frames[1:] + lyrics = _pick_lyrics_frame(lyric_frames, cdg_styles) + return _cdg_png(title_card), _cdg_png(lyrics) + + # --------------------------------------------------------------------------- # Public entry point (+ small cache for identical drafts) # --------------------------------------------------------------------------- @@ -429,10 +574,11 @@ def render_theme_preview( title: str = "Song Title", lyrics: Optional[List[str]] = None, storage: Optional[StorageService] = None, + include_cdg: bool = False, ) -> PreviewImages: lines = [ln.strip() for ln in (lyrics or DEFAULT_SAMPLE_LYRICS) if ln and ln.strip()][:4] or DEFAULT_SAMPLE_LYRICS key = hashlib.sha256( - repr((theme_id, sorted_repr(style_params), artist, title, lines)).encode() + repr((theme_id, sorted_repr(style_params), artist, title, lines, include_cdg)).encode() ).hexdigest() with _cache_lock: if key in _CACHE: @@ -441,13 +587,15 @@ def render_theme_preview( from karaoke_gen.style_loader import screen_enabled - styles = resolve_assets(style_params, theme_id, storage) + styles = resolve_assets(style_params, theme_id, storage, include_cdg=include_cdg) with tempfile.TemporaryDirectory(prefix="theme-preview-") as workdir: result = PreviewImages( title_card=render_title_card(styles, artist, title, workdir) if screen_enabled(styles, "intro") else None, karaoke_frame=render_karaoke_frame(styles, lines, workdir), end_screen=render_end_screen(styles, artist, title, workdir) if screen_enabled(styles, "end") else None, ) + if include_cdg: + result.cdg_title_card, result.cdg_lyrics = render_cdg_previews(styles, artist, title, lines, workdir) with _cache_lock: _CACHE[key] = result while len(_CACHE) > _CACHE_MAX: diff --git a/backend/tests/test_tenant_theme_route.py b/backend/tests/test_tenant_theme_route.py index e937384c..c7f67a42 100644 --- a/backend/tests/test_tenant_theme_route.py +++ b/backend/tests/test_tenant_theme_route.py @@ -194,3 +194,33 @@ def test_timed_out_render_keeps_its_slot_until_it_finishes(client_for, monkeypat break time.sleep(0.02) assert tenant_theme._PREVIEW_SEMAPHORE._value == free_before + + +def test_preview_cdg_frames_only_when_asked(client_for): + images = PreviewImages(b"t", b"k", None, cdg_title_card=b"c", cdg_lyrics=b"l") + with patch.object(tenant_theme, "prepare_preview_styles", return_value={"cdg": {}}), \ + patch.object(tenant_theme, "render_theme_preview", return_value=images) as render: + resp = client_for().post("/api/tenant/theme/preview", json={"style_params": {"cdg": {}}, "include_cdg": True}) + assert resp.status_code == 200 + body = resp.json() + assert body["cdg_title_card"].startswith("data:image/png;base64,") + assert body["cdg_lyrics"].startswith("data:image/png;base64,") + assert render.call_args.kwargs["include_cdg"] is True + + with patch.object(tenant_theme, "prepare_preview_styles", return_value={}), \ + patch.object(tenant_theme, "render_theme_preview", return_value=PreviewImages(b"t", b"k")) as render: + resp = client_for().post("/api/tenant/theme/preview", json={"style_params": {}}) + assert render.call_args.kwargs["include_cdg"] is False + assert resp.json()["cdg_lyrics"] is None + + +def test_cdg_upload_purpose_is_passed_through_and_validated(client_for): + client = client_for() + with patch.object(tenant_theme, "store_uploaded_asset", return_value="card-cdg-1234abcd.png") as store: + resp = client.post("/api/tenant/theme/assets", files={"file": ("card.jpg", b"jpg")}, data={"purpose": "cdg"}) + assert resp.status_code == 200 + assert store.call_args.kwargs["purpose"] == "cdg" + with patch.object(tenant_theme, "store_uploaded_asset") as store: + resp = client.post("/api/tenant/theme/assets", files={"file": ("x.png", b"png")}, data={"purpose": "evil"}) + assert resp.status_code == 400 + store.assert_not_called() diff --git a/backend/tests/test_tenant_theme_service.py b/backend/tests/test_tenant_theme_service.py index 188cc34b..807630ef 100644 --- a/backend/tests/test_tenant_theme_service.py +++ b/backend/tests/test_tenant_theme_service.py @@ -123,6 +123,9 @@ class FakeStorage: def download_json(self, path): return json.loads(self.blobs[path]) + def download_bytes(self, path): + return self.blobs[path] + def download_file(self, path, local): with open(local, "wb") as fh: fh.write(self.blobs[path]) @@ -315,3 +318,115 @@ def test_sanitize_replaces_unsafe_or_unknown_cdg_font_with_main_font(bad): style["cdg"]["font_path"] = bad styles, _ = tts.sanitize_style_params(style, available_assets=ASSETS) assert styles["cdg"]["font_path"] == "AvenirNext-Bold.ttf" + + +# --- CD+G styles ---------------------------------------------------------------- + + +def _image_bytes(size, fmt="PNG", color="blue"): + buf = io.BytesIO() + Image.new("RGB", size, color).save(buf, fmt) + return buf.getvalue() + + +def _cdg_style(**cdg): + style = _style() + style["cdg"] = { + "font_path": "Oswald-SemiBold.ttf", "font_size": 18, "title_color": "#ffff00", "artist_color": "#ffff00", + "active_fill": "#006CF9", "inactive_fill": "#ffff00", "title_separator_text": "MADE FAMOUS BY", + "title_block_top": 56, **cdg, + } + return style + + +def test_sanitize_accepts_cdg_settings(): + styles, _ = tts.sanitize_style_params(_cdg_style(), available_assets=ASSETS) + assert styles["cdg"]["title_separator_text"] == "MADE FAMOUS BY" + assert styles["cdg"]["active_fill"] == "#006CF9" + + +@pytest.mark.parametrize( + "field, value", + [ + ("active_fill", "blue"), + ("title_color", "#ff00"), + ("border_color", "rgb(0,0,0)"), + ("font_size", 200), + ("title_block_top", -1), + ("title_font_size", "28"), + ("stroke_width", 9), + ("title_separator_text", "X" * 41), + ("title_separator_text", "two\nlines"), + ("outro_text_line1", 5), + ], +) +def test_sanitize_rejects_bad_cdg_values(field, value): + with pytest.raises(TenantValidationError): + tts.sanitize_style_params(_cdg_style(**{field: value}), available_assets=ASSETS) + + +def test_sanitize_rejects_unuploaded_cdg_background(): + with pytest.raises(TenantValidationError, match="hasn't been uploaded"): + tts.sanitize_style_params(_cdg_style(title_screen_background="logo.png"), available_assets=ASSETS) + + +def test_fit_cdg_image_letterboxes_to_the_cdg_screen(): + fitted = Image.open(io.BytesIO(tts.fit_cdg_image(_image_bytes((1920, 1080), "JPEG")))) + assert fitted.size == (300, 216) and fitted.format == "PNG" + # 16:9 into 300x216 leaves black bars top and bottom + assert fitted.getpixel((150, 2)) == (0, 0, 0) + assert fitted.getpixel((150, 108))[2] > 200 + + +def test_cdg_upload_is_fitted_and_stored_as_png(): + storage = FakeStorage() + name = tts.store_uploaded_asset(_config(), "Logo Card.jpg", _image_bytes((900, 648), "JPEG"), storage=storage, purpose="cdg") + assert name.startswith("Logo_Card-cdg-") and name.endswith(".png") + stored = Image.open(io.BytesIO(storage.blobs[f"themes/randy-vild/assets/{name}"])) + assert stored.size == (300, 216) + + +def test_ordinary_upload_is_not_resized(): + storage = FakeStorage() + name = tts.store_uploaded_asset(_config(), "bg.png", _image_bytes((900, 648)), storage=storage) + assert Image.open(io.BytesIO(storage.blobs[f"themes/randy-vild/assets/{name}"])).size == (900, 648) + + +def test_save_rejects_cdg_background_of_the_wrong_size(monkeypatch): + storage = FakeStorage() + storage.blobs["themes/randy-vild/assets/big.png"] = _image_bytes((640, 480)) + monkeypatch.setattr(tts, "update_tenant", lambda tenant_id, **kw: None) + with pytest.raises(TenantValidationError, match="300x216"): + tts.save_tenant_theme(_config(), _cdg_style(title_screen_background="big.png"), storage=storage) + + +def test_save_accepts_cdg_background_of_the_right_size(monkeypatch): + storage = FakeStorage() + storage.blobs["themes/randy-vild/assets/card.png"] = _image_bytes((300, 216)) + calls = {} + monkeypatch.setattr(tts, "update_tenant", lambda tenant_id, **kw: calls.update(kw)) + tts.save_tenant_theme(_config(), _cdg_style(title_screen_background="card.png", outro_background="card.png"), storage=storage) + assert calls["style_params"]["cdg"]["title_screen_background"] == "card.png" + + + +def test_editor_lists_only_300x216_images_for_cdg(): + storage = FakeStorage() + storage.blobs["themes/randy-vild/assets/card.png"] = _image_bytes((300, 216)) + storage.blobs["themes/randy-vild/assets/big.png"] = _image_bytes((1920, 1080)) + + class _Blob: + def __init__(self, data): + self.data = data + + def download_as_bytes(self, start=0, end=None): + return self.data[start:(end + 1) if end is not None else None] + + class _Bucket: + def get_blob(self, path): + return _Blob(storage.blobs[path]) if path in storage.blobs else None + + storage.bucket = _Bucket() + data = tts.get_theme_for_editor(_config(), storage=storage) + assert "big.png" in data["images"] and "card.png" in data["images"] + assert data["cdg_images"] == ["card.png"] # bg.jpg isn't a real image here, big.png is 1920x1080 diff --git a/backend/tests/test_theme_preview_service.py b/backend/tests/test_theme_preview_service.py index 506c4614..e73ed9ed 100644 --- a/backend/tests/test_theme_preview_service.py +++ b/backend/tests/test_theme_preview_service.py @@ -195,3 +195,129 @@ def test_omitted_screens_are_not_rendered(): assert _img(result.karaoke_frame).size == (1280, 720) urls = result.as_data_urls() assert urls["title_card"] is None and urls["end_screen"] is None + + +# --- CD+G previews ---------------------------------------------------------------- + +CDG_YELLOW, CDG_BLUE, CDG_WHITE = (255, 255, 0), (0, 102, 255), (255, 255, 255) + + +def _cdg_section(**overrides): + cdg = { + "title_color": "#ffff00", "artist_color": "#ffff00", "background_color": "#000000", + "border_color": "#000000", "font_path": "Oswald-SemiBold.ttf", "font_size": 18, + "stroke_width": 0, "stroke_style": "octagon", "active_fill": "#006CF9", "active_stroke": "#000000", + "inactive_fill": "#ffff00", "inactive_stroke": "#000000", "title_screen_background": "card.png", + "instrumental_background": "card.png", "instrumental_transition": "wipein", + "instrumental_font_color": "#ffff00", "title_screen_transition": "wipein", "row": 4, + "line_tile_height": 3, "lines_per_page": 4, "clear_mode": "eager", "sync_offset": 0, + "instrumental_gap_threshold": 99999, "instrumental_text": "INSTRUMENTAL", + "lead_in_threshold": 99999, "lead_in_symbols": [">"], "lead_in_duration": 30, "lead_in_total": 200, + "title_artist_gap": 8, "title_top_padding": 0, "intro_duration_seconds": 5.0, + "first_syllable_buffer_seconds": 0.5, "outro_background": "card.png", "outro_transition": "wipein", + "outro_text_line1": "$title", "outro_text_line2": "$artist", "outro_line1_color": "#ffff00", + "outro_line2_color": "#ffff00", "outro_line1_line2_gap": 10, + "title_separator_text": "MADE FAMOUS BY", "title_separator_color": "#ffffff", + } + cdg.update(overrides) + return cdg + + +class _CdgAssets: + """Storage whose theme holds one 300x216 black CD+G card (other assets absent).""" + + def __init__(self, tmp_path): + card = tmp_path / "card.png" + Image.new("RGB", (300, 216), (0, 0, 0)).save(card) + self._card = str(card) + outer = self + + class _Blob: + generation = 1 + + def download_to_filename(self, path): + shutil.copy(outer._card, path) + + class _Bucket: + def get_blob(self, path): + return _Blob() if path.endswith("/card.png") else None + + self.bucket = _Bucket() + + +@pytest.fixture +def cdg_cache(tmp_path, monkeypatch): + monkeypatch.setattr(tps, "ASSET_CACHE_ROOT", str(tmp_path / "assets")) + tps._CACHE.clear() + return _CdgAssets(tmp_path) + + +def _colours(img): + return {rgb for n, rgb in img.getcolors(300 * 216 * 9) if n > 40} + + +def test_cdg_previews_only_when_requested(cdg_cache): + theme = _theme() + theme["cdg"] = _cdg_section() + result = tps.render_theme_preview("t1", theme, storage=cdg_cache) + assert result.cdg_title_card is None and result.cdg_lyrics is None + + +def test_cdg_up_card_and_lyrics_page_render_from_the_real_cdg(cdg_cache): + theme = _theme() + theme["cdg"] = _cdg_section() + result = tps.render_theme_preview( + "t1", theme, artist="Lady Gaga", title="Abracadabra", storage=cdg_cache, include_cdg=True + ) + card, lyrics = _img(result.cdg_title_card), _img(result.cdg_lyrics) + assert card.size == lyrics.size == (900, 648) # 300x216 at 3x, hard pixels + assert {CDG_YELLOW, CDG_WHITE} <= _colours(card) # title/artist + "MADE FAMOUS BY" + assert {CDG_YELLOW, CDG_BLUE} <= _colours(lyrics) # part-sung first line + urls = result.as_data_urls() + assert urls["cdg_title_card"].startswith("data:image/png;base64,") + + +def test_cdg_colour_changes_show_in_the_preview(cdg_cache): + theme = _theme() + theme["cdg"] = _cdg_section(active_fill="#ff0000") + lyrics = _img(tps.render_theme_preview("t1", theme, storage=cdg_cache, include_cdg=True).cdg_lyrics) + assert (255, 0, 0) in _colours(lyrics) and CDG_BLUE not in _colours(lyrics) + + +def test_resolve_assets_keeps_a_distinct_cdg_font_and_titles_use_the_main_font(cdg_cache): + theme = _theme() + theme["cdg"] = _cdg_section() + styles = tps.resolve_assets(theme, "t1", cdg_cache, include_cdg=True) + assert styles["cdg"]["font_path"].endswith("Oswald-SemiBold.ttf") + assert styles["cdg"]["title_font_path"].endswith("AvenirNext-Bold.ttf") + assert styles["cdg"]["title_screen_background"].endswith("card.png") + + +def test_missing_cdg_background_is_a_preview_error(cdg_cache): + theme = _theme() + theme["cdg"] = _cdg_section(title_screen_background="missing.png") + with pytest.raises(tps.ThemePreviewError, match="missing.png"): + tps.render_theme_preview("t1", theme, storage=cdg_cache, include_cdg=True) + # ... but the other previews don't need CD+G assets + tps.render_theme_preview("t1", theme, storage=cdg_cache) + + +def test_pick_lyrics_frame_falls_back_to_the_busiest_frame(): + blank = Image.new("RGB", (300, 216), (0, 0, 0)) + busy = blank.copy() + busy.paste((255, 255, 0), (10, 10, 200, 40)) + assert tps._pick_lyrics_frame([blank, busy, blank], {"active_fill": "#006CF9", "inactive_fill": "#ffff00"}) is busy + + + +def test_cdg_audio_timeout_is_a_preview_error(cdg_cache, monkeypatch): + import subprocess + + def boom(*a, **k): + raise subprocess.TimeoutExpired(cmd="ffmpeg", timeout=1) + + monkeypatch.setattr(tps.subprocess, "run", boom) + theme = _theme() + theme["cdg"] = _cdg_section() + with pytest.raises(tps.ThemePreviewError, match="timed out"): + tps.render_cdg_previews(tps.resolve_assets(theme, "t1", cdg_cache, include_cdg=True), "A", "T", ["la la"], str(cdg_cache._card).rsplit("/", 1)[0]) diff --git a/frontend/components/tenant-theme/TenantThemeEditorDialog.tsx b/frontend/components/tenant-theme/TenantThemeEditorDialog.tsx index c31086ed..55ee949a 100644 --- a/frontend/components/tenant-theme/TenantThemeEditorDialog.tsx +++ b/frontend/components/tenant-theme/TenantThemeEditorDialog.tsx @@ -31,7 +31,9 @@ interface Props { onClose: () => void } -type Tab = "titleCard" | "karaoke" | "endScreen" | "advanced" +type Tab = "titleCard" | "karaoke" | "endScreen" | "cdg" | "advanced" +// CD+G screens are 300x216. +const CDG_ASPECT = "300 / 216" // --- small field components --------------------------------------------------- @@ -83,7 +85,7 @@ function RangeInput({ id, label, value, min, max, step = 1, onChange }: { export function TenantThemeEditorDialog({ open, onClose }: Props) { const t = useTranslations("tenantTheme") const { toast } = useToast() - const { tenant } = useTenant() + const { tenant, features } = useTenant() const [loading, setLoading] = useState(false) const [loadError, setLoadError] = useState(null) @@ -91,6 +93,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { const [draft, setDraft] = useState(null) const [images, setImages] = useState([]) const [fonts, setFonts] = useState([]) + const [cdgImages, setCdgImages] = useState([]) const [tab, setTab] = useState("titleCard") const [jsonText, setJsonText] = useState("") const [jsonError, setJsonError] = useState(null) @@ -124,6 +127,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { setJsonText(JSON.stringify(data.style_params, null, 2)) setImages(data.images) setFonts(data.fonts) + setCdgImages(data.cdg_images ?? []) }) .catch((err: any) => !cancelled && setLoadError(err?.message || t("loadFailed"))) .finally(() => !cancelled && setLoading(false)) @@ -153,6 +157,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { draft, { artist: sampleArtist || undefined, title: sampleTitle || undefined }, controller.signal, + { includeCdg: tab === "cdg" }, ) if (!controller.signal.aborted) setPreview(result) } catch (err: any) { @@ -164,7 +169,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { } }, PREVIEW_DEBOUNCE_MS) return () => clearTimeout(handle) - }, [open, draft, sampleArtist, sampleTitle]) // eslint-disable-line react-hooks/exhaustive-deps + }, [open, draft, sampleArtist, sampleTitle, tab === "cdg"]) // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => () => abortRef.current?.abort(), []) @@ -201,12 +206,14 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { } } - const uploadAsset = async (file: File, apply: (name: string) => void, key: string) => { + const uploadAsset = async (file: File, apply: (name: string) => void, key: string, purpose?: "cdg") => { setUploading(key) try { - const { name } = await tenantThemeApi.uploadAsset(file) + const { name } = purpose ? await tenantThemeApi.uploadAsset(file, purpose) : await tenantThemeApi.uploadAsset(file) if (/\.(ttf|otf)$/i.test(name)) setFonts((f) => Array.from(new Set([...f, name])).sort()) else setImages((imgs) => Array.from(new Set([...imgs, name])).sort()) + // CD+G uploads are fitted to 300x216 by the server. + if (purpose === "cdg") setCdgImages((imgs) => Array.from(new Set([...imgs, name])).sort()) apply(name) } catch (err: any) { toast({ title: t("uploadFailed"), description: err?.message, variant: "destructive" }) @@ -229,6 +236,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { ) setImages(data.images) setFonts(data.fonts) + setCdgImages(data.cdg_images ?? []) setSaveResult({ refreshed: data.refreshed_jobs ?? 0, outdated: data.outdated_job_ids ?? [] }) setRerenderStarted(null) setOutdatedThemeJobs(data.outdated_job_ids ?? []) @@ -409,16 +417,73 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { /> ) - const tabs: Tab[] = ["titleCard", "karaoke", "endScreen", "advanced"] + // --- CD+G helpers (the cdg section's colours are plain hex) --------------------- + + const cdgColour = (field: string, label: string, fallback = "#ffffff") => ( + (draft!, "cdg", field) || fallback} + onChange={(v) => update("cdg", field, v)} /> + ) + + const cdgImageField = (field: string, label: string) => { + const image = getField(draft!, "cdg", field) || "" + const key = `cdg-${field}` + return ( +
+ + + +
+ ) + } + + const cdgRange = (field: string, label: string, min: number, max: number, fallback: number) => ( + (draft!, "cdg", field) ?? fallback} + onChange={(n) => update("cdg", field, n)} /> + ) + + const mainFont = getField(draft!, "intro", "font") || "" + const cdgFont = getField(draft!, "cdg", "font_path") || "" + const cdgOutline = getField(draft!, "cdg", "active_stroke") || "#000000" + + // Only portals that make CD+G files, with a CD+G section in their theme. + const hasCdg = !!features?.enable_cdg && Object.keys((draft as Record | null)?.cdg || {}).length > 0 + const tabs: Tab[] = hasCdg ? ["titleCard", "karaoke", "endScreen", "cdg", "advanced"] : ["titleCard", "karaoke", "endScreen", "advanced"] // The screen being edited, then the lyrics frame (Advanced shows all three). - type PreviewKind = "title_card" | "karaoke_frame" | "end_screen" + type PreviewKind = "title_card" | "karaoke_frame" | "end_screen" | "cdg_title_card" | "cdg_lyrics" const previewKinds: PreviewKind[] = tab === "endScreen" ? ["end_screen", "karaoke_frame"] - : tab === "advanced" ? ["title_card", "karaoke_frame", "end_screen"] - : ["title_card", "karaoke_frame"] + : tab === "cdg" ? ["cdg_title_card", "cdg_lyrics"] + : tab === "advanced" ? ["title_card", "karaoke_frame", "end_screen"] + : ["title_card", "karaoke_frame"] const previewLabel = (kind: PreviewKind) => - kind === "title_card" ? t("previewTitleCard") : kind === "end_screen" ? t("previewEndScreen") : t("previewKaraoke") + kind === "title_card" ? t("previewTitleCard") + : kind === "end_screen" ? t("previewEndScreen") + : kind === "cdg_title_card" ? t("previewCdgTitleCard") + : kind === "cdg_lyrics" ? t("previewCdgLyrics") + : t("previewKaraoke") + const isCdgKind = (kind: PreviewKind) => kind === "cdg_title_card" || kind === "cdg_lyrics" return ( { if (!o) handleClose() }}> @@ -554,6 +619,85 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) { )} + {tab === "cdg" && ( +
+

{t("cdgIntro")}

+ +
+ + {cdgImageField("title_screen_background", t("cdgUpCardImage"))} +
+ {cdgColour("title_color", t("titleColour"), "#ffff00")} + {cdgColour("artist_color", t("artistColour"), "#ffff00")} +
+
+ + (draft!, "cdg", "title_separator_text") || ""} + onChange={(e) => update("cdg", "title_separator_text", e.target.value || null)} /> +
+ {!!getField(draft!, "cdg", "title_separator_text") && cdgColour("title_separator_color", t("cdgSeparatorColour"))} +
+ {cdgRange("title_font_size", t("cdgTitleSize"), 12, 48, 24)} + {cdgRange("artist_font_size", t("cdgArtistSize"), 12, 48, 24)} + {cdgRange("title_block_top", t("cdgTextTop"), 0, 150, 0)} + {cdgRange("title_artist_gap", t("cdgTitleArtistGap"), 0, 40, 10)} +
+
+ +
+ +
+ {cdgColour("active_fill", t("sungColour"), "#006cf9")} + {cdgColour("inactive_fill", t("unsungColour"), "#ffff00")} + {cdgColour("background_color", t("cdgScreenColour"), "#000000")} + {cdgColour("border_color", t("cdgBorderColour"), "#000000")} +
+
+ {cdgRange("font_size", t("cdgLyricsSize"), 12, 30, 18)} + {cdgRange("stroke_width", t("cdgOutlineWidth"), 0, 4, 0)} +
+ {(getField(draft!, "cdg", "stroke_width") ?? 0) > 0 && ( + { update("cdg", "active_stroke", v); update("cdg", "inactive_stroke", v) }} /> + )} +
+ + +

{t("cdgLyricsFontHint")}

+
+
+ +
+ + {cdgImageField("instrumental_background", t("cdgInstrumentalImage"))} +
+
+ + (draft!, "cdg", "instrumental_text") || ""} + onChange={(e) => update("cdg", "instrumental_text", e.target.value)} /> +
+ {cdgColour("instrumental_font_color", t("cdgInstrumentalColour"), "#ffff00")} +
+
+ +
+ + {cdgImageField("outro_background", t("cdgOutroImage"))} +
+ {cdgColour("outro_line1_color", t("cdgOutroLine1Colour"), "#ffff00")} + {cdgColour("outro_line2_color", t("cdgOutroLine2Colour"), "#ffff00")} +
+
+
+ )} + {tab === "advanced" && (