File size: 8,792 Bytes
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56d8c4f
8fb6238
56d8c4f
 
8fb6238
 
 
 
 
 
 
 
 
 
56d8c4f
 
8fb6238
56d8c4f
 
 
 
 
 
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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<FfmpegService> _logger;

    public FfmpegService(ILogger<FfmpegService> logger)
    {
        _logger = logger;
    }

    public async Task<string> AssembleVerticalVideoAsync(string audioPath, IReadOnlyList<string> 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<string> 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<string>();
        var filterParts = new List<string>();

        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<string> backgroundClips, string outputPath, CancellationToken ct)
    {
        // Simple approach: scale + concat all clips, then merge with audio using -shortest
        var inputArgs = new List<string>();
        var filterParts = new List<string>();

        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<string> 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<double> 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<string> 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<string> 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;
    }
}