Skip to content

tim-hub/powerball-harness / .claude/skills/generate-video

generate-video

Verified

Generates product demo videos and release walkthroughs via Remotion. Use when creating video documentation or animated demos.

FileKindSize
SKILL.mdskill md6.6 KB
assets/backgrounds/backgrounds.jsonconfig4.9 KB
assets/sounds/sounds.jsonconfig5.7 KB
package.jsonmanifest710 B
references/MIGRATION-11.2.mdmarkdown7.9 KB
references/analyzer.mdmarkdown4.5 KB
references/asset-customization.mdmarkdown11.2 KB
references/best-practices.mdmarkdown8.6 KB
references/direction-guide.mdmarkdown14.6 KB
references/generator.mdmarkdown25.9 KB
references/image-generator.mdmarkdown9.0 KB
references/image-patterns.mdmarkdown14.5 KB
references/image-quality-check.mdmarkdown6.9 KB
references/naming-conventions.mdmarkdown6.0 KB
references/planner.mdmarkdown7.6 KB
references/visual-effects.mdmarkdown11.0 KB
remotion/components/BackgroundLayer.tsxother7.5 KB
remotion/components/EmphasisBox.tsxother5.9 KB
remotion/components/ProgressIndicator.tsxother6.8 KB
remotion/components/README.mdmarkdown8.5 KB
remotion/components/TransitionWrapper.tsxother5.7 KB
remotion/components/index.tsscript1004 B
remotion/tsconfig.jsonconfig617 B
schemas/README.mdmarkdown8.1 KB
schemas/animation.schema.jsonconfig5.2 KB
schemas/assets.manifest.schema.jsonconfig5.9 KB
schemas/character.schema.jsonconfig16.0 KB
schemas/direction.schema.jsonconfig4.5 KB
schemas/emphasis.schema.jsonconfig8.6 KB
schemas/examples/scenario-example.jsonconfig1.6 KB
schemas/examples/scene-example.jsonconfig1.6 KB
schemas/examples/video-script-example.jsonconfig5.1 KB
schemas/examples/visual-patterns/comparison-example.jsonconfig1.0 KB
schemas/examples/visual-patterns/concept-example.jsonconfig2.1 KB
schemas/examples/visual-patterns/flow-example.jsonconfig1.8 KB
schemas/examples/visual-patterns/highlight-example.jsonconfig745 B
schemas/scenario.schema.jsonconfig3.6 KB
schemas/scene.schema.jsonconfig8.2 KB
schemas/validate-schemas-basic.jsscript2.7 KB
schemas/validate-schemas.jsscript6.6 KB
schemas/video-script.schema.jsonconfig7.6 KB
schemas/visual-patterns.schema.jsonconfig14.2 KB
scripts/README.mdmarkdown7.4 KB
scripts/generate-schemas.jsexecutablescript6.2 KB
scripts/load-assets.jsexecutablescript14.1 KB
scripts/merge-scenes.jsexecutablescript15.0 KB
scripts/render-video.jsexecutablescript14.0 KB
scripts/template-registry.jsexecutablescript10.0 KB
scripts/validate-scenario.jsexecutablescript8.0 KB
scripts/validate-scene.jsexecutablescript4.3 KB
scripts/validate-video.jsexecutablescript13.0 KB
src/schemas/animation.tsscript3.7 KB
src/schemas/assets.manifest.tsscript2.8 KB
src/schemas/character.tsscript6.5 KB
src/schemas/direction.tsscript3.2 KB
src/schemas/emphasis.tsscript5.2 KB
src/schemas/index.tsscript423 B
src/schemas/scenario.tsscript2.7 KB
src/schemas/scene.tsscript5.5 KB
src/schemas/video-script.tsscript9.4 KB
src/schemas/visual-patterns.tsscript8.2 KB
src/types/README.mdmarkdown4.1 KB
src/types/components.tsscript6.0 KB
src/types/index.tsscript108 B
src/utils/README.mdmarkdown6.1 KB
src/utils/converters.jsscript5.9 KB
src/utils/converters.tsscript5.7 KB
src/utils/index.tsscript109 B
templates/image-prompts/comparison.txtmarkdown1.3 KB
templates/image-prompts/concept.txtmarkdown2.3 KB
templates/image-prompts/flow.txtmarkdown2.8 KB
templates/image-prompts/highlight.txtmarkdown3.2 KB
templates/intro-3min.jsonconfig8.9 KB
templates/teaser-90s.jsonconfig7.0 KB
tests/asset-loader.test.jsscript12.1 KB
tests/character-schema.test.jsscript7.9 KB
tests/converters.test.jsscript8.3 KB
tests/determinism.test.jsscript11.4 KB
tests/e2e/merge-e2e.test.jsscript13.3 KB
tests/e2e/render.test.jsscript6.1 KB
tests/fixtures/minimal-video-script.jsonconfig1.2 KB
tests/merge-scenes.test.jsscript17.2 KB
tests/schema-validation.test.jsscript3.7 KB
tests/validation-integration.test.jsscript12.9 KB
tests/visual-patterns.test.jsscript12.1 KB

