using System.Diagnostics; using System.Globalization; using ClipForge.Core.Interfaces.Services; using Microsoft.Extensions.Logging; namespace ClipForge.Infrastructure.Services; public class FfmpegService : IFfmpegService { private readonly ILogger _logger; public FfmpegService(ILogger logger) { _logger = logger; } public async Task AssembleVerticalVideoAsync(string audioPath, IReadOnlyList backgroundClips, string outputPath, CancellationToken ct = default) { _logger.LogInformation("Assembling vertical video with {ClipCount} background items", backgroundClips.Count); // Detect if inputs are images or videos var isImages = backgroundClips.All(f => f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".webp", StringComparison.OrdinalIgnoreCase)); if (isImages && backgroundClips.Count > 0) { await AssembleFromImagesAsync(audioPath, backgroundClips, outputPath, ct); } else { await AssembleFromVideosAsync(audioPath, backgroundClips, outputPath, ct); } _logger.LogInformation("Video assembled successfully: {OutputPath}", outputPath); return outputPath; } private async Task AssembleFromImagesAsync(string audioPath, IReadOnlyList images, string outputPath, CancellationToken ct) { _logger.LogInformation("Using Ken Burns effect with {Count} images", images.Count); // Get audio duration to calculate time per image (3-4 seconds each for fast pacing) var audioDuration = await GetMediaDurationAsync(audioPath, ct); if (audioDuration <= 0) audioDuration = 50; var timePerImage = Math.Min(4.0, audioDuration / images.Count); // Max 4s per image var inputArgs = new List(); var filterParts = new List(); for (int i = 0; i < images.Count; i++) { inputArgs.Add($"-loop 1 -t {timePerImage.ToString("F2", CultureInfo.InvariantCulture)} -i \"{images[i]}\""); var frames = (int)(timePerImage * 25); // Varied Ken Burns effects for dynamic feel string zoomEffect = (i % 5) switch { 0 => $"zoompan=z='min(zoom+0.003,1.5)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s=1080x1920:fps=25", // Zoom in center 1 => $"zoompan=z='if(lte(zoom,1.0),1.5,max(1.001,zoom-0.003))':x='iw/2-(iw/zoom/2)':y='ih/3-(ih/zoom/3)':d={frames}:s=1080x1920:fps=25", // Zoom out top 2 => $"zoompan=z='1.3':x='iw/4+((iw/2)*on/{frames})':y='ih/2-(ih/zoom/2)':d={frames}:s=1080x1920:fps=25", // Pan right 3 => $"zoompan=z='min(zoom+0.004,1.6)':x='iw/3-(iw/zoom/3)':y='ih/4-(ih/zoom/4)':d={frames}:s=1080x1920:fps=25", // Zoom in top-left _ => $"zoompan=z='1.3':x='iw/2-(iw/zoom/2)+((iw/4)*sin(on/{frames}*3.14))':y='ih/2-(ih/zoom/2)':d={frames}:s=1080x1920:fps=25", // Sway }; filterParts.Add($"[{i}:v]scale=1920:1920:force_original_aspect_ratio=increase,crop=1080:1920,{zoomEffect},setsar=1[v{i}]"); } // Concatenate all image clips var concatInputs = string.Join("", Enumerable.Range(0, images.Count).Select(i => $"[v{i}]")); filterParts.Add($"{concatInputs}concat=n={images.Count}:v=1:a=0[outv]"); var filterComplex = string.Join(";", filterParts); // Add audio inputArgs.Add($"-i \"{audioPath}\""); var audioIndex = images.Count; var args = $"{string.Join(" ", inputArgs)} -filter_complex \"{filterComplex}\" -map \"[outv]\" -map {audioIndex}:a -c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 -c:a aac -b:a 192k -shortest -y \"{outputPath}\""; await RunFfmpegAsync(args, ct); } private async Task AssembleFromVideosAsync(string audioPath, IReadOnlyList backgroundClips, string outputPath, CancellationToken ct) { // Simple approach: scale + concat all clips, then merge with audio using -shortest var inputArgs = new List(); var filterParts = new List(); for (int i = 0; i < backgroundClips.Count; i++) { inputArgs.Add($"-i \"{backgroundClips[i]}\""); } inputArgs.Add($"-i \"{audioPath}\""); int audioIndex = backgroundClips.Count; // Scale each clip to vertical 1080x1920 for (int i = 0; i < backgroundClips.Count; i++) { filterParts.Add($"[{i}:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1,fps=25[v{i}]"); } // Concat all clips var concatInputs = string.Join("", Enumerable.Range(0, backgroundClips.Count).Select(i => $"[v{i}]")); filterParts.Add($"{concatInputs}concat=n={backgroundClips.Count}:v=1:a=0[outv]"); var filterComplex = string.Join(";", filterParts); var args = $"{string.Join(" ", inputArgs)} " + $"-filter_complex \"{filterComplex}\" " + $"-map \"[outv]\" -map {audioIndex}:a " + $"-c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 " + $"-c:a aac -b:a 192k -shortest -y \"{outputPath}\""; await RunFfmpegAsync(args, ct); } public async Task AddSubtitlesToVideoAsync(string videoPath, string srtPath, string outputPath, CancellationToken ct = default) { _logger.LogInformation("Adding subtitles to video: {VideoPath}", videoPath); var escapedSrtPath = srtPath.Replace("\\", "/").Replace(":", "\\:"); var args = $"-i \"{videoPath}\" -vf \"subtitles='{escapedSrtPath}':force_style='FontName=Arial,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,Outline=3,Alignment=2,MarginV=40'\" -c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 -c:a copy -y \"{outputPath}\""; await RunFfmpegAsync(args, ct); _logger.LogInformation("Subtitles added successfully: {OutputPath}", outputPath); return outputPath; } public async Task GetMediaDurationAsync(string filePath, CancellationToken ct = default) { var args = $"-i \"{filePath}\" -show_entries format=duration -v quiet -of csv=\"p=0\""; var output = await RunFfprobeAsync(args, ct); if (double.TryParse(output.Trim(), CultureInfo.InvariantCulture, out var duration)) return duration; return 0; } public async Task GenerateThumbnailAsync(string videoPath, string outputPath, double atSecond = 1.0, CancellationToken ct = default) { var timeStr = TimeSpan.FromSeconds(atSecond).ToString(@"hh\:mm\:ss\.fff"); var args = $"-i \"{videoPath}\" -ss {timeStr} -vframes 1 -y \"{outputPath}\""; await RunFfmpegAsync(args, ct); return outputPath; } private async Task RunFfmpegAsync(string arguments, CancellationToken ct) { _logger.LogDebug("FFmpeg args: {Args}", arguments); var process = new Process { StartInfo = new ProcessStartInfo { FileName = "ffmpeg", Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); var stderr = await process.StandardError.ReadToEndAsync(ct); await process.WaitForExitAsync(ct); if (process.ExitCode != 0) { _logger.LogError("FFmpeg failed with exit code {ExitCode}: {Error}", process.ExitCode, stderr[..Math.Min(stderr.Length, 500)]); throw new InvalidOperationException($"FFmpeg failed (exit code {process.ExitCode}): {stderr[..Math.Min(stderr.Length, 300)]}"); } } private async Task RunFfprobeAsync(string arguments, CancellationToken ct) { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "ffprobe", Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); var output = await process.StandardOutput.ReadToEndAsync(ct); await process.WaitForExitAsync(ct); return output; } }