-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressProcessor.cs
More file actions
340 lines (306 loc) · 13.2 KB
/
Copy pathCompressProcessor.cs
File metadata and controls
340 lines (306 loc) · 13.2 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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WinUIShared.Controls;
using WinUIShared.Helpers;
namespace CompressMediaPage
{
public class CompressProcessor(string ffmpegPath, string mediaPath) : Processor(ffmpegPath, new FileLogger.FileLogger("ReelBox/Compress"))
{
public async Task<VideoDetails> GetVideoDetails()
{
var size = GetFileSize(mediaPath);
double bitrate = 0, fps = 0;
int width = 0, height = 0;
var valuesSet = false;
await StartFfmpegProcess($"-i \"{mediaPath}\"", (sender, args) =>
{
Debug.WriteLine(args.Data);
if (valuesSet || string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
var matchCollection = Regex.Matches(args.Data, @"\s*Stream #\d+:\d+.*?: Video: .+?, (\d+)x(\d+).*?,(?: (\d+) kb/s,)? (\d+?\.?\d*?) fps");
if (matchCollection.Count == 0) return;
width = int.Parse(matchCollection[0].Groups[1].Value);
height = int.Parse(matchCollection[0].Groups[2].Value);
_ = double.TryParse(matchCollection[0].Groups[3].Value, out bitrate);
fps = double.Parse(matchCollection[0].Groups[4].Value);
valuesSet = true;
});
return new VideoDetails
{
Size = size,
Bitrate = bitrate,
Resolution = new Size(width, height),
Fps = fps
};
}
public async Task<AudioDetails> GetAudioDetails()
{
var size = GetFileSize(mediaPath);
int bitrate = 0, sampleRate = 0;
var valuesSet = false;
await StartFfmpegProcess($"-i \"{mediaPath}\"", (sender, args) =>
{
Debug.WriteLine(args.Data);
if (valuesSet || string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
var matchCollection = Regex.Matches(args.Data, @"\s*Stream #\d+:\d+.*?: Audio: .+?, (\d+) Hz.+?, (\d+) kb/s");
if (matchCollection.Count == 0) return;
sampleRate = int.Parse(matchCollection[0].Groups[1].Value);
bitrate = int.Parse(matchCollection[0].Groups[2].Value);
valuesSet = true;
});
return new AudioDetails
{
Size = size,
AudioRate = sampleRate,
Bitrate = bitrate
};
}
public async Task<Size> GetImageResolution()
{
int width = 0, height = 0;
var valuesSet = false;
await StartFfmpegProcess($"-i \"{mediaPath}\"", (sender, args) =>
{
Debug.WriteLine(args.Data);
if (valuesSet || string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
var matchCollection = Regex.Matches(args.Data, @"\s*Stream #\d+:\d+.*?: Video: .+?, (\d+)x(\d+)");
if (matchCollection.Count == 0) return;
width = int.Parse(matchCollection[0].Groups[1].Value);
height = int.Parse(matchCollection[0].Groups[2].Value);
valuesSet = true;
});
return new Size(width, height);
}
public double GetFileSize(string outputFile) => File.Exists(outputFile) ? new FileInfo(outputFile).Length / (1024.0 * 1024.0) : 0; // Size in MB
public void SetInitialProgressTexts()
{
leftTextPrimary.Report("Compressing...");
rightTextPrimary.Report("0.0 %");
}
private void ProgressHandler(double progress, TimeSpan currentTime, TimeSpan duration, int fps)
{
IncrementProgress(progress);
}
public async Task CompressResolution(int width, bool isImage)
{
var cpuScaleParam = $"scale={width}:-1";
string scaleParams;
switch (gpuInfo?.Vendor)
{
case GpuVendor.Nvidia:
scaleParams = $"scale_cuda=w={width}:h={width}*ih/iw";
break;
case GpuVendor.Amd:
var gpuPixelFormat = await GetGpuPixelFormat(mediaPath);
var (hwDownArgs, hwUpArgs) = GpuInfo.FilterParams(gpuInfo, gpuPixelFormat);
scaleParams = $"{hwDownArgs}scale={width}:-1{hwUpArgs}";
break;
case GpuVendor.Intel:
scaleParams = $"vpp_qsv=w={width}:h={width}*ih/iw";
break;
default:
scaleParams = cpuScaleParam;
break;
}
if (isImage)
{
await StartFfmpegProcess($"-i \"{mediaPath}\" -vf \"{cpuScaleParam}\" \"{GetOutputName(mediaPath)}\"", ProgressHandler); // Images do not support hardware acceleration. (they do, but it is not worth the complexity)
}
else
{
await StartFfmpegTranscodingProcessDefaultQuality([mediaPath], GetOutputName(mediaPath), $"-vf \"{scaleParams}\"",
ProgressHandler, X265LineWatcher);
}
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressFps(double fps, bool isGif)
{
var fpsParam = $"-r {fps}";
if (isGif)
{
await StartFfmpegProcess($"-i \"{mediaPath}\" {fpsParam} \"{GetOutputName(mediaPath)}\"", ProgressHandler); // GIFs do not support hardware acceleration
}
else
{
await StartFfmpegTranscodingProcessDefaultQuality([mediaPath], GetOutputName(mediaPath), $"-fps_mode auto {fpsParam}", ProgressHandler, X265LineWatcher);
}
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressSize(double sizeInMb, bool limitToTarget, bool isAudio)
{
var duration = TimeSpan.MinValue;
var parsedAudioBitrate = 0;
await StartFfmpegProcess($"-i \"{mediaPath}\"", (sender, args) =>
{
if (string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
if (duration == TimeSpan.MinValue)
{
var matchCollection = Regex.Matches(args.Data, @"\s*Duration:\s(\d{2}:\d{2}:\d{2}\.\d{2}).+");
if (matchCollection.Count == 0) return;
duration = TimeSpan.Parse(matchCollection[0].Groups[1].Value);
}
if (parsedAudioBitrate == 0)
{
var matchCollection = Regex.Matches(args.Data, @"\s*Stream .+: Audio: .+ (\d+) kb/s.+");
if (matchCollection.Count == 0) return;
parsedAudioBitrate = int.Parse(matchCollection[0].Groups[1].Value);
}
});
var totalBitrate = sizeInMb * 1000 * 8 / duration.TotalSeconds; // in bits per second
if (!isAudio)
{
var audioBitrate = parsedAudioBitrate;
totalBitrate -= audioBitrate;
}
await CompressBitrate(totalBitrate, limitToTarget, isAudio);
}
public async Task CompressBitrate(double bitrate, bool limitToTarget, bool isAudio)
{
var limitToTargetCommand = limitToTarget ? $"-maxrate:v {bitrate} -bufsize:v {bitrate}" : string.Empty;
bitrate *= 1000;
if (isAudio)
{
await StartProcessForAudioOrImage($"-b:a {bitrate} {limitToTargetCommand}");
}
else
{
await StartFfmpegTranscodingProcess([mediaPath], GetOutputName(mediaPath), "-threads 1",
$"-fps_mode passthrough -rc vbr -b:v {bitrate} {limitToTargetCommand} -c:v {GpuInfo.EncodingParams(gpuInfo)} -c:a copy",
ProgressHandler, X265LineWatcher);
}
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressCrf(int crf, string preset)
{
await StartFfmpegTranscodingProcess([mediaPath], GetOutputName(mediaPath), crf, preset, string.Empty,
ProgressHandler, X265LineWatcher);
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressAudioQualityFactor(int qa)
{
await StartProcessForAudioOrImage($"-c:a libmp3lame -q:a {qa}");
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressAudioSamplingRate(double ar)
{
var parsedAudioBitrate = 0;
await StartFfmpegProcess($"-i \"{mediaPath}\"", (sender, args) =>
{
if (string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
Debug.WriteLine(args.Data);
if (parsedAudioBitrate != 0) return;
var matchCollection = Regex.Matches(args.Data, @"\s*Stream .+: Audio: .+ (\d+) kb/s");
if (matchCollection.Count == 0) return;
parsedAudioBitrate = int.Parse(matchCollection[0].Groups[1].Value);
});
await StartProcessForAudioOrImage($"-c:a libmp3lame -ar {ar} -b:a {parsedAudioBitrate * 1000}");
if (HasBeenKilled()) return;
AllDone();
}
public async Task CompressImageQualityFactor(int qv)
{
await StartProcessForAudioOrImage($"-q:v {qv}");
if (HasBeenKilled()) return;
AllDone();
}
private async Task StartProcessForAudioOrImage(string extraArguments)
{
var duration = TimeSpan.MinValue;
await StartFfmpegProcess($"-i \"{mediaPath}\" {extraArguments} \"{GetOutputName(mediaPath)}\"", (sender, args) =>
{
Debug.WriteLine(args.Data);
logger.Log(args.Data);
if (string.IsNullOrWhiteSpace(args.Data) || hasBeenKilled) return;
if (duration == TimeSpan.MinValue)
{
var matchCollection = Regex.Matches(args.Data, @"\s*Duration:\s(\d{2}:\d{2}:\d{2}\.\d{2}).+");
if (matchCollection.Count == 0) return;
duration = TimeSpan.Parse(matchCollection[0].Groups[1].Value);
}
if (!args.Data.StartsWith("size")) return;
if (!CheckNoSpaceDuringProcess(args.Data))
{
var matchCollection = Regex.Matches(args.Data, @"^size=\s*\d+KiB.+?time=(\d{2}:\d{2}:\d{2}\.\d{2}).+");
if (matchCollection.Count == 0) return;
IncrementProgress(TimeSpan.Parse(matchCollection[0].Groups[1].Value) / duration * 100);
}
});
}
public static MediaType GetMediaType(string path)
{
var extension = Path.GetExtension(path).ToLower();
return extension switch
{
".mp4" or ".mkv" or ".avi" or ".mov" => MediaType.Video,
".mp3" or ".wav"/* or ".aac" or ".flac"*/ => MediaType.Audio,
".jpg" or ".jpeg" => MediaType.ImageJpg,
".png" => MediaType.ImagePng,
".gif" => MediaType.ImageGif,
_ => throw new NotSupportedException($"Unsupported media type: {extension}"),
};
}
public static string GetFileName(string path) => Path.GetFileName(path);
private string GetOutputName(string path)
{
var inputName = Path.GetFileNameWithoutExtension(path);
var extension = Path.GetExtension(path);
var parentFolder = Path.GetDirectoryName(path) ?? throw new FileNotFoundException($"The specified path does not exist: {path}");
outputFile = Path.Combine(parentFolder, $"{inputName}_COMPRESSED{extension}");
File.Delete(outputFile);
return outputFile;
}
private void CheckX265Error(string line)
{
const string x265Error = "x265 [error]: ";
if (!line.StartsWith(x265Error)) return;
error(line[x265Error.Length..]);
}
private void X265LineWatcher(string line)
{
CheckX265Error(line);
}
private void IncrementProgress(double progress)
{
progressPrimary.Report(progress);
rightTextPrimary.Report($"{Math.Round(progress, 2)} %");
}
private void AllDone()
{
progressPrimary.Report(ProgressMax);
rightTextPrimary.Report("100 %");
}
}
public struct VideoDetails
{
public double Size { get; set; }
public double Bitrate { get; set; }
public Size Resolution { get; set; }
public double Fps { get; set; }
}
public struct AudioDetails
{
public double Size { get; set; }
public int Bitrate { get; set; }
public int AudioRate { get; set; }
}
public enum MediaType
{
Video,
Audio,
ImageJpg,
ImagePng,
ImageGif
}
}