scripts/render-video.js

View on GitHub
#!/usr/bin/env node
/**
 * Render Video Script
 *
 * Converts a video-script.json file to an MP4 video using Remotion.
 *
 * Usage:
 *   node scripts/render-video.js <video-script.json> [--output <path>]
 *
 * Example:
 *   node scripts/render-video.js out/video-script.json --output out/final-video.mp4
 *
 * Dependencies:
 *   - Remotion CLI (npx remotion render)
 *   - video-script.json (validated against schema)
 *
 * Process:
 *   1. Load and validate video-script.json
 *   2. Generate Remotion composition (or use existing)
 *   3. Resolve asset paths
 *   4. Calculate frame counts from durations
 *   5. Call Remotion CLI with appropriate settings
 *   6. Show progress and output final file path
 */

const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const os = require('os');

// ANSI color codes for terminal output
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  dim: '\x1b[2m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function logError(message) {
  log(`\u274c ${message}`, 'red');
}

function logSuccess(message) {
  log(`\u2705 ${message}`, 'green');
}

function logInfo(message) {
  log(`\u2139\ufe0f  ${message}`, 'cyan');
}

function logWarning(message) {
  log(`\u26a0\ufe0f  ${message}`, 'yellow');
}

/**
 * Parse command line arguments
 */
function parseArgs() {
  const args = process.argv.slice(2);

  if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
    console.log(`
${colors.bright}Render Video Script${colors.reset}

Usage:
  node scripts/render-video.js <video-script.json> [options]

Arguments:
  <video-script.json>    Path to video script file

Options:
  --output <path>        Output file path (default: out/video.mp4)
  --composition <name>   Remotion composition name (default: VideoComposition)
  --concurrency <num>    Rendering concurrency (default: 50% CPU cores)
  --quality <level>      Quality: low|medium|high|ultra (default: from script)
  --preview              Generate preview instead of final render
  --skip-validation      Skip video-script.json validation (not recommended)
  --help, -h             Show this help message

Examples:
  node scripts/render-video.js out/video-script.json
  node scripts/render-video.js out/video-script.json --output final.mp4
  node scripts/render-video.js out/video-script.json --preview --quality medium
  node scripts/render-video.js out/video-script.json --skip-validation
    `);
    process.exit(0);
  }

  const scriptPath = args[0];
  const options = {
    output: null,
    composition: 'VideoComposition',
    concurrency: null,
    quality: null,
    preview: false,
    skipValidation: false,
  };

  for (let i = 1; i < args.length; i++) {
    switch (args[i]) {
      case '--output':
        options.output = args[++i];
        break;
      case '--composition':
        options.composition = args[++i];
        break;
      case '--concurrency':
        options.concurrency = parseInt(args[++i], 10);
        break;
      case '--quality':
        options.quality = args[++i];
        break;
      case '--preview':
        options.preview = true;
        break;
      case '--skip-validation':
        options.skipValidation = true;
        break;
      default:
        logWarning(`Unknown option: ${args[i]}`);
    }
  }

  return { scriptPath, options };
}

