From bfc8f7fb0f6429fe640c758252f5c98f1d7d8299 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 00:58:42 -0400 Subject: [PATCH] feat(cdg): configurable title card + per-theme CDG lyrics font (Vocal Star up card) (v0.273.0) (#1157) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Vocal Star (and other commercial producers) need CDG files in their own house style. Matt's 2025-02-20 email showed our CDG up card overflowing its bordered design. He asked for his simpler card instead: logo on top, then title, a small "MADE FAMOUS BY" line, then the artist. Two pipeline limits blocked that: - the CDG title card was hardcoded; - a theme could only have **one font** for everything. The shared `font` asset (`intro.font`) overwrites `karaoke.font_path` and `cdg.font_path` at render time. ## Changes - **Title card (cdgmaker composer):** new optional keys; all defaults reproduce today's output. - `title_separator_text` / `_color` / `_font_size`: a line between title and artist. - `title_font_size`, `artist_font_size`, `title_max_height`. - `title_block_top`: centre the block below a logo baked into the background. - It shrinks the title first, then the artist, so it can't loop forever. - **Outro:** respects `title_block_top` and shrinks long text. Before, an `assert` crashed when the text was taller than 200px. - **Fonts:** - The CDG title card and outro use the theme's main font (`cdg.title_font_path`, fed by the shared `font` asset). - A theme may keep a **distinct CDG lyrics font** via a new `cdg_font` asset. The theme service emits it only when it differs from `intro.font`, and `update_asset_paths` applies the shared font first so section overrides win. - No visible change for existing themes, which all use one font. - **Tenant theme editor:** keeps a distinct, available CDG font on save, and copies it into the theme's assets if it's bundled. - Docs: API.md. ## Testing - New `tests/unit/lyrics_transcriber/output/test_cdg_title_card.py` renders **real CDG files**, decodes the packets back into frames and checks: - the separator sits between title and artist; - text stays below `title_block_top` and inside the safe area; - the title font is applied, and a missing one falls back; - long outro text shrinks instead of crashing. - New tests for asset-mapping order, `cdg_font` emission, theme-editor font handling, and the updated mapping assertion. - Package unit tests: 2053 passed. Backend: 6056 passed (emulator tests excluded locally). - Local CodeRabbit with `--fresh`: no findings. - Rendered Vocal Star samples (short, wrapped-long and very long title/artist), decoded and visually checked against Matt's design. After deploy, the Vocal Star theme gets: a new up-card background (logo cropped from Matt's own card), separator "MADE FAMOUS BY", `title_block_top`, black border, Avenir as the main font and Oswald kept for CDG lyrics. @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/admin.py | 5 +- backend/api/routes/jobs.py | 6 +- backend/services/brand_code_service.py | 12 + backend/services/tenant_theme_service.py | 26 ++ backend/services/theme_service.py | 7 + backend/services/visibility_change_service.py | 5 +- backend/tests/test_admin_delete_outputs.py | 17 ++ backend/tests/test_brand_code_service.py | 16 ++ backend/tests/test_tenant_theme_service.py | 39 +++ backend/tests/test_theme_service.py | 24 ++ docs/API.md | 12 +- .../e2e/production/tenant-happy-path.spec.ts | 12 +- karaoke_gen/lyrics_transcriber/output/cdg.py | 87 ++++--- .../output/cdgmaker/composer.py | 244 +++++++++--------- .../output/cdgmaker/config.py | 14 + karaoke_gen/style_loader.py | 9 +- pyproject.toml | 2 +- .../output/test_cdg_title_card.py | 155 +++++++++++ tests/unit/test_style_loader.py | 28 +- 19 files changed, 558 insertions(+), 162 deletions(-) create mode 100644 tests/unit/lyrics_transcriber/output/test_cdg_title_card.py diff --git a/backend/api/routes/admin.py b/backend/api/routes/admin.py index 6fddd5d0..a7c679a5 100644 --- a/backend/api/routes/admin.py +++ b/backend/api/routes/admin.py @@ -1776,7 +1776,8 @@ def delete_job_outputs( # Recycle brand code if Dropbox and GDrive cleanup both succeeded dropbox_success = results["dropbox"]["status"] in ("success", "skipped") gdrive_success = results["gdrive"]["status"] in ("success", "skipped") - if brand_code and dropbox_success and gdrive_success: + from backend.services.brand_code_service import is_preserved_brand_code + if brand_code and dropbox_success and gdrive_success and not is_preserved_brand_code(job, brand_code): try: from backend.services.brand_code_service import BrandCodeService, get_brand_code_service prefix, number = BrandCodeService.parse_brand_code(brand_code) @@ -1786,6 +1787,8 @@ def delete_job_outputs( except (ValueError, Exception) as e: logger.warning(f"Failed to recycle brand code {brand_code}: {e}") results["brand_code"] = {"status": "failed", "error": str(e)} + elif brand_code and is_preserved_brand_code(job, brand_code): + results["brand_code"] = {"status": "skipped", "reason": "Tenant-supplied code (not allocated)"} elif brand_code: logger.warning(f"Brand code {brand_code} NOT recycled: cleanup incomplete (dropbox={results['dropbox']['status']}, gdrive={results['gdrive']['status']})") results["brand_code"] = {"status": "skipped", "reason": "Dropbox/GDrive cleanup incomplete"} diff --git a/backend/api/routes/jobs.py b/backend/api/routes/jobs.py index 5c40e822..fe910ca4 100644 --- a/backend/api/routes/jobs.py +++ b/backend/api/routes/jobs.py @@ -370,7 +370,8 @@ def edit_completed_track( # Recycle brand code if Dropbox + GDrive cleanup both succeeded dropbox_ok = cleanup_results.get("dropbox", {}).get("status") in ("success", "skipped") gdrive_ok = cleanup_results.get("gdrive", {}).get("status") in ("success", "skipped") - if brand_code and dropbox_ok and gdrive_ok: + from backend.services.brand_code_service import is_preserved_brand_code + if brand_code and dropbox_ok and gdrive_ok and not is_preserved_brand_code(job, brand_code): try: from backend.services.brand_code_service import BrandCodeService, get_brand_code_service prefix, number = BrandCodeService.parse_brand_code(brand_code) @@ -2687,7 +2688,8 @@ def _run_distribution_cleanup(job_id: str, job) -> dict: # Recycle the brand code so it can be reused — but only after GDrive is confirmed clean. # If we recycle before GDrive cleanup, a new job could claim the same brand code and # collide with leftover files on GDrive (duplicate brand code in public share). - if dropbox_cleaned and brand_code and gdrive_cleaned: + from backend.services.brand_code_service import is_preserved_brand_code + if dropbox_cleaned and brand_code and gdrive_cleaned and not is_preserved_brand_code(job, brand_code): try: from backend.services.brand_code_service import ( BrandCodeService, get_brand_code_service diff --git a/backend/services/brand_code_service.py b/backend/services/brand_code_service.py index 120cd1a9..aa7c76a1 100644 --- a/backend/services/brand_code_service.py +++ b/backend/services/brand_code_service.py @@ -217,6 +217,18 @@ class BrandCodeService: return match.group(1), int(match.group(2)) +def is_preserved_brand_code(job, brand_code: Optional[str]) -> bool: + """True when ``brand_code`` came from the job itself (``keep_brand_code`` — e.g. a + tenant's own catalogue code like "VS6588"), not from the allocator. + + Such codes must never be recycled into a counter: a tenant code that happens to + look like an allocated one (e.g. "VSTAR-0005") would otherwise put that number + back in the pool and cause a duplicate later. + """ + kept = getattr(job, "keep_brand_code", None) + return bool(kept) and kept == brand_code + + def get_brand_code_service() -> BrandCodeService: """Get or create the singleton BrandCodeService instance.""" global _brand_code_service diff --git a/backend/services/tenant_theme_service.py b/backend/services/tenant_theme_service.py index f7fab9ea..be2381bd 100644 --- a/backend/services/tenant_theme_service.py +++ b/backend/services/tenant_theme_service.py @@ -174,7 +174,21 @@ def sanitize_style_params( font = _basename_only(styles["intro"].get("font") or DEFAULT_FONT, "intro.font") if font not in fonts_ok: raise TenantValidationError(f"Font '{font}' isn't available — upload it or pick a built-in font.") + # The one exception: CDG may keep a distinct lyrics font (rendered as its own + # "cdg_font" asset — e.g. a condensed face so lyric lines fit the CDG screen), + # as long as it's a basename the theme can actually serve. + cdg_font = styles["cdg"].get("font_path") + keep_cdg_font = ( + isinstance(cdg_font, str) + and cdg_font + and os.path.basename(cdg_font) == cdg_font + and cdg_font != font + and cdg_font.lower().endswith((".ttf", ".otf")) + and cdg_font in fonts_ok + ) for section, field in FONT_FIELDS: + if keep_cdg_font and (section, field) == ("cdg", "font_path"): + continue styles[section][field] = font from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE @@ -328,6 +342,18 @@ def save_tenant_theme(config, style_params: object, storage: Optional[StorageSer # Bundled font: copy into the theme so render jobs download it. with open(local, "rb") as fh: assets[font] = (fh.read(), font.rsplit(".", 1)[-1]) + cdg_font = styles["cdg"].get("font_path") + if cdg_font and cdg_font != font: + # Distinct CDG lyrics font: it must really be a font, and a bundled one + # is copied into the theme so render jobs find it. + cdg_local = _font_local_path(storage, theme_id, cdg_font, workdir) + try: + font_family_name(cdg_local) + except Exception as exc: + raise TenantValidationError(f"CDG font '{cdg_font}' couldn't be read.") from exc + if not storage.file_exists(f"{THEMES_PREFIX}/{theme_id}/assets/{cdg_font}"): + with open(cdg_local, "rb") as fh: + assets[cdg_font] = (fh.read(), cdg_font.rsplit(".", 1)[-1]) update_tenant(config.id, style_params=styles, assets=assets or None, storage=storage) logger.info(f"Tenant '{config.id}' saved theme '{theme_id}' (font={font})") diff --git a/backend/services/theme_service.py b/backend/services/theme_service.py index aa84d785..79661d5e 100644 --- a/backend/services/theme_service.py +++ b/backend/services/theme_service.py @@ -364,6 +364,13 @@ class ThemeService: ("cdg_outro_background", "cdg", "outro_background"), ] + # A distinct CDG lyrics font gets its own asset (the shared "font" asset — + # intro.font — is otherwise applied to every section, CDG included). + main_font = os.path.basename(str(style_params.get("intro", {}).get("font") or "")) + cdg_font = os.path.basename(str(style_params.get("cdg", {}).get("font_path") or "")) + if cdg_font and cdg_font != main_font: + asset_checks.append(("cdg_font", "cdg", "font_path")) + for asset_key, section, field in asset_checks: if section in style_params and field in style_params[section]: value = style_params[section][field] diff --git a/backend/services/visibility_change_service.py b/backend/services/visibility_change_service.py index 188fd626..e2fded33 100644 --- a/backend/services/visibility_change_service.py +++ b/backend/services/visibility_change_service.py @@ -446,8 +446,9 @@ class VisibilityChangeService: except Exception as e: logger.warning(f"[job:{job_id}] Failed to delete GCS finals: {e}") - # Recycle brand code - if brand_code: + # Recycle brand code (never a tenant-supplied / preserved one) + from backend.services.brand_code_service import is_preserved_brand_code + if brand_code and not is_preserved_brand_code(job, brand_code): try: from backend.services.brand_code_service import BrandCodeService, get_brand_code_service prefix, number = BrandCodeService.parse_brand_code(brand_code) diff --git a/backend/tests/test_admin_delete_outputs.py b/backend/tests/test_admin_delete_outputs.py index 6158b1b4..d1a87315 100644 --- a/backend/tests/test_admin_delete_outputs.py +++ b/backend/tests/test_admin_delete_outputs.py @@ -522,6 +522,23 @@ class TestDeleteOutputsBrandCodeRecycling: assert data["deleted_services"]["brand_code"]["code"] == "NOMAD-1234" mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 1234) + def test_tenant_preserved_brand_code_is_never_recycled(self, client, mock_complete_job): + """A tenant's own track code (keep_brand_code) must not go back into a counter.""" + mock_complete_job.keep_brand_code = "NOMAD-1234" # looks allocated, but tenant-supplied + with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \ + patch('backend.api.routes.admin.get_user_service') as mock_user_service, \ + patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc: + mock_jm = Mock() + mock_jm.get_job.return_value = mock_complete_job + mock_jm_class.return_value = mock_jm + mock_user_service.return_value.db = Mock() + + response = client.post("/api/admin/jobs/test-job-123/delete-outputs") + + assert response.status_code == 200 + assert response.json()["deleted_services"]["brand_code"]["reason"] == "Tenant-supplied code (not allocated)" + mock_get_svc.return_value.recycle_brand_code.assert_not_called() + def test_brand_code_not_recycled_without_brand_code(self, client, mock_job_no_outputs): """Test that no recycling happens when job has no brand code.""" with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \ diff --git a/backend/tests/test_brand_code_service.py b/backend/tests/test_brand_code_service.py index 1088f75e..7a3f3ecd 100644 --- a/backend/tests/test_brand_code_service.py +++ b/backend/tests/test_brand_code_service.py @@ -588,3 +588,19 @@ class TestGetBrandCodeService: # Clean up module._brand_code_service = None + + +class TestIsPreservedBrandCode: + def test_tenant_code_matching_keep_brand_code_is_preserved(self): + from types import SimpleNamespace + from backend.services.brand_code_service import is_preserved_brand_code + + assert is_preserved_brand_code(SimpleNamespace(keep_brand_code="VS6588"), "VS6588") + + def test_allocated_code_is_not_preserved(self): + from types import SimpleNamespace + from backend.services.brand_code_service import is_preserved_brand_code + + assert not is_preserved_brand_code(SimpleNamespace(keep_brand_code=None), "VSTAR-0003") + assert not is_preserved_brand_code(SimpleNamespace(), "VSTAR-0003") + assert not is_preserved_brand_code(SimpleNamespace(keep_brand_code="VS1"), "VSTAR-0003") diff --git a/backend/tests/test_tenant_theme_service.py b/backend/tests/test_tenant_theme_service.py index bed023cc..188cc34b 100644 --- a/backend/tests/test_tenant_theme_service.py +++ b/backend/tests/test_tenant_theme_service.py @@ -177,6 +177,28 @@ def test_save_copies_bundled_font_sets_family_and_never_touches_config(monkeypat assert calls["style_params"]["karaoke"]["font_path"] == "AvenirNext-Bold.ttf" +def test_save_keeps_distinct_cdg_font_and_copies_it_when_bundled(monkeypatch): + storage = FakeStorage() + calls = {} + monkeypatch.setattr(tts, "update_tenant", lambda tenant_id, **kw: calls.update(kw)) + style = _style() + style["cdg"]["font_path"] = "Oswald-SemiBold.ttf" + tts.save_tenant_theme(_config(), style, storage=storage) + assert calls["style_params"]["cdg"]["font_path"] == "Oswald-SemiBold.ttf" + assert calls["style_params"]["karaoke"]["font_path"] == "AvenirNext-Bold.ttf" + assert "Oswald-SemiBold.ttf" in calls["assets"] + + +def test_save_rejects_an_unreadable_distinct_cdg_font(monkeypatch): + storage = FakeStorage() + storage.blobs["themes/randy-vild/assets/Custom-abc12345.ttf"] = b"not really a font" + monkeypatch.setattr(tts, "update_tenant", lambda tenant_id, **kw: None) + style = _style() + style["cdg"]["font_path"] = "Custom-abc12345.ttf" + with pytest.raises(TenantValidationError): + tts.save_tenant_theme(_config(), style, storage=storage) + + def test_get_theme_for_editor_lists_images_and_fonts(): storage = FakeStorage() storage.blobs["themes/randy-vild/assets/Custom-abc12345.ttf"] = b"font" @@ -276,3 +298,20 @@ def test_screen_enabled_flag_must_be_boolean(section): style[section]["enabled"] = "no" with pytest.raises(TenantValidationError, match=f"{section}.enabled"): tts.sanitize_style_params(style, available_assets=ASSETS) + + +def test_sanitize_keeps_a_distinct_available_cdg_font(): + style = _style() + style["cdg"]["font_path"] = "Oswald-SemiBold.ttf" # bundled, condensed for CDG lyrics + styles, font = tts.sanitize_style_params(style, available_assets=ASSETS) + assert font == "AvenirNext-Bold.ttf" + assert styles["karaoke"]["font_path"] == "AvenirNext-Bold.ttf" + assert styles["cdg"]["font_path"] == "Oswald-SemiBold.ttf" + + +@pytest.mark.parametrize("bad", ["/abs/Oswald-SemiBold.ttf", "NotAFont-zzz.ttf", "bg.jpg"]) +def test_sanitize_replaces_unsafe_or_unknown_cdg_font_with_main_font(bad): + style = _style() + style["cdg"]["font_path"] = bad + styles, _ = tts.sanitize_style_params(style, available_assets=ASSETS) + assert styles["cdg"]["font_path"] == "AvenirNext-Bold.ttf" diff --git a/backend/tests/test_theme_service.py b/backend/tests/test_theme_service.py index 15bc67bd..ee950fcf 100644 --- a/backend/tests/test_theme_service.py +++ b/backend/tests/test_theme_service.py @@ -537,3 +537,27 @@ class TestThemeAPI: assert response.status_code == 200 data = response.json() assert data["description"] == "Thank you for watching!" + + +class TestDistinctCdgFont: + """A theme whose CDG lyrics font differs from its main font gets a cdg_font asset.""" + + def _style(self, cdg_font): + return { + "intro": {"font": "AvenirNext-Bold.ttf"}, + "karaoke": {"font_path": "AvenirNext-Bold.ttf"}, + "cdg": {"font_path": cdg_font}, + } + + def test_distinct_cdg_font_is_its_own_asset(self): + storage = Mock() + storage.file_exists.return_value = True + assets = ThemeService(storage=storage)._build_style_assets_mapping("vocalstar", self._style("Oswald-SemiBold.ttf")) + assert assets["font"] == "themes/vocalstar/assets/AvenirNext-Bold.ttf" + assert assets["cdg_font"] == "themes/vocalstar/assets/Oswald-SemiBold.ttf" + + def test_same_cdg_font_adds_no_extra_asset(self): + storage = Mock() + storage.file_exists.return_value = True + assets = ThemeService(storage=storage)._build_style_assets_mapping("nomad", self._style("AvenirNext-Bold.ttf")) + assert "cdg_font" not in assets diff --git a/docs/API.md b/docs/API.md index 9923be5f..97873648 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1445,8 +1445,16 @@ re-checks membership (`require_tenant_member`): non-members/spoofed headers → be basenames already in the theme's assets (no paths / `gs://`), numeric/colour/region bounds are checked, and the font is made consistent with the render pipeline — `intro.font` is applied to `karaoke.font_path`/`end.font`/`cdg.font_path`, `karaoke.font` is set to the TTF family name libass - matches, and a chosen bundled font is copied into the theme's assets. Tenants can't change their - config/allowlist through this API. + matches, and a chosen bundled font is copied into the theme's assets. The one exception is a + distinct, available `cdg.font_path` (e.g. a condensed face so lyric lines fit the 300x216 CDG + screen): it's kept and rendered via its own `cdg_font` style asset, while the CDG title card and + outro use the main font (`cdg.title_font_path`). Tenants can't change their config/allowlist + through this API. +- **CDG title card ("up card") keys** (all optional; defaults reproduce the original layout): + `title_font_size` (30), `artist_font_size` (25), `title_max_height` (200), + `title_separator_text` (e.g. `"MADE FAMOUS BY"`) + `title_separator_color` + + `title_separator_font_size`, and `title_block_top` — center the title block (and the outro) in + the area below this y offset, for a logo baked into `title_screen_background`. UI: user menu → **Theme & style** on tenant portals (`components/tenant-theme/`). After a save, the editor says how many in-progress tracks were updated and offers **Re-render all N** for outdated diff --git a/frontend/e2e/production/tenant-happy-path.spec.ts b/frontend/e2e/production/tenant-happy-path.spec.ts index c1067dfb..61cee946 100644 --- a/frontend/e2e/production/tenant-happy-path.spec.ts +++ b/frontend/e2e/production/tenant-happy-path.spec.ts @@ -48,6 +48,11 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => { }); test.afterAll(async () => { + // E2E_KEEP_JOB=1 keeps the job + outputs for manual inspection (local runs only). + if (process.env.E2E_KEEP_JOB === '1') { + console.log(`[${TENANT_ID}] Keeping job ${createdJobId} (E2E_KEEP_JOB=1) — delete it when done`); + return; + } if (createdJobId && ADMIN_TOKEN) { // DELETE /api/jobs/{id} uses require_auth + ownership; admins bypass. await fetch(`${API_URL}/api/jobs/${createdJobId}`, { @@ -140,8 +145,12 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => { // Submit a track through the tenant portal form // ===================================================================== const uniqueTitle = `E2E ${TENANT_ID} ${new Date().toISOString().replace(/[:.]/g, '-')}`; + // Tenant catalogue code (e.g. Vocal Star's "VS6588"): must become the job's + // brand code, so the delivery folder + every file are prefixed with it. + const trackCode = `E2E${Date.now().toString().slice(-7)}`; await page.getByLabel('Artist').fill('Nomad E2E'); await page.getByLabel('Title').fill(uniqueTitle); + await page.getByLabel('Track code (optional)').fill(trackCode); await page.locator('#tenant-mixed-audio').setInputFiles(MIXED_AUDIO); await page.locator('#tenant-instrumental-audio').setInputFiles(INSTRUMENTAL_AUDIO); await page.getByRole('button', { name: /submit track/i }).click(); @@ -275,6 +284,7 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => { for (const f of ['lossy_4k_mp4', 'lossy_720p_mp4', 'with_vocals_mp4']) expect(finals).toContain(f); for (const p of ['cdg_zip', 'txt_zip']) expect(packages).toContain(p); expect(job.is_private, 'tenant job is private').toBeTruthy(); + expect(sd.brand_code, 'tenant track code used as the brand code (output folder/file prefix)').toBe(trackCode); // Real-world tenant-scenario invariants (beyond "it completed"): these guard the // exact flow tenant operators rely on — they upload their own audio + instrumental, @@ -283,6 +293,6 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => { expect(sd.instrumental_selection, 'uploaded instrumental used (custom), not a separated stem').toBe('custom'); // 2. Lyrics were transcribed + corrected — the job did real work, not a short-circuit. expect(sd.lyrics_complete, 'lyrics transcription completed').toBeTruthy(); - console.log(`[${TENANT_ID}] PASSED — complete, private, Dropbox present, no YouTube, uploaded instrumental used, downloads available`); + console.log(`[${TENANT_ID}] PASSED — complete, private, Dropbox present, no YouTube, uploaded instrumental used, track code ${trackCode} applied, downloads available`); }); }); diff --git a/karaoke_gen/lyrics_transcriber/output/cdg.py b/karaoke_gen/lyrics_transcriber/output/cdg.py index bffefc45..7afd9bff 100644 --- a/karaoke_gen/lyrics_transcriber/output/cdg.py +++ b/karaoke_gen/lyrics_transcriber/output/cdg.py @@ -254,56 +254,65 @@ class CDGGenerator: self._write_toml_file(toml_data, output_file) def _validate_and_setup_font(self, cdg_styles: dict) -> None: - """Validate and set up font path in CDG styles. + """Validate and set up font paths in CDG styles. - Resolution order: + Resolution order for ``font_path`` (lyrics font): 1. Use font_path as-is if it's an absolute path that exists 2. Use font_path as-is if it exists as a relative path 3. Try full relative path inside bundled fonts directory 4. Try just the filename inside bundled fonts directory 5. Fall back to arial.ttf from bundled fonts - """ - if not cdg_styles.get("font_path"): - return + ``title_font_path`` (optional font for the title card / outro, usually the + theme's main font) resolves the same way but falls back to ``font_path``. + """ + if cdg_styles.get("font_path"): + resolved = self._resolve_font_file(cdg_styles["font_path"]) + font_path = cdg_styles["font_path"] + fonts_dir = os.path.join(os.path.dirname(__file__), "fonts") + fallback_font = os.path.join(fonts_dir, "arial.ttf") + if resolved: + cdg_styles["font_path"] = resolved + elif os.path.isfile(fallback_font): + # Last resort: fall back to arial.ttf + cdg_styles["font_path"] = os.path.abspath(fallback_font) + self.logger.warning(f"Font file {font_path} not found, falling back to bundled arial.ttf") + else: + self.logger.error(f"Font file {font_path} not found and no bundled fonts available in {fonts_dir}") + cdg_styles["font_path"] = None + + if cdg_styles.get("title_font_path"): + resolved = self._resolve_font_file(cdg_styles["title_font_path"]) + if resolved: + cdg_styles["title_font_path"] = resolved + else: + self.logger.warning( + f"Title font {cdg_styles['title_font_path']} not found, using the lyrics font for the title card" + ) + cdg_styles.pop("title_font_path") + + def _resolve_font_file(self, font_path: str) -> Optional[str]: + """Absolute path for a font: as given, else in the bundled fonts dir; None if missing.""" fonts_dir = os.path.join(os.path.dirname(__file__), "fonts") - font_path = cdg_styles["font_path"] # Already exists (absolute or relative to cwd) — absolutize to avoid CWD issues if os.path.isfile(font_path): - cdg_styles["font_path"] = os.path.abspath(font_path) - return + return os.path.abspath(font_path) # Try full relative path in bundled fonts dir package_font_path = os.path.join(fonts_dir, font_path) if os.path.isfile(package_font_path): - cdg_styles["font_path"] = os.path.abspath(package_font_path) self.logger.debug(f"Found font in package fonts directory: {package_font_path}") - return + return os.path.abspath(package_font_path) # Try just the filename in bundled fonts dir font_filename = os.path.basename(font_path) package_font_by_name = os.path.join(fonts_dir, font_filename) if os.path.isfile(package_font_by_name): - cdg_styles["font_path"] = os.path.abspath(package_font_by_name) - self.logger.warning( - f"Font file {font_path} not found, using bundled font: {font_filename}" - ) - return + self.logger.warning(f"Font file {font_path} not found, using bundled font: {font_filename}") + return os.path.abspath(package_font_by_name) - # Last resort: fall back to arial.ttf - fallback_font = os.path.join(fonts_dir, "arial.ttf") - if os.path.isfile(fallback_font): - cdg_styles["font_path"] = os.path.abspath(fallback_font) - self.logger.warning( - f"Font file {font_path} not found, falling back to bundled arial.ttf" - ) - return - - self.logger.error( - f"Font file {font_path} not found and no bundled fonts available in {fonts_dir}" - ) - cdg_styles["font_path"] = None + return None def _compose_cdg(self, toml_file: str) -> None: """Compose CDG using KaraokeComposer.""" @@ -435,7 +444,13 @@ class CDGGenerator: optional_styles_with_defaults = { "title_top_padding": 0, - # Any other optional parameters with their default values + # Title card ("up card") layout — defaults reproduce the original layout + "title_font_size": 30, + "artist_font_size": 25, + "title_max_height": 200, + "title_separator_text": "", + "title_separator_color": "#ffffff", + "title_separator_font_size": 14, } # Add any missing optional parameters with their default values @@ -610,6 +625,20 @@ class CDGGenerator: "outro_line1_color": cdg_styles["outro_line1_color"], "outro_line2_color": cdg_styles["outro_line2_color"], "outro_line1_line2_gap": cdg_styles["outro_line1_line2_gap"], + "title_font_size": cdg_styles["title_font_size"], + "artist_font_size": cdg_styles["artist_font_size"], + "title_max_height": cdg_styles["title_max_height"], + "title_separator_text": cdg_styles["title_separator_text"], + "title_separator_color": cdg_styles["title_separator_color"], + "title_separator_font_size": cdg_styles["title_separator_font_size"], + # Title card / outro font (theme's main font); falls back to `font` in the composer + **({"title_font": cdg_styles["title_font_path"]} if cdg_styles.get("title_font_path") else {}), + # TOML has no null: only emitted when the theme sets it + **( + {"title_block_top": cdg_styles["title_block_top"]} + if cdg_styles.get("title_block_top") is not None + else {} + ), } def _write_toml_file(self, toml_data: dict, output_file: str) -> None: diff --git a/karaoke_gen/lyrics_transcriber/output/cdgmaker/composer.py b/karaoke_gen/lyrics_transcriber/output/cdgmaker/composer.py index d7da872f..94508081 100644 --- a/karaoke_gen/lyrics_transcriber/output/cdgmaker/composer.py +++ b/karaoke_gen/lyrics_transcriber/output/cdgmaker/composer.py @@ -1552,109 +1552,106 @@ class KaraokeComposer: self.config.border, # border self.config.title_color, # title color self.config.artist_color, # artist color + self.config.title_separator_color, # separator line color (index 4) ], ) - smallfont = ImageFont.truetype(self.config.font, 25) - bigfont_size = 30 - MAX_HEIGHT = 200 - # Try rendering the title and artist to an image + bigfont_size = self.config.title_font_size + artist_font_size = self.config.artist_font_size + separator_font_size = self.config.title_separator_font_size + MAX_HEIGHT = self.config.title_max_height + MIN_FONT_SIZE = 10 + separator_text = (self.config.title_separator_text or "").strip() + # Try rendering the title (+ optional separator line, e.g. "MADE FAMOUS BY") + # and artist to an image, shrinking until the block fits MAX_HEIGHT. while True: self.logger.debug(f"trying song title at size {bigfont_size}") - text_image = Image.new("P", (CDG_VISIBLE_WIDTH, MAX_HEIGHT * 2), 0) + text_image = Image.new("P", (CDG_VISIBLE_WIDTH, MAX_HEIGHT * 3), 0) y = 0 - if self.config.title_top_padding: - self.logger.info(f"title top padding set to {self.config.title_top_padding} in config, setting as initial y position") - y = self.config.title_top_padding - self.logger.info(f"Initial y position with padding: {y}") - else: - self.logger.info("no title top padding configured; starting with y = 0") - self.logger.info(f"Initial y position without padding: {y}") + bigfont = ImageFont.truetype(self._title_font_path(), bigfont_size) + smallfont = ImageFont.truetype(self._title_font_path(), artist_font_size) - bigfont = ImageFont.truetype(self.config.font, bigfont_size) + def draw_block(text: str, font, color_index: int, y: int) -> int: + for image in render_lines( + get_wrapped_text( + text, + font=font, + width=text_image.width, + ).split("\n"), + font=font, + ): + text_image.paste( + image.point(lambda v: v and color_index, "P"), + ((text_image.width - image.width) // 2, y), + mask=image.point(lambda v: v and 255, "1"), + ) + y += int(font.size) + return y - # Draw song title + # Draw song title (index 2 = title color) title_start_y = y - self.logger.info(f"Starting to draw title at y={y}") - for image in render_lines( - get_wrapped_text( - self.config.title, - font=bigfont, - width=text_image.width, - ).split("\n"), - font=bigfont, - ): - text_image.paste( - # Use index 2 for title color - image.point(lambda v: v and 2, "P"), - ((text_image.width - image.width) // 2, y), - mask=image.point(lambda v: v and 255, "1"), - ) - y += int(bigfont.size) - title_end_y = y - self.logger.info(f"Finished drawing title at y={y}, title height={title_end_y - title_start_y}") + y = draw_block(self.config.title, bigfont, 2, y) + self.logger.info(f"Finished drawing title at y={y}, title height={y - title_start_y}") # Add vertical gap between title and artist using configured value y += self.config.title_artist_gap - self.logger.info(f"After adding title_artist_gap of {self.config.title_artist_gap}, y is now {y}") - # Draw song artist + if separator_text: + # Optional separator line (index 4 = separator color), then the + # same gap again before the artist. + separator_font = ImageFont.truetype(self._title_font_path(), separator_font_size) + y = draw_block(separator_text, separator_font, 4, y) + y += self.config.title_artist_gap + + # Draw song artist (index 3 = artist color) artist_start_y = y - self.logger.info(f"Starting to draw artist at y={y}") - for image in render_lines( - get_wrapped_text( - self.config.artist, - font=smallfont, - width=text_image.width, - ).split("\n"), - font=smallfont, - ): - text_image.paste( - # Use index 3 for artist color - image.point(lambda v: v and 3, "P"), - ((text_image.width - image.width) // 2, y), - mask=image.point(lambda v: v and 255, "1"), - ) - y += int(smallfont.size) - artist_end_y = y - self.logger.info(f"Finished drawing artist at y={y}, artist height={artist_end_y - artist_start_y}") - self.logger.info(f"Total content height before cropping: {artist_end_y - title_start_y}") + y = draw_block(self.config.artist, smallfont, 3, y) + self.logger.info(f"Finished drawing artist at y={y}, artist height={y - artist_start_y}") # Break out of loop only if text box ends up small enough bbox = text_image.getbbox() - self.logger.info(f"Original bounding box from getbbox(): {bbox}") if bbox is None: # If there's no content, still create a minimal bbox bbox = (0, 0, text_image.width, 1) self.logger.info("No content found, created minimal bbox") - + # We'll crop to just the content area, without padding - original_height = text_image.height text_image = text_image.crop(bbox) - self.logger.info(f"After cropping: text_image dimensions={text_image.width}x{text_image.height}, height difference={original_height - text_image.height}") - + if text_image.height <= MAX_HEIGHT: self.logger.debug("height just right") break - # If text box is not small enough, reduce font size of title + # If text box is not small enough, reduce the title font size first; + # once the title is at the floor, shrink the artist + separator too so + # very long titles/artists can never loop forever. self.logger.debug("height too big; reducing font size") - bigfont_size -= 2 + if bigfont_size - 2 >= max(MIN_FONT_SIZE, min(artist_font_size, self.config.title_font_size)): + bigfont_size -= 2 + elif artist_font_size - 2 >= MIN_FONT_SIZE or bigfont_size - 2 >= MIN_FONT_SIZE: + bigfont_size = max(MIN_FONT_SIZE, bigfont_size - 2) + artist_font_size = max(MIN_FONT_SIZE, artist_font_size - 2) + separator_font_size = max(MIN_FONT_SIZE, separator_font_size - 1) + else: + self.logger.warning("title card text still too tall at minimum font size; using it anyway") + break - # Calculate position - center horizontally, but add padding to vertical position + # Calculate position - center horizontally center_x = (CDG_SCREEN_WIDTH - text_image.width) // 2 - - # Standard centered position - standard_center_y = (CDG_SCREEN_HEIGHT - text_image.height) // 2 - - # Add the title_top_padding to shift the entire content downward - padding_offset = self.config.title_top_padding if self.config.title_top_padding else 0 - final_y = standard_center_y + padding_offset - - self.logger.info(f"Pasting text image ({text_image.width}x{text_image.height}) onto background") - self.logger.info(f"Standard centered position would be y={standard_center_y}") - self.logger.info(f"With padding offset of {padding_offset}, final position is y={final_y}") - + + if self.config.title_block_top is not None: + # Center the text block in the area below title_block_top (e.g. below a + # logo at the top of the background), keeping it inside the safe area. + area_top = self.config.title_block_top + area_bottom = CDG_SCREEN_HEIGHT - (CDG_SCREEN_HEIGHT - CDG_VISIBLE_HEIGHT) // 2 + final_y = max(area_top, area_top + (area_bottom - area_top - text_image.height) // 2) + else: + # Standard centered position, shifted down by title_top_padding + standard_center_y = (CDG_SCREEN_HEIGHT - text_image.height) // 2 + padding_offset = self.config.title_top_padding if self.config.title_top_padding else 0 + final_y = standard_center_y + padding_offset + self.logger.info(f"Pasting text image ({text_image.width}x{text_image.height}) at y={final_y}") + background_image.paste( text_image, ( @@ -1738,65 +1735,58 @@ class KaraokeComposer: ], ) - smallfont = ImageFont.truetype(self.config.font, 25) - MAX_HEIGHT = 200 - - # Render text to an image - self.logger.debug(f"rendering outro text") - text_image = Image.new("P", (CDG_VISIBLE_WIDTH, MAX_HEIGHT * 2), 0) - y = 0 - - # Render first line of outro text + safe_bottom = CDG_SCREEN_HEIGHT - (CDG_SCREEN_HEIGHT - CDG_VISIBLE_HEIGHT) // 2 + area_top = self.config.title_block_top + # Keep the outro text below a logo baked into the background when configured. + MAX_HEIGHT = (safe_bottom - area_top) if area_top is not None else 200 outro_text_line1 = self.config.outro_text_line1.replace("$artist", self.config.artist).replace("$title", self.config.title) - - for image in render_lines( - get_wrapped_text( - outro_text_line1, - font=smallfont, - width=text_image.width, - ).split("\n"), - font=smallfont, - ): - text_image.paste( - # Use index 2 for line 1 color - image.point(lambda v: v and 2, "P"), - ((text_image.width - image.width) // 2, y), - mask=image.point(lambda v: v and 255, "1"), - ) - y += int(smallfont.size) - - # Add vertical gap between title and artist using configured value - y += self.config.outro_line1_line2_gap - - # Render second line of outro text outro_text_line2 = self.config.outro_text_line2.replace("$artist", self.config.artist).replace("$title", self.config.title) - for image in render_lines( - get_wrapped_text( - outro_text_line2, - font=smallfont, - width=text_image.width, - ).split("\n"), - font=smallfont, - ): - text_image.paste( - # Use index 3 for line 2 color - image.point(lambda v: v and 3, "P"), - ((text_image.width - image.width) // 2, y), - mask=image.point(lambda v: v and 255, "1"), - ) - y += int(smallfont.size) + font_size = 25 + while True: + smallfont = ImageFont.truetype(self._title_font_path(), font_size) - # Break out of loop only if text box ends up small enough - text_image = text_image.crop(text_image.getbbox()) - assert text_image.height <= MAX_HEIGHT + # Render text to an image + self.logger.debug(f"rendering outro text at size {font_size}") + text_image = Image.new("P", (CDG_VISIBLE_WIDTH, MAX_HEIGHT * 3), 0) + y = 0 + + for line_text, color_index in ((outro_text_line1, 2), (outro_text_line2, 3)): + for image in render_lines( + get_wrapped_text( + line_text, + font=smallfont, + width=text_image.width, + ).split("\n"), + font=smallfont, + ): + text_image.paste( + # Index 2 = line 1 color, index 3 = line 2 color + image.point(lambda v, c=color_index: v and c, "P"), + ((text_image.width - image.width) // 2, y), + mask=image.point(lambda v: v and 255, "1"), + ) + y += int(smallfont.size) + if color_index == 2: + # Add vertical gap between line 1 and line 2 using configured value + y += self.config.outro_line1_line2_gap + + bbox = text_image.getbbox() or (0, 0, text_image.width, 1) + text_image = text_image.crop(bbox) + if text_image.height <= MAX_HEIGHT or font_size <= 10: + break + font_size -= 2 # Draw text onto image + if area_top is not None: + outro_y = max(area_top, area_top + (safe_bottom - area_top - text_image.height) // 2) + else: + outro_y = (CDG_SCREEN_HEIGHT - text_image.height) // 2 background_image.paste( text_image, ( (CDG_SCREEN_WIDTH - text_image.width) // 2, - (CDG_SCREEN_HEIGHT - text_image.height) // 2, + outro_y, ), mask=text_image.point(lambda v: v and 255, "1"), ) @@ -1819,6 +1809,16 @@ class KaraokeComposer: self.writer.queue_packets([no_instruction()] * (end - self.writer.packets_queued)) + def _title_font_path(self): + """Font for the title card + outro: `title_font` when it exists, else the lyrics font.""" + title_font = self.config.title_font + if title_font: + for candidate in (Path(title_font), self.relative_dir / title_font): + if candidate.is_file(): + return str(candidate) + self.logger.warning(f"Title font not found: {title_font}; using the lyrics font") + return self.config.font + def _load_image( self, image_path: "StrOrBytesPath | Path", diff --git a/karaoke_gen/lyrics_transcriber/output/cdgmaker/config.py b/karaoke_gen/lyrics_transcriber/output/cdgmaker/config.py index 777e3583..37a28b94 100644 --- a/karaoke_gen/lyrics_transcriber/output/cdgmaker/config.py +++ b/karaoke_gen/lyrics_transcriber/output/cdgmaker/config.py @@ -127,6 +127,20 @@ class Settings: title_screen_transition: str = "centertexttoplogobottomtext" title_artist_gap: int = 30 title_top_padding: int = 0 + # Title card ("up card") layout. Defaults reproduce the original layout: + # title (30px, shrinks to fit) / gap / artist (25px), centered on screen. + # Font for the title card + outro (defaults to `font`, the lyrics font). + title_font: Path | None = None + title_font_size: int = 30 + artist_font_size: int = 25 + title_max_height: int = 200 + # Optional line between title and artist, e.g. "MADE FAMOUS BY". + title_separator_text: str = "" + title_separator_color: RGBColor = field(converter=to_rgbcolor, default="#ffffff") + title_separator_font_size: int = 14 + # When set, the text block is centered in the area below this y offset + # (e.g. below a logo baked into the title background) instead of on screen. + title_block_top: int | None = None intro_duration_seconds: float = 5.0 first_syllable_buffer_seconds: float = 3.0 diff --git a/karaoke_gen/style_loader.py b/karaoke_gen/style_loader.py index 5e6847f0..9b07d2e8 100644 --- a/karaoke_gen/style_loader.py +++ b/karaoke_gen/style_loader.py @@ -213,13 +213,18 @@ ASSET_KEY_MAPPINGS: Dict[str, Union[Tuple[str, str], List[Tuple[str, str]]]] = { ("karaoke", "font_path"), ("end", "font"), ("cdg", "font_path"), + ("cdg", "title_font_path"), # CDG title card / outro use the theme's main font ], "style_font": [ # CLI upload key ("intro", "font"), ("karaoke", "font_path"), ("end", "font"), ("cdg", "font_path"), + ("cdg", "title_font_path"), ], + # Optional distinct CDG lyrics font (e.g. a condensed face that fits more of a + # lyric line on the 300x216 CDG screen). Applied after "font" so it wins. + "cdg_font": ("cdg", "font_path"), # CDG-specific backgrounds "cdg_instrumental_background": ("cdg", "instrumental_background"), @@ -355,7 +360,9 @@ def update_asset_paths( log = logger or logging.getLogger(__name__) updates_made = False - for asset_key, local_path in local_assets.items(): + # Shared keys first so section-specific overrides (e.g. "cdg_font") win. + shared_first = sorted(local_assets.items(), key=lambda kv: kv[0] not in ("font", "style_font")) + for asset_key, local_path in shared_first: if asset_key not in ASSET_KEY_MAPPINGS: continue diff --git a/pyproject.toml b/pyproject.toml index 245eabd8..c4b26432 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "karaoke-gen" -version = "0.272.0" +version = "0.273.0" description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens." authors = ["Andrew Beveridge "] license = "MIT" diff --git a/tests/unit/lyrics_transcriber/output/test_cdg_title_card.py b/tests/unit/lyrics_transcriber/output/test_cdg_title_card.py new file mode 100644 index 00000000..9adb2f44 --- /dev/null +++ b/tests/unit/lyrics_transcriber/output/test_cdg_title_card.py @@ -0,0 +1,155 @@ +"""End-to-end tests for the configurable CDG title card ("up card") and outro. + +Renders real CDG files through CDGGenerator + KaraokeComposer, decodes the +packets back into frames with a tiny CD+G decoder and asserts on the pixels: +separator line ("MADE FAMOUS BY"), text kept below a logo area +(``title_block_top``), outro shrink-to-fit, and the title-font fallback. +""" +import os +import shutil +import subprocess + +import pytest +from PIL import Image + +from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator + +pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg required to compose CDG audio") + +CDG_FPS = 300 +W, H = 300, 216 +YELLOW = (255, 255, 0) +WHITE = (255, 255, 255) + + +def _font(name: str) -> str: + import karaoke_gen.lyrics_transcriber.output as output_mod + + return os.path.join(os.path.dirname(output_mod.__file__), "fonts", name) + + +def decode_frame(cdg_path: str, seconds: float) -> Image.Image: + """Decode a CD+G file up to `seconds` and return the screen as RGB.""" + data = open(cdg_path, "rb").read() + px = bytearray(W * H) + pal = [(0, 0, 0)] * 16 + for i in range(min(len(data) // 24, int(seconds * CDG_FPS))): + p = data[i * 24:(i + 1) * 24] + if p[0] & 0x3F != 9: + continue + ins, d = p[1] & 0x3F, p[4:20] + if ins == 1: # memory preset + px[:] = bytes([d[0] & 0x0F]) * (W * H) + elif ins in (6, 38): # tile block (normal / XOR) + c0, c1, row, col = d[0] & 0x0F, d[1] & 0x0F, d[2] & 0x1F, d[3] & 0x3F + for r in range(12): + for b in range(6): + x, y = col * 6 + b, row * 12 + r + if x < W and y < H: + v = c1 if d[4 + r] & (0x20 >> b) else c0 + px[y * W + x] = v ^ px[y * W + x] if ins == 38 else v + elif ins in (30, 31): # load color table lo / hi + for k in range(8): + hi, lo = d[2 * k] & 0x3F, d[2 * k + 1] & 0x3F + pal[(0 if ins == 30 else 8) + k] = ( + ((hi >> 2) & 0xF) * 17, + (((hi & 3) << 2) | ((lo >> 4) & 3)) * 17, + (lo & 0xF) * 17, + ) + img = Image.new("RGB", (W, H)) + img.putdata([pal[c] for c in px]) + return img + + +def rows_with(img: Image.Image, color) -> list: + return sorted({y for y in range(H) for x in range(W) if img.getpixel((x, y)) == color}) + + +def _styles(tmp_path, **overrides) -> dict: + black = tmp_path / "black.png" + Image.new("RGB", (W, H), (0, 0, 0)).save(black) + styles = { + "title_color": "#ffff00", "artist_color": "#ffff00", "background_color": "#000000", + "border_color": "#000000", "font_path": _font("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": str(black), + "instrumental_background": str(black), "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": str(black), "outro_transition": "wipein", + "outro_text_line1": "$title", "outro_text_line2": "$artist", "outro_line1_color": "#ffff00", + "outro_line2_color": "#ffff00", "outro_line1_line2_gap": 10, + } + styles.update(overrides) + return styles + + +def render(tmp_path, title, artist, **overrides) -> str: + audio = tmp_path / "silence.mp3" + if not audio.exists(): + subprocess.run( + ["ffmpeg", "-loglevel", "error", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo", "-t", "16", "-q:a", "9", str(audio)], + check=True, + ) + lrc = tmp_path / "test.lrc" + lrc.write_text("[00:08.000]1:/HELLO \n[00:08.500]1:WORLD \n[00:10.000]1:/SECOND \n[00:10.500]1:LINE \n") + out_dir = tmp_path / "out" + out_dir.mkdir(exist_ok=True) + gen = CDGGenerator(output_dir=str(out_dir)) + cdg_file, _, _ = gen.generate_cdg_from_lrc(str(lrc), str(audio), title, artist, _styles(tmp_path, **overrides)) + return cdg_file + + +class TestTitleCard: + def test_default_layout_has_no_separator(self, tmp_path): + frame = decode_frame(render(tmp_path, "Hello", "World"), 4.8) + assert rows_with(frame, YELLOW), "title/artist should render" + assert not rows_with(frame, WHITE) + + def test_separator_line_renders_between_title_and_artist(self, tmp_path): + cdg = render( + tmp_path, "Abracadabra", "Lady Gaga", + title_separator_text="MADE FAMOUS BY", title_separator_color="#ffffff", + ) + frame = decode_frame(cdg, 4.8) + yellow, white = rows_with(frame, YELLOW), rows_with(frame, WHITE) + assert white, "separator should render in its own colour" + # Title above, artist below the separator. + assert min(yellow) < min(white) and max(white) < max(yellow) + + def test_title_block_top_keeps_text_below_logo_area(self, tmp_path): + cdg = render( + tmp_path, "There's a Kind of Hush (All Over the World)", + "Herman's Hermits & The Very Long Band Name Orchestra", + title_separator_text="MADE FAMOUS BY", title_block_top=60, title_max_height=130, + title_font_size=28, artist_font_size=28, + ) + frame = decode_frame(cdg, 4.8) + text_rows = rows_with(frame, YELLOW) + rows_with(frame, WHITE) + assert min(text_rows) >= 60 + assert max(text_rows) < 204 # inside the CDG safe area + + def test_missing_title_font_falls_back_to_lyrics_font(self, tmp_path): + cdg = render(tmp_path, "Hello", "World", title_font_path="/nope/missing.ttf") + assert rows_with(decode_frame(cdg, 4.8), YELLOW) + + def test_title_font_is_used_for_title_card(self, tmp_path): + oswald = decode_frame(render(tmp_path, "Hello", "World"), 4.8) + avenir = decode_frame( + render(tmp_path, "Hello", "World", title_font_path=_font("AvenirNext-Bold.ttf")), 1.5 + ) + assert list(oswald.getdata()) != list(avenir.getdata()) + + +class TestOutro: + def test_long_outro_text_shrinks_instead_of_crashing(self, tmp_path): + # Previously an assert fired when outro text exceeded 200px. + long = "A Really Quite Extraordinarily Long Song Title That Keeps Going On And On Forever" + cdg = render(tmp_path, long, long + " Featuring Absolutely Everybody", title_block_top=60) + data_len = os.path.getsize(cdg) // 24 + frame = decode_frame(cdg, data_len / CDG_FPS) + rows = rows_with(frame, YELLOW) + assert rows and min(rows) >= 60 diff --git a/tests/unit/test_style_loader.py b/tests/unit/test_style_loader.py index 8b16594b..dcbccd49 100644 --- a/tests/unit/test_style_loader.py +++ b/tests/unit/test_style_loader.py @@ -88,7 +88,11 @@ class TestAssetKeyMappings: def test_font_mapping_is_list(self): """Test that font mapping is a list (maps to multiple sections).""" assert isinstance(ASSET_KEY_MAPPINGS["font"], list) - assert len(ASSET_KEY_MAPPINGS["font"]) == 4 # intro, karaoke, end, cdg + # intro, karaoke, end, cdg lyrics + cdg title card + assert ASSET_KEY_MAPPINGS["font"] == [ + ("intro", "font"), ("karaoke", "font_path"), ("end", "font"), + ("cdg", "font_path"), ("cdg", "title_font_path"), + ] def test_cdg_mappings_exist(self): """Test that CDG-specific mappings exist.""" @@ -771,3 +775,25 @@ class TestScreenEnabled: # existing theme fail validation. assert "enabled" not in DEFAULT_INTRO_STYLE assert "enabled" not in DEFAULT_END_STYLE + + +class TestCdgFontAssets: + """Per-section CDG fonts: main font feeds the CDG title card, cdg_font overrides lyrics.""" + + def _style(self): + return {"intro": {"font": None}, "karaoke": {"font_path": None}, "end": {"font": None}, "cdg": {"font_path": None}} + + def test_main_font_also_sets_cdg_title_font(self): + style = self._style() + update_asset_paths(style, {"font": "/l/main.ttf"}) + assert style["cdg"]["title_font_path"] == "/l/main.ttf" + assert style["cdg"]["font_path"] == "/l/main.ttf" + + @pytest.mark.parametrize("order", [("font", "cdg_font"), ("cdg_font", "font")]) + def test_cdg_font_wins_over_main_font_regardless_of_order(self, order): + paths = {"font": "/l/main.ttf", "cdg_font": "/l/condensed.ttf"} + style = self._style() + update_asset_paths(style, {k: paths[k] for k in order}) + assert style["cdg"]["font_path"] == "/l/condensed.ttf" + assert style["cdg"]["title_font_path"] == "/l/main.ttf" + assert style["karaoke"]["font_path"] == "/l/main.ttf"