-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressionTask.cs
More file actions
55 lines (48 loc) · 2.17 KB
/
CompressionTask.cs
File metadata and controls
55 lines (48 loc) · 2.17 KB
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
using FFMpegCore;
using FFMpegCore.Enums;
namespace LiteCut
{
internal class CompressionTask(string inputFilePath, string outputFilePath, int targetFileSizeMB, TimeSpan startTime, TimeSpan endTime, bool mergeAudio)
{
public EventHandler<double>? CompressionProgress;
public EventHandler<string>? CompressionError;
public EventHandler<string>? CompressionOutput;
public async Task CompressVideo()
{
double targetFileSizeBytes = targetFileSizeMB * 1024;
var videoInfo = await FFProbe.AnalyseAsync(inputFilePath);
double durationSeconds = endTime.TotalSeconds - startTime.TotalSeconds;
int targetBitrate = (int)(targetFileSizeBytes * 7 / durationSeconds); //picking 7 over 8 for a bit of a margin of error
Action<double>? compressionProgressAction = new Action<double>(p =>
{
Console.WriteLine("progress: " + p);
CompressionProgress?.Invoke(this, p);
});
await FFMpegArguments.FromFileInput(inputFilePath).OutputToFile(outputFilePath, true, options =>
{
if (mergeAudio)
{
options.WithCustomArgument($"-c:v copy -c:a aac -b:a 160k -ac 2 -filter_complex amerge=inputs={videoInfo.AudioStreams.Count}");
}
options.UsingMultithreading(true);
options.WithAudioBitrate(AudioQuality.Normal);
options.WithSpeedPreset(Speed.VeryFast);
options.WithVideoBitrate(targetBitrate);
options.WithVideoCodec(VideoCodec.LibX264);
options.WithDuration(TimeSpan.FromSeconds(durationSeconds));
options.Seek(startTime);
options.EndSeek(endTime);
})
.NotifyOnProgress(compressionProgressAction, TimeSpan.FromSeconds(durationSeconds))
.NotifyOnOutput((output) =>
{
CompressionOutput?.Invoke(this, output);
})
.NotifyOnError((error) =>
{
CompressionError?.Invoke(this, error);
})
.ProcessAsynchronously();
}
}
}