/**
 * Load and validate video script
 */
function loadVideoScript(scriptPath, options = {}) {
  if (!fs.existsSync(scriptPath)) {
    throw new Error(`Video script not found: ${scriptPath}`);
  }

  const content = fs.readFileSync(scriptPath, 'utf-8');
  const script = JSON.parse(content);

  // Schema validation unless --skip-validation is specified
  if (!options.skipValidation) {
    logInfo('Validating video-script.json against schema...');
    const { validateVideoScript } = require('./validate-video.js');
    const videoSchemaPath = path.join(__dirname, '../schemas/video-script.schema.json');
    const sceneSchemaPath = path.join(__dirname, '../schemas/scene.schema.json');

    const validationResult = validateVideoScript(script, videoSchemaPath, sceneSchemaPath);

    if (!validationResult.valid) {
      logError('Video script validation failed:');
      console.error('');
      validationResult.errors.forEach((error, index) => {
        console.error(`  ${index + 1}. ${error.details || error.message}`);
      });
      console.error('');
      logWarning('Run with --skip-validation to bypass validation (not recommended).');
      throw new Error('Video script validation failed');
    }

    // Display warnings if any
    if (validationResult.warnings && validationResult.warnings.length > 0) {
      logWarning(`${validationResult.warnings.length} warning(s) found:`);
      validationResult.warnings.forEach((warning, index) => {
        console.log(`  ${index + 1}. ${warning.details || warning.message}`);
      });
      console.log('');
    }

    logSuccess('Video script validation passed');
  } else {
    logWarning('Skipping video-script.json validation (--skip-validation)');
  }

  // Basic validation (after schema validation or if validation is skipped)
  if (!script.metadata || !script.scenes || !script.output_settings) {
    throw new Error('Invalid video script: missing required fields (metadata, scenes, output_settings)');
  }

  if (!Array.isArray(script.scenes) || script.scenes.length === 0) {
    throw new Error('Invalid video script: scenes must be a non-empty array');
  }

  return script;
}

/**
 * Validate that resolved path is within allowed roots (Security fix)
 * Prevents path traversal attacks
 */
function isPathWithinRoots(resolvedPath, allowedRoots) {
  const normalizedPath = path.resolve(resolvedPath);
  return allowedRoots.some(root => {
    const normalizedRoot = path.resolve(root);
    return normalizedPath.startsWith(normalizedRoot + path.sep) || normalizedPath === normalizedRoot;
  });
}

/**
 * Resolve asset paths relative to project root
 * Security: Validates paths are within allowed directories
 */
function resolveAssets(script, scriptPath) {
  const scriptDir = path.dirname(path.resolve(scriptPath));
  const projectRoot = process.cwd();

  // Allowed asset roots for security
  const allowedRoots = [scriptDir, projectRoot];

  const resolvedScenes = script.scenes.map(scene => {
    if (!scene.assets || scene.assets.length === 0) {
      return scene;
    }

    const resolvedAssets = scene.assets.map(asset => {
      if (!asset.source) {
        return asset;
      }

      // Security: Reject paths with path traversal attempts
      if (asset.source.includes('..')) {
        logWarning(`Asset path contains '..', rejected for security: ${asset.source}`);
        return asset;
      }

      // Security: Reject absolute paths from untrusted input
      if (path.isAbsolute(asset.source)) {
        logWarning(`Absolute asset paths are not allowed for security: ${asset.source}`);
        return asset;
      }

      // Try relative to script file
      const relativeToScript = path.resolve(scriptDir, asset.source);
      if (isPathWithinRoots(relativeToScript, allowedRoots) && fs.existsSync(relativeToScript)) {
        return { ...asset, source: relativeToScript };
      }

      // Try relative to project root
      const relativeToRoot = path.resolve(projectRoot, asset.source);
      if (isPathWithinRoots(relativeToRoot, allowedRoots) && fs.existsSync(relativeToRoot)) {
        return { ...asset, source: relativeToRoot };
      }

      logWarning(`Asset not found: ${asset.source}`);
      return asset;
    });

    return { ...scene, assets: resolvedAssets };
  });

  return { ...script, scenes: resolvedScenes };
}

