diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 94c578b7..591012f3 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -2,6 +2,7 @@ // do (see credentials.ts). The file default-exports a plain object; `import type { ShipConfig }` is optional. import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { validateCapture } from '../shots/devices'; export type ProductType = 'consumable' | 'non_consumable'; @@ -89,13 +90,100 @@ export interface ShotsConfig { /** Phone screen size of the raw frames in CSS px (default 440 x 902, iPhone 6.9" minus the 54 px status bar). */ phone?: { w: number; h: number; dpr?: number }; tablet?: { w: number; h: number; dpr?: number }; - /** Optional capture of raw frames from a running build of your game. */ - capture?: { - baseUrl: string; - /** Appended to every URL, e.g. "noads=1&noanalytics=1". "{lang}" is replaced. */ - query?: string; - shots: Record; + /** Optional capture of raw frames (web build, iOS Simulator, Android emulator / device, or your own folder). */ + capture?: ShotsCapture; + /** A/B variants: other scene orders / copy, rendered into ///... (`shots render --variant b`). */ + variants?: Record; + /** App preview / promo video from gameplay clips (`shots record`, `shots video`). */ + video?: VideoConfig; +} + +/** One raw frame. Web: `path` (+ query). Simulator / emulator: `url` deep link and / or `args` / `extras`. */ +export interface ShotSpec { + /** Web: URL path after baseUrl, "{lang}" replaced. */ + path?: string; + /** ios-sim / android-emu: deep link opened after launch, e.g. "mygame://shot/{shot}?lang={lang}". */ + url?: string; + /** Web: JS expression polled until true. */ + waitFor?: string; + /** Wait before the screenshot (ms). Default 1000 (web) / 2500 (simulator, emulator). */ + delayMs?: number; + /** Web: JS run in the page before the screenshot. */ + eval?: string[]; + device?: 'phone' | 'tablet' | 'both'; + /** ios-sim: extra launch arguments, e.g. ["-shotScene", "{shot}", "-seed", "1"] (read them with UserDefaults / your engine). */ + args?: string[]; + /** android-emu: intent extras for `am start` (string / int / float / boolean), "{lang}" replaced in strings. */ + extras?: Record; +} + +export interface ShotsCapture { + /** Where frames come from. Default "web". */ + source?: 'web' | 'ios-sim' | 'android-emu' | 'folder'; + /** web: URL of the running game, e.g. http://127.0.0.1:5173 */ + baseUrl?: string; + /** web: appended to every URL, e.g. "lang={lang}&noads=1". */ + query?: string; + ios?: { + /** Simulator name or UDID for phone shots, e.g. "iPhone 17 Pro Max" (6.9"). */ + device?: string; + devices?: { phone?: string; tablet?: string }; + bundleId: string; + /** Optional .app to install first (a Simulator build: xcodebuild -sdk iphonesimulator, Unity / Godot / Flutter export). */ + app?: string; + /** Launch arguments for every shot ("{lang}", "{shot}" replaced). */ + args?: string[]; + /** Status bar override 9:41, full battery and signal. Default true. */ + statusBar?: boolean; }; + android?: { + /** adb serial (adb devices); default: the only device. */ + serial?: string; + serials?: { phone?: string; tablet?: string }; + package: string; + /** Launch activity when a shot has no deep link. Default ".MainActivity". */ + activity?: string; + /** Optional APK to install first. */ + apk?: string; + /** System UI demo mode (clean status bar). Default true. */ + demoMode?: boolean; + /** Per-app language via `cmd locale set-app-locales` (Android 13+). Default true. */ + appLocale?: boolean; + }; + /** folder: where your frames are (default shots.frames): ///.png */ + folder?: string; + /** Rows cut from the top of a simulator / emulator screenshot (its status bar; the template draws one). Default: about 5.6 % of the height. */ + cropTop?: number; + shots: Record; +} + +export interface ShotVariant { + /** Scene ids in the order this variant shows them (a subset is fine). Default: the base order. */ + scenes?: string[]; + /** Copy file merged over the base copy per language and scene (only the scenes / fields that change). */ + copy?: string; + /** Palette per scene id. */ + palettes?: Record; +} + +export interface VideoConfig { + /** Gameplay clips: //*.mp4|mov, or /*.mp4|mov shared by every language. Default store/video/clips. */ + clips?: string; + /** Target length in seconds (15-30 for App Store previews). Default 25. */ + seconds?: number; + /** Outputs: iphone (886x1920), ipad (1200x1600, iPad apps), youtube (1080x1920), youtube-landscape (1920x1080). */ + targets?: string[]; + /** Caption overlays from the screenshot copy (scene titles), one per clip. Default true. */ + captions?: boolean; + /** Scene ids whose titles caption the clips, in order. Default: the scene order. */ + captionScenes?: string[]; + /** Music / sound file mixed in (looped, faded out). Default: a silent stereo track (Apple wants an audio track). */ + audio?: string; + /** Poster frame time in seconds (App Store shows it before playback). Default 5. */ + poster?: number; + /** cover (crop to fill, default) or contain (letterbox on `background`). */ + fit?: 'cover' | 'contain'; + background?: string; } export interface IconsConfig { @@ -140,7 +228,11 @@ export interface ShipConfig { contactEmail: string; }; languages: Language[]; - play?: { packageName: string; defaultLanguage?: string; listing?: string; icon?: string }; + play?: { + packageName: string; defaultLanguage?: string; listing?: string; icon?: string; + /** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */ + video?: string; + }; apple?: { bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; /** @@ -149,8 +241,10 @@ export interface ShipConfig { * to skip the question: a wrong answer is a legal problem, not a store one. Unset = storebound will not answer. */ usesNonExemptEncryption?: boolean; - /** Screenshot display types every locale must have (validate). Default ["APP_IPHONE_67"]; add "APP_IPAD_PRO_3GEN_129" for iPad apps. */ + /** Screenshot display types every locale must have (validate). Default ["APP_IPHONE_67"] (+ "APP_IPAD_PRO_3GEN_129" with ipad). */ screenshotTypes?: string[]; + /** The app runs on iPad: renders, checks and uploads 13" iPad screenshots (2064 x 2752) and iPad app previews. */ + ipad?: boolean; }; products?: Product[]; dataSafety?: DataSafety; @@ -191,6 +285,8 @@ export function validateConfig(c: unknown): string[] { ids.add(l.id); } if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)'); + if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video)) + e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters'); if (cfg.apple) { if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)'); if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)'); @@ -233,6 +329,21 @@ export function validateConfig(c: unknown): string[] { for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`); if (!s.scenes?.length) e.push('shots.scenes: at least one scene'); for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`); + e.push(...validateCapture(s.capture)); + const sceneIds = new Set((s.scenes ?? []).map(x => x.id)); + for (const [k, v] of Object.entries(s.variants ?? {})) { + if (!/^[a-z0-9][a-z0-9-]*$/.test(k)) e.push(`shots.variants.${k}: lowercase letters, digits, "-" (it is a folder name)`); + if (cfg.languages?.some(l => l.id === k)) e.push(`shots.variants.${k}: same name as a language id`); + for (const id of v.scenes ?? []) if (!sceneIds.has(id)) e.push(`shots.variants.${k}.scenes: unknown scene "${id}"`); + for (const id of Object.keys(v.palettes ?? {})) if (!sceneIds.has(id)) e.push(`shots.variants.${k}.palettes: unknown scene "${id}"`); + } + if (s.video) { + const v = s.video; + if (v.seconds !== undefined && !(v.seconds >= 15 && v.seconds <= 30)) e.push('shots.video.seconds: 15-30 (App Store app preview length)'); + for (const t of v.targets ?? []) if (!['iphone', 'ipad', 'youtube', 'youtube-landscape'].includes(t)) e.push(`shots.video.targets: unknown "${t}" (iphone, ipad, youtube, youtube-landscape)`); + if (v.fit && !['cover', 'contain'].includes(v.fit)) e.push('shots.video.fit: cover | contain'); + for (const id of v.captionScenes ?? []) if (!sceneIds.has(id)) e.push(`shots.video.captionScenes: unknown scene "${id}"`); + } } if (cfg.icons) { if (!cfg.icons.composite) e.push('icons.composite: missing'); diff --git a/cli/shots/caption.html b/cli/shots/caption.html new file mode 100644 index 00000000..080e03ca --- /dev/null +++ b/cli/shots/caption.html @@ -0,0 +1,42 @@ + + + + + + + + + +
+ + + diff --git a/cli/shots/capture.ts b/cli/shots/capture.ts index 32aa8f02..70a5fb0c 100644 --- a/cli/shots/capture.ts +++ b/cli/shots/capture.ts @@ -1,53 +1,187 @@ -// Raw frames from a running build of your game (headless Chromium, mobile viewport, touch, device scale). -// storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] -// Each entry of shots.capture.shots: { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }. -// URL = baseUrl + path + (? or &) + query, with "{lang}" replaced. Frames go to ///.png. -// The frame is the screen BELOW the status bar (the template draws one), so the viewport is phone.w x phone.h. -// Tip: give your game URL switches for screenshots (fixed seed, no ads, no tutorial, freeze at a moment). -import { mkdirSync } from 'node:fs'; +// Raw frames from a running build of your game, from any engine. +// storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder] +// Frames go to ///.png: the screen BELOW the status bar (the template draws one). +// shots.capture.source (default web): +// web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot: +// { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }; URL = baseUrl + path + +// query, "{lang}" replaced. +// ios-sim xcrun simctl: boots the simulator (ios.device / ios.devices.tablet), optional install of ios.app, status +// bar 9:41 / full battery / full bars, then per shot: launch ios.bundleId with -AppleLanguages (xx) +// -AppleLocale + ios.args + shot.args, open shot.url (deep link) if given, wait, `simctl io screenshot`. +// android-emu adb: demo mode status bar, per-app language (Android 13+, `cmd locale set-app-locales`), then per shot +// force-stop + `am start` with shot.url (VIEW intent) or the launch activity + shot.extras, wait, +// `exec-out screencap -p`. Works on an emulator or a USB device. Nothing is wiped or rebooted. +// folder your own frames (any tool, any engine): only checks that every frame the scenes use exists with the +// right aspect ratio and resolution. +// Simulator / emulator screenshots are full screen: cropTop rows (the status bar) are cut so the frame fits the template. +// The game needs switches for this: language, scene, fixed seed, no ads / tutorial, freeze. See the store-screenshots skill. +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import type { ShipConfig } from '../lib/config'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; import { done, log, warn } from '../lib/log'; import { launch } from './browser'; +import { checkFrameFolder } from './check'; +import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbScreencapArgs, adbStartArgs, cropArgs, defaultCropTop, pickSimulator, + shotsFor, simLaunchArgs, simOpenUrlArgs, simScreenshotArgs, simStatusBarArgs, type Source } from './devices'; import { DEFAULT_PHONE, DEFAULT_TABLET } from './lib'; +import { imageInfo } from './spec'; + +type Device = 'phone' | 'tablet'; + +export function sh(cmd: string, args: string[], o: { allowFail?: boolean; timeout?: number } = {}): { out: Buffer; err: string; code: number } { + const r = spawnSync(cmd, args, { timeout: o.timeout ?? 120_000, maxBuffer: 256 * 1024 * 1024 }); + const code = r.status ?? 1; + if (code !== 0 && !o.allowFail) throw new Error(`${cmd} ${args.slice(0, 6).join(' ')} -> exit ${code}: ${(r.stderr?.toString() || r.error?.message || '').trim().slice(0, 400)}`); + return { out: r.stdout ?? Buffer.alloc(0), err: r.stderr?.toString() ?? '', code }; +} + +/** adb from ANDROID_HOME / ANDROID_SDK_ROOT / the default SDK folder, else PATH. */ +export function adbPath(): string { + const sdk = process.env.ANDROID_HOME ?? process.env.ANDROID_SDK_ROOT ?? join(homedir(), process.platform === 'darwin' ? 'Library/Android/sdk' : 'Android/Sdk'); + const p = join(sdk, 'platform-tools', process.platform === 'win32' ? 'adb.exe' : 'adb'); + return existsSync(p) ? p : 'adb'; +} + +/** Language ids -> the locale each source should use (App Store locale for iOS, first Play code for Android). */ +function localeOf(config: ShipConfig, lang: string, source: Source): string { + const l = config.languages.find(x => x.id === lang); + if (source === 'ios-sim') return l?.apple ?? lang; + const p = l?.play; + return (Array.isArray(p) ? p[0] : p) ?? lang; +} + +/** Crop the status bar off a full-screen capture and store it as a frame. */ +function storeFrame(tmp: string, out: string, cropTop: number | undefined): void { + const h = imageInfo(readFileSync(tmp)).h; + if (!h) throw new Error('screenshot is not a PNG'); + sh('ffmpeg', cropArgs(tmp, out, cropTop ?? defaultCropTop(h))); + rmSync(tmp, { force: true }); +} export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const shots = need(config.shots, 'shots'); const cap = need(shots.capture, 'shots.capture'); const a = ctx.args; + const source = (a.get('source') ?? cap.source ?? 'web') as Source; const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id); const only = a.list('only'); - const devices = a.get('device') ? [a.get('device') as 'phone' | 'tablet'] : (['phone', 'tablet'] as const); - const dims = { phone: { ...DEFAULT_PHONE, ...shots.phone }, tablet: { ...DEFAULT_TABLET, ...shots.tablet } }; - const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] }); - let failed = 0; - try { - for (const lang of langs) for (const device of devices) for (const [name, s] of Object.entries(cap.shots)) { - if (only.length && !only.includes(name)) continue; - const want = s.device ?? 'phone'; - if (want !== 'both' && want !== device) continue; - const d = dims[device]; - const out = resolve(join(shots.frames, lang, device)); - mkdirSync(out, { recursive: true }); - const q = (cap.query ?? '').replaceAll('{lang}', lang); - const url = cap.baseUrl.replace(/\/$/, '') + s.path.replaceAll('{lang}', lang) + (q ? (s.path.includes('?') ? '&' : '?') + q : ''); - const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: lang }); - const page = await c.newPage(); - const errs: string[] = []; - page.on('pageerror', (e: Error) => errs.push(e.message)); - try { - await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 }); - if (s.waitFor) await page.waitForFunction(s.waitFor, null, { timeout: 120000, polling: 50 }); - for (const js of s.eval ?? []) await page.evaluate(js); - await page.waitForTimeout(s.delayMs ?? 1000); - await page.screenshot({ path: join(out, `${name}.png`) }); - log('shots', `${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`); - } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } - await c.close(); + const devices: Device[] = a.get('device') ? [a.get('device') as Device] : ['phone', 'tablet']; + const framesDir = resolve(shots.frames); + const tmpDir = join(root, '.storebound', 'tmp'); + mkdirSync(tmpDir, { recursive: true }); + const target = (lang: string, device: Device, name: string) => { const d = join(framesDir, lang, device); mkdirSync(d, { recursive: true }); return join(d, `${name}.png`); }; + let failed = 0, n = 0; + + if (source === 'folder') { + const dir = resolve(cap.folder ?? shots.frames); + const issues = checkFrameFolder(config, dir, langs); + for (const i of issues) warn('shots', `frames/${i.file}: ${i.msg}`); + if (issues.length) throw new Error(`${issues.length} frame problems in ${dir} (expected //.png)`); + if (dir !== framesDir) warn('shots', `frames are read from shots.frames (${shots.frames}); point it at ${cap.folder} or copy them there`); + return done('shots', `folder frames ok: ${dir}`); + } + + if (source === 'web') { + const dims = { phone: { ...DEFAULT_PHONE, ...shots.phone }, tablet: { ...DEFAULT_TABLET, ...shots.tablet } }; + const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] }); + try { + for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) { + const d = dims[device]; + const q = (cap.query ?? '').replaceAll('{lang}', lang); + const path = (s.path ?? '/').replaceAll('{lang}', lang); + const url = need(cap.baseUrl, 'shots.capture.baseUrl').replace(/\/$/, '') + path + (q ? (path.includes('?') ? '&' : '?') + q : ''); + const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: lang }); + const page = await c.newPage(); + const errs: string[] = []; + page.on('pageerror', (e: Error) => errs.push(e.message)); + try { + await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 }); + if (s.waitFor) await page.waitForFunction(s.waitFor, null, { timeout: 120000, polling: 50 }); + for (const js of s.eval ?? []) await page.evaluate(js); + await page.waitForTimeout(s.delayMs ?? 1000); + await page.screenshot({ path: target(lang, device, name) }); + n++; + log('shots', `${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`); + } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + await c.close(); + } + } finally { await browser.close(); } + } + + if (source === 'ios-sim') { + const ios = need(cap.ios, 'shots.capture.ios'); + const list = sh('xcrun', ['simctl', 'list', 'devices', '-j']).out.toString(); + for (const device of devices) { + const want = device === 'tablet' ? ios.devices?.tablet : ios.devices?.phone ?? ios.device; + const todo = shotsFor(cap, device, only); + if (!todo.length) continue; + if (!want) { warn('shots', `no ios.devices.${device}: ${todo.length} ${device} shots skipped`); continue; } + const sim = pickSimulator(list, want); + if (!sim) throw new Error(`no simulator "${want}" (xcrun simctl list devices)`); + if (sim.state !== 'Booted') { + log('shots', `booting ${sim.name} (${sim.udid})`); + sh('xcrun', ['simctl', 'boot', sim.udid], { allowFail: true }); + sh('xcrun', ['simctl', 'bootstatus', sim.udid, '-b'], { timeout: 300_000 }); + } + if (ios.app) { log('shots', `installing ${ios.app}`); sh('xcrun', ['simctl', 'install', sim.udid, resolve(ios.app)], { timeout: 300_000 }); } + if (ios.statusBar !== false) sh('xcrun', simStatusBarArgs(sim.udid)); + for (const lang of langs) for (const [name, s] of todo) { + try { + const locale = localeOf(config, lang, 'ios-sim'); + sh('xcrun', simLaunchArgs(sim.udid, ios.bundleId, { lang, locale, shot: name, baseArgs: ios.args, args: s.args })); + if (s.url) { await Bun.sleep(1500); sh('xcrun', simOpenUrlArgs(sim.udid, s.url.replaceAll('{lang}', lang).replaceAll('{shot}', name))); } + await Bun.sleep(s.delayMs ?? 2500); + const tmp = join(tmpDir, `sim-${name}.png`); + sh('xcrun', simScreenshotArgs(sim.udid, tmp)); + storeFrame(tmp, target(lang, device, name), cap.cropTop); + n++; + log('shots', `${lang}/${device}/${name}.png (${sim.name})`); + } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + } } - } finally { await browser.close(); } - if (failed) throw new Error(`${failed} captures failed`); - done('shots', 'capture done'); + } + + if (source === 'android-emu') { + const and = need(cap.android, 'shots.capture.android'); + const adb = adbPath(); + for (const device of devices) { + const todo = shotsFor(cap, device, only); + if (!todo.length) continue; + const serial = device === 'tablet' ? and.serials?.tablet : and.serials?.phone ?? and.serial; + if (device === 'tablet' && !serial) { warn('shots', `no android.serials.tablet: ${todo.length} tablet shots skipped`); continue; } + const state = sh(adb, [...(serial ? ['-s', serial] : []), 'get-state'], { allowFail: true }); + if (state.code !== 0) throw new Error(`no Android device${serial ? ` ${serial}` : ''} (adb devices): start an emulator or plug in a device`); + if (and.apk) { log('shots', `installing ${and.apk}`); sh(adb, [...(serial ? ['-s', serial] : []), 'install', '-r', resolve(and.apk)], { timeout: 300_000 }); } + if (and.demoMode !== false) for (const args of adbDemoModeArgs(serial)) sh(adb, args, { allowFail: true }); + for (const lang of langs) { + const locale = localeOf(config, lang, 'android-emu'); + if (and.appLocale !== false) { + const r = sh(adb, adbAppLocaleArgs(and.package, locale, serial), { allowFail: true }); + if (r.code !== 0) warn('shots', `per-app language needs Android 13+; set the language from a launch extra instead (${r.err.trim().slice(0, 120)})`); + } + for (const [name, s] of todo) { + try { + sh(adb, adbForceStopArgs(and.package, serial)); + sh(adb, adbStartArgs(and.package, { lang, locale, shot: name, url: s.url, activity: and.activity, extras: s.extras }, serial)); + await Bun.sleep(s.delayMs ?? 2500); + const tmp = join(tmpDir, `adb-${name}.png`); + writeFileSync(tmp, sh(adb, adbScreencapArgs(serial)).out); + storeFrame(tmp, target(lang, device, name), cap.cropTop); + n++; + log('shots', `${lang}/${device}/${name}.png${serial ? ` (${serial})` : ''}`); + } catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); } + } + } + if (and.demoMode !== false) sh(adb, adbDemoExitArgs(serial), { allowFail: true }); + } + } + + if (!existsSync(framesDir)) mkdirSync(framesDir, { recursive: true }); + if (failed) throw new Error(`${failed} captures failed (${n} ok)`); + done('shots', `capture done: ${n} frames from ${source}`); } diff --git a/cli/shots/check.ts b/cli/shots/check.ts new file mode 100644 index 00000000..ec82b558 --- /dev/null +++ b/cli/shots/check.ts @@ -0,0 +1,61 @@ +// Local store checks of the renders folder, before any upload: +// storebound shots check [--lang en,tr] [--variants] [--json] +// Per image: exact pixel size for its store type, no alpha (both stores), Play: no palette PNG, 8 MB per screenshot. +// Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic. +// Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set. +// Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame +// the scenes use must exist with the right aspect. Exit 1 on any error (warnings do not fail). +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { ShipConfig } from '../lib/config'; +import type { Ctx } from '../lib/ctx'; +import { log } from '../lib/log'; +import { checkFrames, type FrameIssue } from './devices'; +import { DEFAULT_PHONE, DEFAULT_TABLET, defaultSizes, SIZES } from './lib'; +import { allIssues, requiredSets, type RendersScan, scanRenders } from './report'; +import { imageInfo } from './spec'; + +/** Frame files the scenes (and the feature graphic) use, per language and device class. */ +export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] { + const shots = config.shots!; + const sizes = defaultSizes(config); + const devices: ('phone' | 'tablet')[] = ['phone', ...(sizes.some(s => SIZES[s]!.device === 'tablet') ? ['tablet' as const] : [])]; + const scene = [...new Set(shots.scenes.flatMap(s => s.frames.map(f => f.src)))]; + const phone = [...new Set([...scene, ...(shots.feature?.frame && sizes.includes('feature') ? [shots.feature.frame] : [])])]; + return langs.flatMap(lang => devices.flatMap(device => (device === 'phone' ? phone : scene).map(name => ({ lang, device, name })))); +} + +export function checkFrameFolder(config: ShipConfig, dir: string, langs: string[]): FrameIssue[] { + const found = new Map(); + for (const lang of langs) for (const device of ['phone', 'tablet']) { + const d = join(dir, lang, device); + if (!existsSync(d)) continue; + for (const f of readdirSync(d).filter(x => /\.png$/i.test(x))) { const i = imageInfo(readFileSync(join(d, f))); found.set(`${lang}/${device}/${f}`, i); } + } + const s = config.shots!; + return checkFrames(found, framesNeeded(config, langs), { phone: { ...DEFAULT_PHONE, ...s.phone }, tablet: { ...DEFAULT_TABLET, ...s.tablet } }); +} + +export function scanProject(ctx: Ctx): RendersScan { + const { config, resolve } = ctx.loaded; + const langs = ctx.args.list('lang').length ? ctx.args.list('lang') : config.languages.map(l => l.id); + const dir = resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'); + return scanRenders(dir, { langs, variants: Object.keys(config.shots?.variants ?? {}), required: requiredSets(config) }); +} + +export async function run(ctx: Ctx): Promise { + const { config, resolve } = ctx.loaded; + const scan = scanProject(ctx); + const issues = allIssues(scan); + const cap = config.shots?.capture; + const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : []; + if (ctx.args.has('json')) { + console.log(JSON.stringify({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues }, null, 2)); + } else { + for (const { where, issue } of issues) console.log(`${issue.level === 'error' ? 'ERROR' : 'warn '} ${where}: ${issue.msg}`); + for (const f of frameIssues) console.log(`ERROR frames/${f.file}: ${f.msg}`); + } + const errors = issues.filter(i => i.issue.level === 'error').length + frameIssues.length; + log('shots', `checked ${scan.images.length} images, ${scan.videos.length} videos, ${scan.sets.length} sets: ${errors} errors, ${issues.length - issues.filter(i => i.issue.level === 'error').length} warnings`); + if (errors) process.exitCode = 1; +} diff --git a/cli/shots/devices.ts b/cli/shots/devices.ts new file mode 100644 index 00000000..6127829d --- /dev/null +++ b/cli/shots/devices.ts @@ -0,0 +1,164 @@ +// Capture sources for raw frames, as pure argv builders (tests run them without a simulator or emulator) plus the +// config check. The IO lives in capture.ts / record.ts. +// web Playwright on a running web build (default) +// ios-sim xcrun simctl: boot, status bar override, launch with -AppleLanguages + your launch args / deep link, +// io screenshot. Any engine that builds for the iOS Simulator (Unity, Godot, Flutter, native, Capacitor). +// android-emu adb: demo-mode status bar, per-app language (Android 13+), am start with deep link / extras, +// exec-out screencap. Emulator or a USB device. +// folder bring your own frames: ///.png, checked for size. +import type { ShotsCapture, ShotSpec } from '../lib/config'; + +export type Source = 'web' | 'ios-sim' | 'android-emu' | 'folder'; +export const SOURCES: Source[] = ['web', 'ios-sim', 'android-emu', 'folder']; + +/** "{lang}" (and "{locale}", "{shot}") in deep links, URLs and launch args. */ +export function fill(s: string, v: { lang: string; locale?: string; shot?: string }): string { + return s.replaceAll('{lang}', v.lang).replaceAll('{locale}', v.locale ?? v.lang).replaceAll('{shot}', v.shot ?? ''); +} + +/** Problems with shots.capture (pure). */ +export function validateCapture(c: ShotsCapture | undefined): string[] { + if (!c) return []; + const e: string[] = []; + const src = c.source ?? 'web'; + if (!SOURCES.includes(src)) return [`shots.capture.source: one of ${SOURCES.join(', ')}`]; + if (src === 'web' && !/^https?:\/\//.test(c.baseUrl ?? '')) e.push('shots.capture.baseUrl: http(s) URL of the running game (source web)'); + if (src === 'ios-sim') { + if (!c.ios?.bundleId) e.push('shots.capture.ios.bundleId: bundle id of the app on the simulator (source ios-sim)'); + if (!c.ios?.device && !c.ios?.devices?.phone) e.push('shots.capture.ios.device: simulator name or UDID, e.g. "iPhone 17 Pro Max"'); + } + if (src === 'android-emu' && !c.android?.package) e.push('shots.capture.android.package: application id (source android-emu)'); + if (src !== 'folder' && (!c.shots || !Object.keys(c.shots).length)) e.push('shots.capture.shots: at least one shot'); + for (const [name, s] of Object.entries(c.shots ?? {})) { + if (!/^[A-Za-z0-9._-]+$/.test(name)) e.push(`shots.capture.shots.${name}: name must be a file name (letters, digits, . _ -)`); + if (s.device && !['phone', 'tablet', 'both'].includes(s.device)) e.push(`shots.capture.shots.${name}.device: phone | tablet | both`); + if (src === 'web' && s.path === undefined) e.push(`shots.capture.shots.${name}.path: URL path (source web)`); + if ((src === 'web' || src === 'folder') && (s.args || s.extras)) e.push(`shots.capture.shots.${name}: args / extras only apply to ios-sim / android-emu`); + for (const [k, v] of Object.entries(s.extras ?? {})) { + if (!/^[A-Za-z0-9._-]+$/.test(k)) e.push(`shots.capture.shots.${name}.extras.${k}: key must be letters, digits, . _ -`); + if (!['string', 'number', 'boolean'].includes(typeof v)) e.push(`shots.capture.shots.${name}.extras.${k}: string | number | boolean`); + } + } + if (c.cropTop !== undefined && !(Number.isInteger(c.cropTop) && c.cropTop >= 0)) e.push('shots.capture.cropTop: pixels (integer >= 0)'); + return e; +} + +/** Which shots run on which device class. */ +export function shotsFor(c: ShotsCapture, device: 'phone' | 'tablet', only: string[] = []): [string, ShotSpec][] { + return Object.entries(c.shots ?? {}).filter(([name, s]) => (!only.length || only.includes(name)) && ((s.device ?? 'phone') === 'both' || (s.device ?? 'phone') === device)); +} + +// ---- iOS Simulator (xcrun simctl) ---- + +interface SimDevice { udid: string; name: string; state: string; isAvailable?: boolean } + +/** `simctl list devices -j` -> the device matching a name or UDID: booted first, then the newest runtime. */ +export function pickSimulator(listJson: string, want: string): SimDevice | null { + const j = JSON.parse(listJson) as { devices: Record }; + const runtimes = Object.keys(j.devices).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })); + const all = runtimes.flatMap(r => j.devices[r]!.filter(d => d.isAvailable !== false)); + const hits = all.filter(d => d.udid === want || d.name === want); + return hits.find(d => d.state === 'Booted') ?? hits[0] ?? null; +} + +export const STATUS_BAR = { time: '9:41', batteryState: 'charged', batteryLevel: 100, cellularBars: 4, wifiBars: 3 } as const; + +export function simStatusBarArgs(udid: string): string[] { + return ['simctl', 'status_bar', udid, 'override', '--time', STATUS_BAR.time, '--batteryState', STATUS_BAR.batteryState, + '--batteryLevel', String(STATUS_BAR.batteryLevel), '--cellularMode', 'active', '--cellularBars', String(STATUS_BAR.cellularBars), + '--wifiMode', 'active', '--wifiBars', String(STATUS_BAR.wifiBars)]; +} + +/** Apple locale for -AppleLocale from a language id / App Store locale: "en-US" -> en_US, "tr" -> tr, "zh-Hans" -> zh-Hans. */ +export const appleLocale = (l: string): string => (/^[a-z]{2,3}-[A-Z]{2}$/.test(l) ? l.replace('-', '_') : l); + +/** `simctl launch` for one shot: language via -AppleLanguages / -AppleLocale, then your launch args ({lang} filled). */ +export function simLaunchArgs(udid: string, bundleId: string, o: { lang: string; locale?: string; shot: string; args?: string[]; baseArgs?: string[] }): string[] { + const loc = o.locale ?? o.lang; + const extra = [...(o.baseArgs ?? []), ...(o.args ?? [])].map(a => fill(a, { lang: o.lang, locale: loc, shot: o.shot })); + return ['simctl', 'launch', '--terminate-running-process', udid, bundleId, '-AppleLanguages', `(${loc})`, '-AppleLocale', appleLocale(loc), ...extra]; +} + +export const simOpenUrlArgs = (udid: string, url: string): string[] => ['simctl', 'openurl', udid, url]; +export const simScreenshotArgs = (udid: string, out: string): string[] => ['simctl', 'io', udid, 'screenshot', '--type=png', '--mask=ignored', out]; +export const simRecordArgs = (udid: string, out: string): string[] => ['simctl', 'io', udid, 'recordVideo', '--codec=h264', '--mask=ignored', '--force', out]; + +// ---- Android (adb) ---- + +/** POSIX single-quote for `adb shell` (the remote side runs the string through sh). */ +export const shQuote = (s: string): string => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`); + +const adb = (serial: string | undefined, ...rest: string[]): string[] => [...(serial ? ['-s', serial] : []), ...rest]; + +/** Demo mode: clean, fixed status bar (9:41, full battery, full signal, no notifications). */ +export function adbDemoModeArgs(serial?: string): string[][] { + const b = (cmd: string, ...extra: string[]) => adb(serial, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', cmd, ...extra); + return [ + adb(serial, 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '1'), + b('enter'), + b('clock', '-e', 'hhmm', '0941'), + b('battery', '-e', 'level', '100', '-e', 'plugged', 'false'), + b('network', '-e', 'wifi', 'show', '-e', 'level', '4'), + b('network', '-e', 'mobile', 'show', '-e', 'datatype', 'none', '-e', 'level', '4'), + b('notifications', '-e', 'visible', 'false'), + ]; +} +export const adbDemoExitArgs = (serial?: string): string[] => adb(serial, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'exit'); + +/** BCP 47 tag for Android from a language id / Play code: "en-US" stays, "es-419" stays, "pt_BR" -> pt-BR. */ +export const androidLocale = (l: string): string => l.replace('_', '-'); + +/** Per-app language (Android 13+, API 33): no root, no system locale change. Older devices: set the language in the + * game from a launch extra instead (see `extras` with "{lang}"). */ +export const adbAppLocaleArgs = (pkg: string, lang: string, serial?: string): string[] => adb(serial, 'shell', 'cmd', 'locale', 'set-app-locales', pkg, '--locales', androidLocale(lang)); + +export const adbForceStopArgs = (pkg: string, serial?: string): string[] => adb(serial, 'shell', 'am', 'force-stop', pkg); + +/** `am start` for one shot: a deep link (VIEW intent to the package) or the launch activity, plus typed extras. */ +export function adbStartArgs(pkg: string, o: { lang: string; locale?: string; shot: string; url?: string; activity?: string; extras?: Record }, serial?: string): string[] { + const v = { lang: o.lang, locale: o.locale, shot: o.shot }; + const parts = ['am', 'start', '-W']; + if (o.url) parts.push('-a', 'android.intent.action.VIEW', '-d', fill(o.url, v)); + else parts.push('-n', `${pkg}/${o.activity ?? '.MainActivity'}`); + for (const [k, x] of Object.entries(o.extras ?? {})) { + if (typeof x === 'boolean') parts.push('--ez', k, String(x)); + else if (typeof x === 'number' && Number.isInteger(x)) parts.push('--ei', k, String(x)); + else if (typeof x === 'number') parts.push('--ef', k, String(x)); + else parts.push('--es', k, fill(x, v)); + } + if (o.url) parts.push(pkg); + return adb(serial, 'shell', parts.map(shQuote).join(' ')); +} + +export const adbScreencapArgs = (serial?: string): string[] => adb(serial, 'exec-out', 'screencap', '-p'); +/** screenrecord stops by itself after `seconds` (Android caps it at 180). */ +export const adbRecordArgs = (remote: string, seconds: number, serial?: string): string[] => adb(serial, 'shell', 'screenrecord', '--time-limit', String(Math.min(180, Math.max(1, Math.round(seconds)))), remote); + +// ---- frames ---- + +/** Status bar rows to cut from a full-screen capture so the frame matches the template (which draws its own bar). + * Default: the same share of the height the default phone frame uses (54 of 956 px on a 6.9" iPhone). */ +export const defaultCropTop = (h: number, bar = 54, screen = 956): number => Math.round(h * bar / screen); + +/** ffmpeg argv: crop `top` rows, write 24-bit RGB PNG. */ +export const cropArgs = (inp: string, out: string, top: number): string[] => + ['-v', 'error', '-y', '-i', inp, ...(top > 0 ? ['-vf', `crop=iw:ih-${top}:0:${top}`] : []), '-pix_fmt', 'rgb24', out]; + +export interface FrameIssue { file: string; msg: string } + +/** Folder source: every frame the scenes use must exist per language / device, with the device's aspect ratio + * (within 3 %) and at least the frame's CSS width x 2 pixels wide. */ +export function checkFrames(found: Map, need: { lang: string; device: 'phone' | 'tablet'; name: string }[], + dims: Record<'phone' | 'tablet', { w: number; h: number }>): FrameIssue[] { + const out: FrameIssue[] = []; + for (const n of need) { + const rel = `${n.lang}/${n.device}/${n.name}`; + const f = found.get(rel); + if (!f) { out.push({ file: rel, msg: 'missing' }); continue; } + const d = dims[n.device]; + const want = d.w / d.h, got = f.w / f.h; + if (Math.abs(got / want - 1) > 0.03) out.push({ file: rel, msg: `${f.w}x${f.h} has aspect ${got.toFixed(3)}, ${n.device} frames want ${want.toFixed(3)} (${d.w}x${d.h} or a multiple; crop the status bar)` }); + else if (f.w < d.w * 2) out.push({ file: rel, msg: `${f.w}x${f.h} is small: at least ${d.w * 2} px wide keeps the store images sharp` }); + } + return out; +} diff --git a/cli/shots/lib.ts b/cli/shots/lib.ts index 977a7c7d..13208993 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -1,11 +1,13 @@ // Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data. -import type { Palette, ShotsConfig } from '../lib/config'; +import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config'; -/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), play = Play phone 9:16, - * tab7 / tab10 = Play 7" / 10" tablets (tablet frames), feature = Play feature graphic. */ +/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), ipad13 = 13" iPad + * (APP_IPAD_PRO_3GEN_129, only for apps that run on iPad), play = Play phone 9:16, tab7 / tab10 = Play 7" / 10" + * tablets (tablet frames), feature = Play feature graphic. Rules per size: spec.ts. */ export const SIZES: Record = { ios69: { w: 1320, h: 2868 }, ios65: { w: 1284, h: 2778 }, + ipad13: { w: 2064, h: 2752, device: 'tablet' }, play: { w: 1080, h: 1920 }, tab7: { w: 1080, h: 1920, device: 'tablet' }, tab10: { w: 1440, h: 2560, device: 'tablet' }, @@ -74,3 +76,44 @@ export function validateCopy(copy: CopyFile, shots: ShotsConfig, langs: string[] export const DEFAULT_PHONE = { w: 440, h: 902, dpr: 3, bar: 54 }; export const DEFAULT_TABLET = { w: 800, h: 1240, dpr: 2, bar: 40 }; + +/** Size keys this project renders by default: Apple sizes only with an apple section (iPad only with apple.ipad), + * Play sizes only with a play section (both when neither is configured). */ +export function defaultSizes(config: Pick): string[] { + const apple = !!config.apple || !config.play, play = !!config.play || !config.apple; + return Object.keys(SIZES).filter(k => (k === 'ipad13' ? apple && !!config.apple?.ipad : k.startsWith('ios') ? apple : play)); +} + +/** Scenes of a variant (its order / subset, palette overrides), or the base scenes. */ +export function variantScenes(shots: ShotsConfig, variant?: string): ShotScene[] { + if (!variant) return shots.scenes; + const v = shots.variants?.[variant]; + if (!v) throw new Error(`unknown variant "${variant}" (${Object.keys(shots.variants ?? {}).join(', ') || 'none configured in shots.variants'})`); + const byId = new Map(shots.scenes.map(s => [s.id, s] as const)); + return (v.scenes ?? shots.scenes.map(s => s.id)).map(id => { + const s = byId.get(id); + if (!s) throw new Error(`variant ${variant}: unknown scene ${id}`); + return v.palettes?.[id] ? { ...s, palette: v.palettes[id]! } : s; + }); +} + +/** Base copy with a variant's copy merged over it per language and scene (fields of the variant win). */ +export function mergeCopy(base: CopyFile, over: CopyFile | undefined): CopyFile { + if (!over) return base; + const out: CopyFile = {}; + for (const lang of new Set([...Object.keys(base), ...Object.keys(over)])) { + out[lang] = { ...base[lang] }; + for (const [id, sc] of Object.entries(over[lang] ?? {})) out[lang]![id] = { ...base[lang]?.[id], ...sc } as SceneCopy; + } + return out; +} + +/** Output folder for a language (and variant): / or //. */ +export const renderDir = (out: string, lang: string, variant?: string): string => (variant ? `${out}/${variant}/${lang}` : `${out}/${lang}`); + +/** One caption per clip from the scene titles ("line one line two"), cycling through the scenes. */ +export function captionsFor(copy: Record | undefined, sceneIds: string[], clips: number): string[] { + const titles = sceneIds.map(id => copy?.[id]?.title?.filter(Boolean).join(' ') ?? '').filter(Boolean); + if (!titles.length) return Array.from({ length: clips }, () => ''); + return Array.from({ length: clips }, (_, i) => titles[i % titles.length]!); +} diff --git a/cli/shots/render.ts b/cli/shots/render.ts index 93ebf0ff..cdd4c3d3 100644 --- a/cli/shots/render.ts +++ b/cli/shots/render.ts @@ -1,7 +1,10 @@ // Store screenshots + Play feature graphic at exact pixel sizes, from raw game frames and per-language copy. -// storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--no-sheet] [--port 8792] +// storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--variant b | --variants] +// [--no-sheet] [--port 8792] // Out: ///NN.png (24-bit RGB: Play rejects alpha / palette PNGs), /feature/1024x500.png, -// and /sheet.png (contact sheet of every size, for a quick review). Needs playwright + ffmpeg. +// /sheet.png (contact sheet of every size, for a quick review) and /report.json (text overflow flags +// per image, read by `shots check` and `shots gallery`). Variants go to ///... +// Default sizes: defaultSizes() (ipad13 only with apple.ipad). Needs playwright + ffmpeg. import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; import { join, relative } from 'node:path'; import { spawnSync } from 'node:child_process'; @@ -9,7 +12,8 @@ import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; import { done, log, warn } from '../lib/log'; import { launch } from './browser'; -import { type CopyFile, DEFAULT_PHONE, DEFAULT_TABLET, SIZES, copyText, palette, scriptFont, validateCopy } from './lib'; +import { type CopyFile, DEFAULT_PHONE, DEFAULT_TABLET, SIZES, copyText, defaultSizes, mergeCopy, palette, renderDir, scriptFont, validateCopy, variantScenes } from './lib'; +import { type RenderReport, mergeReport, readReport } from './report'; const TYPES: Record = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' }; @@ -19,12 +23,19 @@ export async function run(ctx: Ctx): Promise { const shots = need(config.shots, 'shots'); const a = ctx.args; const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id); - const sizes = a.list('size').length ? a.list('size') : Object.keys(SIZES); - const sceneIds = a.list('scenes').length ? a.list('scenes') : shots.scenes.map(s => s.id); + const sizes = a.list('size').length ? a.list('size') : defaultSizes(config); for (const s of sizes) if (!SIZES[s]) throw new Error(`unknown size ${s} (${Object.keys(SIZES).join(', ')})`); - const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile; - const problems = validateCopy(copy, shots, langs); - if (problems.length) throw new Error('shots copy:\n ' + problems.join('\n ')); + const variants: (string | undefined)[] = a.has('variants') ? [undefined, ...Object.keys(shots.variants ?? {})] : [a.get('variant')]; + const baseCopy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile; + const jobs = new Map(); + for (const v of variants) { + const scenes = variantScenes(shots, v); + const vc = v && shots.variants?.[v]?.copy ? JSON.parse(readFileSync(resolve(shots.variants[v]!.copy!), 'utf8')) as CopyFile : undefined; + const copy = mergeCopy(baseCopy, vc); + const problems = validateCopy(copy, { ...shots, scenes }, langs); + if (problems.length) throw new Error(`shots copy${v ? ` (variant ${v})` : ''}:\n ` + problems.join('\n ')); + jobs.set(v ?? '', { scenes, copy }); + } const framesDir = resolve(shots.frames), outDir = resolve(shots.out); const fontsDir = join(root, '.storebound', 'fonts'); if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts)'); @@ -40,15 +51,16 @@ export async function run(ctx: Ctx): Promise { const p = decodeURIComponent(url.pathname); if (p === '/job.json') { const lang = url.searchParams.get('lang') ?? ''; + const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!; const text = copyText(lang, copy[lang]); const script = scriptFont(lang, text); const base = { phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name, fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } }; if (url.searchParams.has('feature')) - return Response.json({ ...base, frame: shots.feature?.frame ?? shots.scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? shots.scenes[0]!.palette) }); + return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? scenes[0]!.palette) }); const sid = url.searchParams.get('s') ?? ''; - const scene = shots.scenes.find(s => s.id === sid)!; - const number = shots.scenes.filter(s => !s.hero).indexOf(scene) + 1; + const scene = scenes.find(s => s.id === sid)!; + const number = scenes.filter(s => !s.hero).indexOf(scene) + 1; return Response.json({ ...base, scene, number, palette: palette(scene.palette), copy: copy[lang]?.[sid] ?? {} }); } let file = ''; @@ -70,6 +82,7 @@ export async function run(ctx: Ctx): Promise { page.on('pageerror', (e: Error) => errs.push(e.message)); page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); }); let warnings = 0; + const report: RenderReport = {}; async function shoot(url: string, w: number, h: number, out: string): Promise { errs.length = 0; @@ -79,6 +92,9 @@ export async function run(ctx: Ctx): Promise { await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 }); await page.waitForTimeout(200); const tmp = out + '.tmp.png'; + const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[]; + if (!out.endsWith('sheet.png')) report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')) }; + if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`); await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } }); const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]); rmSync(tmp, { force: true }); @@ -88,20 +104,23 @@ export async function run(ctx: Ctx): Promise { } try { - for (const lang of langs) { + for (const [v, job] of jobs) for (const lang of langs) { + const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id); + const vq = v ? `&v=${encodeURIComponent(v)}` : ''; + const dir = renderDir(outDir, lang, v || undefined); const rows: { size: string; files: string[] }[] = []; for (const size of sizes) { const s = SIZES[size]!; if (s.feature) { - const f = join(outDir, lang, 'feature', '1024x500.png'); - await shoot(`${base}/feature.html?lang=${encodeURIComponent(lang)}`, s.w, s.h, f); + const f = join(dir, 'feature', '1024x500.png'); + await shoot(`${base}/feature.html?lang=${encodeURIComponent(lang)}${vq}`, s.w, s.h, f); rows.push({ size, files: [f] }); continue; } const files: string[] = []; for (const [i, id] of sceneIds.entries()) { - const f = join(outDir, lang, size, `${String(i + 1).padStart(2, '0')}.png`); - await shoot(`${base}/template.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}`, s.w, s.h, f); + const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`); + await shoot(`${base}/template.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${vq}`, s.w, s.h, f); files.push(f); } rows.push({ size, files }); @@ -114,16 +133,19 @@ export async function run(ctx: Ctx): Promise { row.files.forEach((f, i) => { imgs += ``; }); W = Math.max(W, gap + row.files.length * (w + gap)); y += h + gap; } - const sheet = join(outDir, lang, '.sheet.html'); + const sheet = join(dir, '.sheet.html'); await Bun.write(sheet, `${imgs} `); - await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(outDir, lang, 'sheet.png')); + await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(dir, 'sheet.png')); rmSync(sheet, { force: true }); } } } finally { await browser.close(); server.stop(true); + if (Object.keys(report).length) await Bun.write(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n'); } + const flagged = Object.values(report).filter(r => r.overflow.length).length; + if (flagged) warn('shots', `${flagged} images with text overflow flags: storebound shots check / shots gallery`); done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`); } diff --git a/cli/shots/report.ts b/cli/shots/report.ts new file mode 100644 index 00000000..0eefcd18 --- /dev/null +++ b/cli/shots/report.ts @@ -0,0 +1,95 @@ +// Render report + the local checks over a renders folder: exact sizes, alpha, bytes, counts per set, text overflow +// flags from the last render, app preview videos. Shared by `shots check`, `shots gallery` and `validate`. +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { SIZES } from './lib'; +import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec'; + +/** /report.json: path relative to the renders dir -> flags found while rendering. */ +export type RenderReport = Record; + +export function readReport(dir: string): RenderReport { + try { return JSON.parse(readFileSync(join(dir, 'report.json'), 'utf8')) as RenderReport; } catch { return {}; } +} + +/** Newer entries replace older ones per file; keys sorted so the file diffs well. */ +export function mergeReport(old: RenderReport, next: RenderReport): RenderReport { + const all = { ...old, ...next }; + return Object.fromEntries(Object.keys(all).sort().map(k => [k, all[k]!])); +} + +export interface ImageEntry { rel: string; lang: string; variant?: string; size: string; file: string; info: ImageInfo; issues: Issue[] } +export interface VideoEntry { rel: string; lang: string; variant?: string; target: string; file: string; probe: ProbeInfo | null; issues: Issue[] } +export interface SetEntry { lang: string; variant?: string; size: string; count: number; issues: Issue[] } +export interface RendersScan { images: ImageEntry[]; videos: VideoEntry[]; sets: SetEntry[]; variants: string[]; langs: string[] } + +/** Every NN.png|jpg of every size, plus preview//*.mp4|mov, for the given languages (and variants). Reads files; + * `probe` is injectable so tests do not need ffprobe. JPEG copies next to PNGs are checked as their own files but + * counted once per number. */ +export function scanRenders(dir: string, o: { langs: string[]; variants?: string[]; required?: Record; sizes?: string[]; + probe?: (file: string) => ProbeInfo | null }): RendersScan { + const report = readReport(dir); + const out: RendersScan = { images: [], videos: [], sets: [], variants: [], langs: o.langs }; + const probe = o.probe ?? ffprobe; + for (const variant of [undefined, ...(o.variants ?? [])]) { + const vdir = variant ? join(dir, variant) : dir; + if (variant && !existsSync(vdir)) continue; + if (variant) out.variants.push(variant); + for (const lang of o.langs) { + const ldir = join(vdir, lang); + for (const size of o.sizes ?? Object.keys(SIZES)) { + const sdir = join(ldir, size); + const files = existsSync(sdir) ? readdirSync(sdir).filter(f => (size === 'feature' ? /^1024x500\.(png|jpe?g)$/i : /^\d+\.(png|jpe?g)$/i).test(f)).sort() : []; + const numbers = new Set(files.map(f => f.split('.')[0])); + for (const f of files) { + const file = join(sdir, f); + const info = imageInfo(readFileSync(file)); + const rel = (variant ? `${variant}/` : '') + `${lang}/${size}/${f}`; + const issues = checkImage(info, size); + for (const msg of report[rel.replace(/\.jpe?g$/i, '.png')]?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg }); + out.images.push({ rel, lang, variant, size, file, info, issues }); + } + const required = o.required?.[size] ?? false; + if (!files.length && !required) continue; + out.sets.push({ lang, variant, size, count: numbers.size, issues: checkCount(numbers.size, size, required) }); + } + const pdir = join(ldir, 'preview'); + if (!existsSync(pdir)) continue; + for (const target of readdirSync(pdir).filter(t => VIDEO_TARGETS[t])) { + const vids = readdirSync(join(pdir, target)).filter(f => /\.(mp4|mov|m4v)$/i.test(f)).sort(); + if (VIDEO_TARGETS[target]!.store === 'apple' && vids.length > PREVIEW_RULES.maxPerSet) + out.sets.push({ lang, variant, size: `preview/${target}`, count: vids.length, issues: [{ level: 'error', code: 'count', msg: `${vids.length} app previews, at most ${PREVIEW_RULES.maxPerSet} per device size and language` }] }); + for (const f of vids) { + const file = join(pdir, target, f); + const p = probe(file); + out.videos.push({ rel: (variant ? `${variant}/` : '') + `${lang}/preview/${target}/${f}`, lang, variant, target, file, probe: p, + issues: p ? checkVideo(p, target) : [{ level: 'warn', code: 'video', msg: 'not checked (ffprobe missing)' }] }); + } + } + } + } + return out; +} + +export function ffprobe(file: string): ProbeInfo | null { + const r = spawnSync('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', file]); + if (r.status !== 0) return null; + return parseProbe(r.stdout.toString(), statSync(file).size); +} + +/** Which sets the stores require for this config (missing ones are errors, others only checked when present). */ +export function requiredSets(c: { apple?: { ipad?: boolean } | undefined; play?: unknown }): Record { + return { ios69: !!c.apple, ipad13: !!c.apple?.ipad, play: !!c.play, feature: !!c.play }; +} + +export const allIssues = (s: RendersScan): { where: string; issue: Issue }[] => [ + ...s.sets.flatMap(x => x.issues.map(issue => ({ where: `${x.variant ? x.variant + '/' : ''}${x.lang}/${x.size}`, issue }))), + ...s.images.flatMap(x => x.issues.map(issue => ({ where: x.rel, issue }))), + ...s.videos.flatMap(x => x.issues.map(issue => ({ where: x.rel, issue }))), +]; + +export const storeOf = (where: string): 'apple' | 'play' => { + const key = where.split('/').find(p => IMAGE_SPECS[p] || VIDEO_TARGETS[p]) ?? ''; + return (IMAGE_SPECS[key]?.store ?? VIDEO_TARGETS[key]?.store ?? 'apple'); +}; diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts new file mode 100644 index 00000000..b6635a9c --- /dev/null +++ b/cli/shots/spec.ts @@ -0,0 +1,172 @@ +// Store image / video rules as data, plus the pure checks `shots check`, `shots gallery` and `validate` share. +// Sources (checked October 2026): +// Apple screenshots: App Store Connect Help > Reference > Screenshot specifications +// https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications +// Apple app previews: App Store Connect Help > Reference > App preview specifications +// https://developer.apple.com/help/app-store-connect/reference/app-information/app-preview-specifications +// Google Play graphics: Play Console Help "Add preview assets to showcase your app" (answer 9866151) +// https://support.google.com/googleplay/android-developer/answer/9866151 +// No IO here: callers read the bytes (or ffprobe output) and pass them in. + +export type Store = 'apple' | 'play'; + +export interface ImageSpec { + store: Store; + /** What the store calls it (ASC display type or Play image type). */ + type: string; + label: string; + /** Accepted pixel sizes (portrait first). The renderer writes the first one. */ + sizes: [number, number][]; + /** Images per set / per type. */ + min: number; + max: number; + /** Max bytes per file (null = the store does not publish one). */ + maxBytes: number | null; + alpha: false; +} + +const MB = 1024 * 1024; + +/** One entry per render size key (cli/shots/lib.ts SIZES). */ +export const IMAGE_SPECS: Record = { + // Apple accepts 1260x2736, 1290x2796 and 1320x2868 for "iPhone with Dynamic Island (large display)" = 6.9". + ios69: { store: 'apple', type: 'APP_IPHONE_67', label: 'App Store iPhone 6.9"', sizes: [[1320, 2868], [1290, 2796], [1260, 2736]], min: 1, max: 10, maxBytes: null, alpha: false }, + ios65: { store: 'apple', type: 'APP_IPHONE_65', label: 'App Store iPhone 6.5"', sizes: [[1284, 2778], [1242, 2688]], min: 1, max: 10, maxBytes: null, alpha: false }, + // 13" iPad display (iPad Pro M4/M5, iPad Air M2+): required when the app runs on iPad. API display type keeps the old name. + ipad13: { store: 'apple', type: 'APP_IPAD_PRO_3GEN_129', label: 'App Store iPad 13"', sizes: [[2064, 2752], [2048, 2732]], min: 1, max: 10, maxBytes: null, alpha: false }, + play: { store: 'play', type: 'phoneScreenshots', label: 'Play phone', sizes: [[1080, 1920]], min: 2, max: 8, maxBytes: 8 * MB, alpha: false }, + tab7: { store: 'play', type: 'sevenInchScreenshots', label: 'Play 7" tablet', sizes: [[1080, 1920]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, + tab10: { store: 'play', type: 'tenInchScreenshots', label: 'Play 10" tablet', sizes: [[1440, 2560]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, + // Play Console states 1024x500, JPEG or 24-bit PNG (no alpha); the upload dialog caps it at 15 MB. + feature: { store: 'play', type: 'featureGraphic', label: 'Play feature graphic', sizes: [[1024, 500]], min: 1, max: 1, maxBytes: 15 * MB, alpha: false }, +}; + +/** Play screenshots in general (any size the store accepts): 320..3840 px per side, long side at most 2x the short. */ +export function playScreenshotOk(w: number, h: number): boolean { + const lo = Math.min(w, h), hi = Math.max(w, h); + return lo >= 320 && hi <= 3840 && hi <= 2 * lo; +} + +export interface ImageInfo { format: 'png' | 'jpeg' | 'unknown'; w: number; h: number; alpha: boolean; palette: boolean; bytes: number } + +/** Width / height / alpha from the PNG IHDR (+ tRNS) or the JPEG SOF marker. Pure, reads only the buffer. */ +export function imageInfo(b: Uint8Array): ImageInfo { + const bytes = b.length; + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + if (bytes > 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) { + const w = dv.getUint32(16), h = dv.getUint32(20), colorType = b[25]!; + let trns = false; + for (let p = 8; p + 8 <= bytes;) { + const len = dv.getUint32(p), type = String.fromCharCode(b[p + 4]!, b[p + 5]!, b[p + 6]!, b[p + 7]!); + if (type === 'tRNS') { trns = true; break; } + if (type === 'IDAT' || type === 'IEND') break; + p += 12 + len; + } + return { format: 'png', w, h, alpha: colorType === 4 || colorType === 6 || trns, palette: colorType === 3, bytes }; + } + if (bytes > 4 && b[0] === 0xff && b[1] === 0xd8) { + for (let p = 2; p + 9 < bytes;) { + if (b[p] !== 0xff) { p++; continue; } + const m = b[p + 1]!; + if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { p += 2; continue; } + const len = dv.getUint16(p + 2); + if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) + return { format: 'jpeg', w: dv.getUint16(p + 7), h: dv.getUint16(p + 5), alpha: false, palette: false, bytes }; + p += 2 + len; + } + } + return { format: 'unknown', w: 0, h: 0, alpha: false, palette: false, bytes }; +} + +export type IssueLevel = 'error' | 'warn'; +export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video'; msg: string } + +/** Problems with one image for a size key. */ +export function checkImage(info: ImageInfo, sizeKey: string): Issue[] { + const s = IMAGE_SPECS[sizeKey]; + if (!s) return [{ level: 'error', code: 'size', msg: `unknown size key ${sizeKey}` }]; + const out: Issue[] = []; + if (info.format === 'unknown') return [{ level: 'error', code: 'format', msg: 'not a PNG or JPEG' }]; + if (!s.sizes.some(([w, h]) => w === info.w && h === info.h)) + out.push({ level: 'error', code: 'size', msg: `${info.w}x${info.h}, ${s.label} wants ${s.sizes.map(([w, h]) => `${w}x${h}`).join(' or ')}` }); + if (info.alpha) out.push({ level: 'error', code: 'alpha', msg: 'has an alpha channel / transparency (both stores reject it): re-render or flatten to RGB' }); + if (info.palette && s.store === 'play') out.push({ level: 'error', code: 'format', msg: 'palette PNG: Play wants JPEG or 24-bit PNG' }); + if (s.maxBytes !== null && info.bytes > s.maxBytes) + out.push({ level: 'error', code: 'bytes', msg: `${(info.bytes / 1024 / 1024).toFixed(1)} MB > ${s.maxBytes / 1024 / 1024} MB` }); + return out; +} + +/** Problems with how many images a set has. `required` = the store needs this set at all. */ +export function checkCount(n: number, sizeKey: string, required: boolean): Issue[] { + const s = IMAGE_SPECS[sizeKey]!; + if (n === 0) return required ? [{ level: 'error', code: 'count', msg: `no ${s.label} images` }] : []; + if (n < s.min) return [{ level: 'error', code: 'count', msg: `${n} ${s.label} images, at least ${s.min}` }]; + if (n > s.max) return [{ level: s.store === 'apple' ? 'error' : 'warn', code: 'count', msg: `${n} ${s.label} images, at most ${s.max} (${s.store === 'play' ? 'play images uploads the first 8' : 'apple screenshots uploads the first 10'})` }]; + return []; +} + +// ---- app previews (Apple) and promo video (Play takes a YouTube URL, no upload) ---- + +export interface VideoTarget { + /** Folder name under //preview/. */ + key: string; + store: Store; + /** ASC preview type for Apple targets. */ + previewType?: string; + w: number; + h: number; + label: string; +} + +/** 886 x 1920 is accepted for every Dynamic Island / Face ID iPhone class (6.9", 6.5", 6.1"); 1200 x 1600 for 13" iPad. */ +export const VIDEO_TARGETS: Record = { + iphone: { key: 'iphone', store: 'apple', previewType: 'IPHONE_67', w: 886, h: 1920, label: 'App Store iPhone app preview (6.9" / 6.5")' }, + ipad: { key: 'ipad', store: 'apple', previewType: 'IPAD_PRO_3GEN_129', w: 1200, h: 1600, label: 'App Store iPad 13" app preview' }, + youtube: { key: 'youtube', store: 'play', w: 1080, h: 1920, label: 'Play promo video (upload to YouTube, paste the URL)' }, + 'youtube-landscape': { key: 'youtube-landscape', store: 'play', w: 1920, h: 1080, label: 'Play promo video, landscape (YouTube)' }, +}; + +export const PREVIEW_RULES = { minSec: 15, maxSec: 30, maxFps: 30, maxBytes: 500 * 1000 * 1000, maxPerSet: 3 } as const; + +export interface ProbeInfo { + bytes: number; + duration: number; + video?: { codec: string; w: number; h: number; fps: number; profile?: string }; + audio?: { codec: string; channels: number; sampleRate: number }; +} + +/** ffprobe -show_streams -show_format JSON -> ProbeInfo. */ +export function parseProbe(json: string, bytes: number): ProbeInfo { + const j = JSON.parse(json) as { streams?: Record[]; format?: { duration?: string } }; + const v = j.streams?.find(s => s.codec_type === 'video'); + const a = j.streams?.find(s => s.codec_type === 'audio'); + const rate = (r: unknown) => { const [n, d] = String(r ?? '0/1').split('/').map(Number); return d ? n! / d : n!; }; + return { + bytes, duration: Number(j.format?.duration ?? 0), + video: v ? { codec: String(v.codec_name), w: Number(v.width), h: Number(v.height), fps: rate(v.avg_frame_rate ?? v.r_frame_rate), profile: v.profile as string | undefined } : undefined, + audio: a ? { codec: String(a.codec_name), channels: Number(a.channels), sampleRate: Number(a.sample_rate) } : undefined, + }; +} + +/** Problems with an app preview / promo video file for a target. Apple rules apply to Apple targets only. */ +export function checkVideo(p: ProbeInfo, targetKey: string): Issue[] { + const t = VIDEO_TARGETS[targetKey]; + if (!t) return [{ level: 'error', code: 'video', msg: `unknown video target ${targetKey}` }]; + const e: Issue[] = []; + const err = (msg: string) => e.push({ level: 'error', code: 'video', msg }); + if (!p.video) { err('no video stream'); return e; } + if (p.video.w !== t.w || p.video.h !== t.h) err(`${p.video.w}x${p.video.h}, ${t.label} wants ${t.w}x${t.h}`); + if (t.store === 'apple') { + if (p.video.codec !== 'h264') err(`video codec ${p.video.codec}, Apple wants H.264 (or ProRes 422 HQ)`); + if (p.video.fps > PREVIEW_RULES.maxFps + 0.01) err(`${p.video.fps.toFixed(2)} fps > 30`); + if (p.duration < PREVIEW_RULES.minSec - 0.05 || p.duration > PREVIEW_RULES.maxSec + 0.05) err(`${p.duration.toFixed(1)} s, app previews are 15-30 s`); + if (p.bytes > PREVIEW_RULES.maxBytes) err(`${(p.bytes / 1e6).toFixed(0)} MB > 500 MB`); + if (!p.audio) err('no audio track: Apple wants a stereo audio track (a silent one is fine)'); + else { + if (p.audio.channels !== 2) err(`audio has ${p.audio.channels} channel(s), Apple wants stereo`); + if (p.audio.codec !== 'aac' && !p.audio.codec.startsWith('pcm')) err(`audio codec ${p.audio.codec}, Apple wants AAC (or PCM with ProRes)`); + if (![44100, 48000].includes(p.audio.sampleRate)) err(`audio ${p.audio.sampleRate} Hz, Apple wants 44.1 or 48 kHz`); + } + } + return e; +} diff --git a/cli/shots/template.html b/cli/shots/template.html index 1c1fd8a7..cbbd21d8 100644 --- a/cli/shots/template.html +++ b/cli/shots/template.html @@ -5,7 +5,7 @@ @@ -103,9 +103,9 @@
diff --git a/cli/shots/video.ts b/cli/shots/video.ts new file mode 100644 index 00000000..7306243c --- /dev/null +++ b/cli/shots/video.ts @@ -0,0 +1,212 @@ +// App preview (App Store) and promo video (Play, via YouTube) from gameplay clips, with ffmpeg. +// storebound shots video [--lang en,tr] [--target iphone,ipad,youtube] [--seconds 25] [--no-captions] +// Clips: //*.mp4|mov|webm (or /*.* shared by every language), joined in name order. +// Record them with `storebound shots record` (simulator, emulator or web build) or bring your own. +// Out: //preview//01.mp4 + 01-poster.png. Every file is checked afterwards (`shots check` rules): +// iphone 886 x 1920 (accepted for 6.9" / 6.5" / 6.1" iPhones) ipad 1200 x 1600 (13" iPad, only with apple.ipad) +// youtube 1080 x 1920 (or youtube-landscape 1920 x 1080): upload it to YouTube yourself and put the URL in play.video. +// Apple: H.264 High <= level 4.0, 30 fps, 15-30 s, stereo AAC 256 kbps 48 kHz (a silent track when there is no audio), +// <= 500 MB, up to 3 per device size and language. Captions are transparent PNGs rendered from the screenshot copy +// (scene titles) with the same fonts (so RTL / CJK work), overlaid per clip. +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import type { Ctx } from '../lib/ctx'; +import { need } from '../lib/ctx'; +import { done, log, warn } from '../lib/log'; +import { launch } from './browser'; +import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont } from './lib'; +import { ffprobe } from './report'; +import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec'; + +export const CLIP_RE = /\.(mp4|mov|m4v|webm)$/i; + +/** Clip files for a language: // first, else the shared / folder. */ +export function clipFiles(clipsDir: string, lang: string, list: (d: string) => string[] = d => (existsSync(d) ? readdirSync(d) : [])): string[] { + for (const d of [join(clipsDir, lang), clipsDir]) { + const f = list(d).filter(x => CLIP_RE.test(x)).sort(); + if (f.length) return f.map(x => join(d, x)); + } + return []; +} + +export interface ClipPlan { file: string; dur: number; start: number } + +/** Clips in order until `seconds` is filled (the last one is cut). Total below 15 s is an error (App Store minimum). */ +export function planClips(clips: { file: string; dur: number }[], seconds: number): { plan: ClipPlan[]; total: number } { + const want = Math.min(PREVIEW_RULES.maxSec, Math.max(PREVIEW_RULES.minSec, seconds)); + const plan: ClipPlan[] = []; + let t = 0; + for (const c of clips) { + if (t >= want - 0.05) break; + const d = Math.min(c.dur, want - t); + if (d < 0.5) continue; + plan.push({ file: c.file, dur: +d.toFixed(3), start: +t.toFixed(3) }); + t += d; + } + if (t < PREVIEW_RULES.minSec - 0.01) throw new Error(`clips add up to ${t.toFixed(1)} s; app previews need at least 15 s (record longer or more clips)`); + return { plan, total: +t.toFixed(3) }; +} + +export interface VideoJob { + plan: ClipPlan[]; + total: number; + w: number; + h: number; + fps?: number; + fit?: 'cover' | 'contain'; + background?: string; + /** Transparent PNG per clip (same index), shown while that clip plays. */ + captions?: (string | null)[]; + audio?: string; + out: string; +} + +/** The ffmpeg argv for one preview: scale / crop (or pad) every clip to W x H at 30 fps, join, overlay captions, add music + * or a silent stereo track, encode H.264 High 4.0 + AAC 256k 48 kHz stereo, faststart. Pure. */ +export function videoArgs(j: VideoJob): string[] { + const fps = j.fps ?? 30; + const args = ['-v', 'error', '-y']; + for (const c of j.plan) args.push('-i', c.file); + const caps = (j.captions ?? []).map((c, i) => [c, i] as const).filter((x): x is [string, number] => !!x[0]); + for (const [c] of caps) args.push('-i', c); + const audioIdx = j.plan.length + caps.length; + if (j.audio) args.push('-stream_loop', '-1', '-i', j.audio); + else args.push('-f', 'lavfi', '-t', String(j.total), '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000'); + + const fit = (j.fit ?? 'cover') === 'cover' + ? `scale=${j.w}:${j.h}:force_original_aspect_ratio=increase,crop=${j.w}:${j.h}` + : `scale=${j.w}:${j.h}:force_original_aspect_ratio=decrease,pad=${j.w}:${j.h}:(ow-iw)/2:(oh-ih)/2:color=${j.background ?? 'black'}`; + const f: string[] = j.plan.map((c, i) => `[${i}:v]trim=duration=${c.dur},setpts=PTS-STARTPTS,fps=${fps},${fit},setsar=1,format=yuv420p[v${i}]`); + f.push(`${j.plan.map((_, i) => `[v${i}]`).join('')}concat=n=${j.plan.length}:v=1:a=0[base]`); + let last = 'base'; + caps.forEach(([, clip], k) => { + const c = j.plan[clip]!; + const a = +(c.start + Math.min(0.3, c.dur / 6)).toFixed(3), b = +(c.start + c.dur - Math.min(0.25, c.dur / 6)).toFixed(3); + f.push(`[${last}][${j.plan.length + k}:v]overlay=0:0:enable='between(t,${a},${b})'[c${k}]`); + last = `c${k}`; + }); + f.push(`[${last}]format=yuv420p[vout]`); + const fade = Math.min(1.5, j.total / 10); + f.push(`[${audioIdx}:a]atrim=0:${j.total},asetpts=PTS-STARTPTS,aformat=sample_rates=48000:channel_layouts=stereo${j.audio ? `,afade=t=out:st=${+(j.total - fade).toFixed(3)}:d=${fade}` : ''}[aout]`); + args.push('-filter_complex', f.join(';'), '-map', '[vout]', '-map', '[aout]', + '-c:v', 'libx264', '-profile:v', 'high', '-level:v', '4.0', '-pix_fmt', 'yuv420p', '-r', String(fps), + '-b:v', '10M', '-maxrate', '12M', '-bufsize', '24M', + '-c:a', 'aac', '-b:a', '256k', '-ar', '48000', '-ac', '2', + '-t', String(j.total), '-movflags', '+faststart', j.out); + return args; +} + +/** ffmpeg argv for the poster frame PNG. */ +export const posterArgs = (video: string, at: number, out: string): string[] => ['-v', 'error', '-y', '-ss', String(at), '-i', video, '-frames:v', '1', '-pix_fmt', 'rgb24', out]; + +/** App Store Connect previewFrameTimeCode (hours:minutes:seconds:frames) for a time in seconds. */ +export function timeCode(sec: number, fps = 30): string { + const total = Math.max(0, Math.round(sec * fps)); + const f = total % fps, s = Math.floor(total / fps); + const p = (n: number) => String(n).padStart(2, '0'); + return `${p(Math.floor(s / 3600))}:${p(Math.floor(s / 60) % 60)}:${p(s % 60)}:${p(f)}`; +} + +/** Targets for this project: config, else iphone (+ ipad with apple.ipad) and youtube with a play section. */ +export function defaultTargets(c: { apple?: { ipad?: boolean }; play?: unknown; shots?: { video?: { targets?: string[] } } }): string[] { + if (c.shots?.video?.targets?.length) return c.shots.video.targets; + return [...(c.apple || !c.play ? ['iphone'] : []), ...(c.apple?.ipad ? ['ipad'] : []), ...(c.play ? ['youtube'] : [])]; +} + +const duration = (file: string): number => { + const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file]); + const d = Number(r.stdout?.toString().trim()); + if (r.status !== 0 || !(d > 0)) throw new Error(`ffprobe could not read ${file}`); + return d; +}; + +export async function run(ctx: Ctx): Promise { + const { config, root, resolve } = ctx.loaded; + const shots = need(config.shots, 'shots'); + const vc = shots.video ?? {}; + const a = ctx.args; + const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id); + const targets = a.list('target').length ? a.list('target') : defaultTargets(config); + for (const t of targets) if (!VIDEO_TARGETS[t]) throw new Error(`unknown target ${t} (${Object.keys(VIDEO_TARGETS).join(', ')})`); + const seconds = a.num('seconds', vc.seconds ?? 25); + const clipsDir = resolve(vc.clips ?? 'store/video/clips'); + const outDir = resolve(config.renders ?? shots.out); + const captions = vc.captions !== false && !a.has('no-captions'); + const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile; + const sceneIds = vc.captionScenes ?? shots.scenes.map(s => s.id); + const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const)); + const tmp = join(root, '.storebound', 'tmp', 'captions'); + mkdirSync(tmp, { recursive: true }); + + // caption PNGs come from a local page (fonts from `shots fonts`), like the screenshots + let server: ReturnType | null = null, browser: { close(): Promise; newContext(o: unknown): Promise<{ newPage(): Promise }> } | null = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let page: any = null; + if (captions) { + const fontsDir = join(root, '.storebound', 'fonts'); + if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (captions fall back to system fonts)'); + server = Bun.serve({ port: a.num('port', 8793), hostname: '127.0.0.1', async fetch(req) { + const url = new URL(req.url); + if (url.pathname === '/caption.json') { + const lang = url.searchParams.get('lang') ?? ''; + const texts = captionsFor(copy[lang], sceneIds, 64); + const script = scriptFont(lang, copyText(lang, copy[lang])); + const pal = palette(shots.scenes[0]?.palette); + return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: pal.ink, rtl: rtl.get(lang), + fonts: { title: shots.fonts?.title ?? 'Lilita One', script: script ? `Store ${script.slug}` : null } }); + } + if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } }); + if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) { + const f = Bun.file(join(fontsDir, url.pathname.slice(7))); + if (await f.exists()) return new Response(f, { headers: { 'content-type': url.pathname.endsWith('.css') ? 'text/css' : 'font/woff2' } }); + } + return new Response('no', { status: 404 }); + } }); + browser = await launch(root, { headless: true }); + page = await (await browser!.newContext({ deviceScaleFactor: 1 })).newPage(); + } + + let made = 0, bad = 0; + try { + for (const lang of langs) { + const files = clipFiles(clipsDir, lang); + if (!files.length) { warn('shots', `${lang}: no clips in ${clipsDir}/${lang} or ${clipsDir} (storebound shots record)`); continue; } + const { plan, total } = planClips(files.map(file => ({ file, dur: duration(file) })), seconds); + const texts = captions ? captionsFor(copy[lang], sceneIds, plan.length) : []; + for (const key of targets) { + const t = VIDEO_TARGETS[key]!; + const dir = join(renderDir(outDir, lang), 'preview', key); + mkdirSync(dir, { recursive: true }); + const caps: (string | null)[] = []; + if (captions) for (const [i, text] of texts.entries()) { + if (!text) { caps.push(null); continue; } + const png = join(tmp, `${lang}-${key}-${i}.png`); + await page.setViewportSize({ width: t.w, height: t.h }); + await page.goto(`http://127.0.0.1:${server!.port}/caption.html?w=${t.w}&h=${t.h}&lang=${encodeURIComponent(lang)}&i=${i}`, { waitUntil: 'load' }); + await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 }); + await page.screenshot({ path: png, omitBackground: true, clip: { x: 0, y: 0, width: t.w, height: t.h } }); + caps.push(png); + } + const out = join(dir, '01.mp4'); + log('shots', `${lang}/${key}: ${plan.length} clips, ${total.toFixed(1)} s -> ${t.w}x${t.h}`); + const r = spawnSync('ffmpeg', videoArgs({ plan, total, w: t.w, h: t.h, fit: vc.fit, background: vc.background, captions: caps, audio: vc.audio ? resolve(vc.audio) : undefined, out }), { maxBuffer: 64 * 1024 * 1024 }); + if (r.status !== 0) throw new Error(`ffmpeg (${lang}/${key}): ${r.stderr.toString().slice(-800)}`); + const poster = Math.min(vc.poster ?? 5, total - 0.5); + spawnSync('ffmpeg', posterArgs(out, poster, join(dir, '01-poster.png'))); + const probe = ffprobe(out); + const issues = probe ? checkVideo(probe, key) : []; + for (const i of issues) warn('shots', `${lang}/${key}: ${i.msg}`); + if (issues.some(i => i.level === 'error')) bad++; + made++; + log('shots', `${lang}/${key}/01.mp4 ${(statSync(out).size / 1e6).toFixed(1)} MB${issues.length ? '' : ', store checks ok'}${t.store === 'play' ? ' (upload to YouTube, then set play.video)' : ''}`); + } + } + } finally { + await browser?.close(); + server?.stop(true); + rmSync(tmp, { recursive: true, force: true }); + } + if (bad) throw new Error(`${bad} videos fail the store checks`); + done('shots', `video done: ${made} files`); +} diff --git a/package.json b/package.json index bfd11a54..5a458a54 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ }, "devDependencies": { "@types/bun": "1.3.0", + "playwright": "1.55.0", "typescript": "5.9.3" } }