/**
 * Calculate total frames from milliseconds
 */
function msToFrames(ms, fps) {
  return Math.ceil((ms / 1000) * fps);
}

/**
 * Get Remotion CLI path
 * Returns { command: string, extraArgs: string[] } for safe spawn usage
 */
function getRemotionCli() {
  // Check if remotion is installed locally
  const localRemotionBin = path.join(process.cwd(), 'node_modules', '.bin', 'remotion');
  if (fs.existsSync(localRemotionBin)) {
    return { command: localRemotionBin, extraArgs: [] };
  }

  // Fallback to npx - split into command and args for shell: false safety
  return { command: 'npx', extraArgs: ['remotion'] };
}

/**
 * Build Remotion CLI command
 */
function buildRenderCommand(script, options) {
  const { output_settings, total_duration_ms } = script;
  const fps = output_settings.fps || 30;
  const totalFrames = msToFrames(total_duration_ms, fps);

  // Determine output path
  const outputPath = options.output || path.join(process.cwd(), 'out', 'video.mp4');
  const outputDir = path.dirname(outputPath);

  // Ensure output directory exists
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
    logInfo(`Created output directory: ${outputDir}`);
  }

  // Build command
  const { command: remotionCommand, extraArgs: remotionExtraArgs } = getRemotionCli();
  const entryPoint = path.join(process.cwd(), 'remotion', 'index.ts');

  // Write props to temp file to avoid CLI argument length limits (Security & Performance fix)
  const propsFile = path.join(os.tmpdir(), `remotion-props-${Date.now()}.json`);
  fs.writeFileSync(propsFile, JSON.stringify({ script }), 'utf-8');

  const args = [
    ...remotionExtraArgs,
    'render',
    entryPoint,
    options.composition,
    outputPath,
    `--props=${propsFile}`,
  ];

  // Add codec
  if (output_settings.codec) {
    args.push(`--codec=${output_settings.codec}`);
  }

  // Add quality settings
  const quality = options.quality || output_settings.quality;
  if (quality) {
    const qualityMap = {
      low: { crf: 28, preset: 'fast' },
      medium: { crf: 23, preset: 'medium' },
      high: { crf: 18, preset: 'slow' },
      ultra: { crf: 15, preset: 'slower' },
    };
    const qualitySettings = qualityMap[quality] || qualityMap.high;
    args.push(`--crf=${qualitySettings.crf}`);
  }

  // Add concurrency
  if (options.concurrency) {
    args.push(`--concurrency=${options.concurrency}`);
  }

  // Add preview mode
  if (options.preview) {
    args.push('--scale=0.5');
    args.push('--every-nth-frame=2');
  }

  return { command: remotionCommand, args, outputPath, totalFrames, fps };
}

/**
 * Execute Remotion render command
 */
function executeRender(command, args) {
  logInfo('Starting Remotion render...');
  const displayCommand = `${command} ${args.join(' ')}`;
  log(`Command: ${displayCommand}`, 'dim');

  try {
    // Use spawn with shell: false for security (prevents command injection)
    // Command is already split properly by getRemotionCli()
    const child = spawn(command, args, {
      stdio: 'inherit',
      shell: false,
    });

    return new Promise((resolve, reject) => {
      child.on('close', (code) => {
        if (code === 0) {
          resolve();
        } else {
          reject(new Error(`Remotion render failed with exit code ${code}`));
        }
      });

      child.on('error', (err) => {
        reject(err);
      });
    });
  } catch (error) {
    throw new Error(`Failed to execute Remotion: ${error.message}`);
  }
}

/**
 * Display render summary
 */
function displaySummary(script, outputPath, renderTimeMs) {
  const { metadata, scenes, output_settings, total_duration_ms } = script;
  const fileStats = fs.existsSync(outputPath) ? fs.statSync(outputPath) : null;
  const fileSizeMB = fileStats ? (fileStats.size / (1024 * 1024)).toFixed(2) : 'N/A';

  log('\n' + '='.repeat(60), 'cyan');
  log('  RENDER COMPLETE', 'bright');
  log('='.repeat(60), 'cyan');

  log('\nšŸ“ Output File:', 'bright');
  log(`   ${outputPath}`, 'green');
  log(`   Size: ${fileSizeMB} MB\n`, 'dim');

  log('šŸ“Š Video Details:', 'bright');
  log(`   Title: ${metadata.title}`);
  log(`   Duration: ${(total_duration_ms / 1000).toFixed(1)}s`);
  log(`   Resolution: ${output_settings.width}x${output_settings.height}`);
  log(`   FPS: ${output_settings.fps}`);
  log(`   Codec: ${output_settings.codec || 'h264'}`);
  log(`   Scenes: ${scenes.length}\n`);

  log('ā±ļø  Performance:', 'bright');
  log(`   Render Time: ${(renderTimeMs / 1000).toFixed(1)}s`);
  log(`   Speed: ${(total_duration_ms / renderTimeMs).toFixed(2)}x realtime\n`);

  log('šŸŽ¬ Next Steps:', 'bright');
  log(`   Preview: open ${outputPath}`);
  log(`   Studio: npm run remotion\n`);

  log('='.repeat(60), 'cyan');
}

/**
 * Main execution
 */
async function main() {
  const startTime = Date.now();

  try {
    // Parse arguments
    const { scriptPath, options } = parseArgs();

    log('\nšŸŽ¬ Video Rendering Pipeline', 'bright');
    log('='.repeat(60) + '\n', 'cyan');

    // Load video script
    logInfo(`Loading video script: ${scriptPath}`);
    const script = loadVideoScript(scriptPath, options);
    logSuccess(`Loaded: ${script.metadata.title}`);

    // Resolve assets
    logInfo('Resolving asset paths...');
    const resolvedScript = resolveAssets(script, scriptPath);
    logSuccess('Assets resolved');

    // Build render command
    logInfo('Building Remotion command...');
    const { command, args, outputPath, totalFrames, fps } = buildRenderCommand(resolvedScript, options);
    logSuccess(`Target: ${outputPath} (${totalFrames} frames @ ${fps}fps)`);

    // Execute render
    log('');
    await executeRender(command, args);
    log('');

    // Display summary
    const renderTime = Date.now() - startTime;
    displaySummary(script, outputPath, renderTime);

    process.exit(0);
  } catch (error) {
    log('');
    logError(`Render failed: ${error.message}`);
    log('');
    log('šŸ” Troubleshooting:', 'yellow');
    log('  1. Check that Remotion is installed: npm install remotion');
    log('  2. Verify video-script.json is valid: node scripts/validate-video.js <file>');
    log('  3. Ensure all assets exist and are accessible');
    log('  4. Check remotion/index.ts has the correct composition');
    log('');
    process.exit(1);
  }
}

// Run if called directly
if (require.main === module) {
  main();
}

module.exports = {
  loadVideoScript,
  resolveAssets,
  msToFrames,
  buildRenderCommand,
};
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 198kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 198kUpdated Claude CodeCodexVerifiedInstall