-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2889 lines (2494 loc) · 126 KB
/
Copy pathProgram.cs
File metadata and controls
2889 lines (2494 loc) · 126 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Win32;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
using System.Management;
namespace FormatConverter {
class Program {
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const uint CREATE_NO_WINDOW = 0x08000000;
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern int SHParseDisplayName(string name, IntPtr pbc, out IntPtr pidl, uint sfgaoIn,
out uint psfgaoOut);
[DllImport("shell32.dll")]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In] IntPtr[] apidl,
uint dwFlags);
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr ILFindChild(IntPtr pidlParent, IntPtr pidlChild);
[DllImport("ole32.dll")]
public static extern void CoTaskMemFree(IntPtr pv);
private static readonly string[] VideoConversions =
{ "mp4", "mkv", "avi", "mov", "wmv", "webm", "flv", "mp3", "m4a" };
private static readonly string[] AudioConversions =
{ "mp3", "wav", "ogg", "opus", "aac", "flac", "m4a", "wma" };
private static readonly string[] ImageConversions =
{ "jpg", "jpeg", "png", "bmp", "gif", "webp", "tiff", "ico" };
private static readonly Dictionary<string, (string type, string[] conversions)> FormatMappings = new()
{
{ ".mp4", ("video", VideoConversions) },
{ ".mkv", ("video", VideoConversions) },
{ ".avi", ("video", VideoConversions) },
{ ".mov", ("video", VideoConversions) },
{ ".wmv", ("video", VideoConversions) },
{ ".webm", ("video", VideoConversions) },
{ ".flv", ("video", VideoConversions) },
{ ".ts", ("video", VideoConversions) },
{ ".3gp", ("video", VideoConversions) },
{ ".mp3", ("audio", AudioConversions) },
{ ".wav", ("audio", AudioConversions) },
{ ".ogg", ("audio", AudioConversions) },
{ ".opus", ("audio", AudioConversions) },
{ ".aac", ("audio", AudioConversions) },
{ ".flac", ("audio", AudioConversions) },
{ ".wma", ("audio", AudioConversions) },
{ ".m4a", ("audio", AudioConversions) },
{ ".ac3", ("audio", AudioConversions) },
{ ".jpg", ("image", ImageConversions) },
{ ".jpeg", ("image", ImageConversions) },
{ ".png", ("image", ImageConversions) },
{ ".bmp", ("image", ImageConversions) },
{ ".gif", ("image", ImageConversions) },
{ ".webp", ("image", ImageConversions) },
{ ".tiff", ("image", ImageConversions) },
{ ".ico", ("image", ImageConversions) },
{ ".heic", ("image", ImageConversions) }
};
private static string detectedGpu = null;
static string DetectGpuType()
{
if (detectedGpu != null)
return detectedGpu;
var gpuInfo = new System.Text.StringBuilder();
gpuInfo.AppendLine("GPU Detection Information:");
gpuInfo.AppendLine("------------------------");
try
{
var startInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = "-hide_banner -hwaccels",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
gpuInfo.AppendLine("FFmpeg Hardware Accelerators:");
gpuInfo.AppendLine(output);
if (output.Contains("nvenc"))
{
startInfo.Arguments = "-hide_banner -encoders | findstr nvenc";
using (var versionProcess = Process.Start(startInfo))
{
string versionOutput = versionProcess.StandardOutput.ReadToEnd();
versionProcess.WaitForExit();
gpuInfo.AppendLine("NVENC API Version Information:");
gpuInfo.AppendLine(versionOutput);
if (versionOutput.Contains("nvenc") && !versionOutput.Contains("13.0"))
{
detectedGpu = "generic";
gpuInfo.AppendLine("NVENC version is below 13.0, using generic settings.");
}
else
{
detectedGpu = "nvidia";
gpuInfo.AppendLine("Detected NVIDIA GPU with NVENC API version >= 13.0");
}
}
}
else if (output.Contains("cuda"))
{
detectedGpu = "nvidia";
gpuInfo.AppendLine("Detected NVIDIA GPU via FFmpeg");
}
else if (output.Contains("amf") || output.Contains("d3d11va"))
{
detectedGpu = "amd";
gpuInfo.AppendLine("Detected AMD GPU via FFmpeg");
}
else if (output.Contains("qsv"))
{
detectedGpu = "intel";
gpuInfo.AppendLine("Detected Intel GPU via FFmpeg");
}
}
if (detectedGpu == null)
{
startInfo = new ProcessStartInfo
{
FileName = "wmic",
Arguments = "path win32_VideoController get name",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
string output = process.StandardOutput.ReadToEnd().ToLower();
process.WaitForExit();
gpuInfo.AppendLine("\nWMIC GPU Detection:");
gpuInfo.AppendLine(output);
if (output.Contains("nvidia"))
{
detectedGpu = "nvidia";
gpuInfo.AppendLine("Detected NVIDIA GPU via WMIC");
}
else if (output.Contains("amd") || output.Contains("radeon"))
{
detectedGpu = "amd";
gpuInfo.AppendLine("Detected AMD GPU via WMIC");
}
else if (output.Contains("intel"))
{
detectedGpu = "intel";
gpuInfo.AppendLine("Detected Intel GPU via WMIC");
}
}
}
}
catch (Exception ex)
{
gpuInfo.AppendLine($"Error detecting GPU: {ex.Message}");
}
if (detectedGpu == null)
{
detectedGpu = "generic";
gpuInfo.AppendLine("No specific GPU detected, using generic settings");
}
gpuInfo.AppendLine($"\nFinal GPU Type: {detectedGpu}");
MessageBox.Show(gpuInfo.ToString(), "GPU Detection Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
return detectedGpu;
}
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length == 0) {
if (!IsAdministrator()) {
var procInfo = new ProcessStartInfo {
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Application.ExecutablePath,
Verb = "runas"
};
try {
Process.Start(procInfo);
}
catch {
}
return;
}
if (!IsFfmpegInstalled())
{
if (!InstallFfmpeg())
{
return;
}
}
RegisterContextMenus();
CustomMessageBox.Show(
"Right-click on a file to convert it to another format.",
"Success",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
static bool InstallFfmpeg()
{
try
{
var result = CustomMessageBox.Show(
"FFmpeg is required but not found on your system.\n\nWould you like to install it now using winget?",
"FFmpeg Required",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
var startInfo = new ProcessStartInfo
{
FileName = "winget",
Arguments = "install ffmpeg",
UseShellExecute = true,
CreateNoWindow = false
};
using var process = Process.Start(startInfo);
process.WaitForExit();
if (process.ExitCode == 0)
{
CustomMessageBox.Show(
"FFmpeg was installed successfully. You may need to restart the application.",
"Installation Complete",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return true;
}
else
{
CustomMessageBox.Show(
"FFmpeg installation failed. Please install FFmpeg manually.",
"Installation Failed",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
}
else
{
CustomMessageBox.Show(
"FFmpeg is required for this application to work.",
"FFmpeg Required",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
return false;
}
}
catch (Exception ex)
{
CustomMessageBox.Show(
$"Error during FFmpeg installation: {ex.Message}\n\nPlease install FFmpeg manually.",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
}
if (args.Length == 1 && args[0] == "-unregister") {
if (!IsAdministrator()) {
var procInfo = new ProcessStartInfo {
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Application.ExecutablePath,
Verb = "runas"
};
try {
Process.Start(procInfo);
}
catch {
}
return;
}
UnregisterContextMenus();
MessageBox.Show("Context menus removed successfully.", "Info");
return;
}
if (args.Length == 2 && args[1] == "mute") {
string inputFile = args[0];
string extension = Path.GetExtension(inputFile);
string outputFile = Path.Combine(
Path.GetDirectoryName(inputFile),
Path.GetFileNameWithoutExtension(inputFile) + "_muted" + extension);
try {
if (File.Exists(outputFile)) {
var result = MessageBox.Show(
$"File already exists:\n{outputFile}\n\nDo you want to replace it?",
"File Exists",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel || result == DialogResult.No)
return;
try {
File.Delete(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Cannot replace existing file: {ex.Message}", "Error");
return;
}
}
PerformMuteWithProgress(inputFile, outputFile);
OpenFolderAndSelectFile(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Error during muting: {ex.Message}", "Error");
Environment.Exit(1);
}
return;
}
if (args.Length >= 2 && args[1] == "compress") {
string inputFile = args[0];
string extension = Path.GetExtension(inputFile);
int targetSizeMB = 10;
if (args.Length >= 3 && int.TryParse(args[2], out int size)) {
targetSizeMB = size;
}
string outputFile = Path.Combine(
Path.GetDirectoryName(inputFile),
Path.GetFileNameWithoutExtension(inputFile) + $"_compressed{targetSizeMB}MB" + extension);
try {
if (File.Exists(outputFile)) {
var result = CustomMessageBox.Show(
$"File already exists:\n{outputFile}\n\nDo you want to replace it?",
"File Exists",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel || result == DialogResult.No)
return;
try {
File.Delete(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Cannot replace existing file: {ex.Message}", "Error");
return;
}
}
PerformCompressWithProgress(inputFile, outputFile, targetSizeMB);
OpenFolderAndSelectFile(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Error during compression: {ex.Message}", "Error");
Environment.Exit(1);
}
return;
}
if (args.Length == 2 && (args[1] == "resize50" || args[1] == "resize75")) {
string inputFile = args[0];
string extension = Path.GetExtension(inputFile);
string scale = args[1] == "resize50" ? "50%" : "75%";
string scaleValue = args[1] == "resize50" ? "0.5" : "0.75";
string outputFile = Path.Combine(
Path.GetDirectoryName(inputFile),
Path.GetFileNameWithoutExtension(inputFile) + "_" + scale.Replace("%", "pct") + extension);
try {
if (File.Exists(outputFile)) {
var result = MessageBox.Show(
$"File already exists:\n{outputFile}\n\nDo you want to replace it?",
"File Exists",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel || result == DialogResult.No)
return;
try {
File.Delete(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Cannot replace existing file: {ex.Message}", "Error");
return;
}
}
PerformResizeWithProgress(inputFile, outputFile, scaleValue);
OpenFolderAndSelectFile(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Error during resizing: {ex.Message}", "Error");
Environment.Exit(1);
}
return;
}
if (args.Length > 1) {
if (args.Length > 2) {
string outputFormat = args.Last();
try {
foreach (var inputFile in args.Take(args.Length - 1)) {
string outputFile = Path.ChangeExtension(inputFile, outputFormat);
if (File.Exists(outputFile)) {
var result = MessageBox.Show(
$"File already exists:\n{outputFile}\n\nDo you want to replace it?",
"File Exists",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel)
return;
if (result == DialogResult.No)
continue;
try {
File.Delete(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Cannot replace existing file: {ex.Message}", "Error");
continue;
}
}
PerformConversionWithProgress(inputFile, outputFile);
}
MessageBox.Show("Batch conversion completed successfully.", "Info");
}
catch (Exception ex) {
MessageBox.Show($"Error during batch conversion: {ex.Message}", "Error");
Environment.Exit(1);
}
}
else {
string inputFile = args[0];
string outputFormat = args[1];
string outputFile = Path.ChangeExtension(inputFile, outputFormat);
try {
if (File.Exists(outputFile)) {
var result = MessageBox.Show(
$"File already exists:\n{outputFile}\n\nDo you want to replace it?",
"File Exists",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel || result == DialogResult.No)
return;
try {
File.Delete(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Cannot replace existing file: {ex.Message}", "Error");
return;
}
}
PerformConversionWithProgress(inputFile, outputFile);
OpenFolderAndSelectFile(outputFile);
}
catch (Exception ex) {
MessageBox.Show($"Error during conversion: {ex.Message}", "Error");
Environment.Exit(1);
}
}
}
}
static bool IsFfmpegInstalled()
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "where",
Arguments = "ffmpeg",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using var process = Process.Start(startInfo);
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return process.ExitCode == 0 && !string.IsNullOrWhiteSpace(output);
}
catch
{
return false;
}
}
static bool IsAdministrator() {
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
static void RegisterContextMenus() {
string execPath = Application.ExecutablePath;
foreach (var mapping in FormatMappings) {
string extension = mapping.Key;
var (type, conversions) = mapping.Value;
using var mainKey =
Registry.ClassesRoot.CreateSubKey($@"SystemFileAssociations\{extension}\shell\Convert To");
mainKey.SetValue("SubCommands", "");
mainKey.SetValue("MUIVerb", "Convert To");
using var shellKey = Registry.ClassesRoot.CreateSubKey($@"SystemFileAssociations\{extension}\shell\Convert To\shell");
mainKey.SetValue("Icon", $"\"{execPath}\",0");
using var toolsKey = shellKey.CreateSubKey("!Tools");
toolsKey.SetValue("MUIVerb", "Tools");
toolsKey.SetValue("SubCommands", "");
using var toolsShellKey = toolsKey.CreateSubKey("shell");
if (type == "audio" || type == "video") {
using var muteKey = toolsShellKey.CreateSubKey("Mute");
muteKey.SetValue("", "Mute");
using var muteCmdKey = muteKey.CreateSubKey("command");
muteCmdKey.SetValue("", $"\"{execPath}\" \"%1\" mute");
using var compressKey = toolsShellKey.CreateSubKey("Compress");
compressKey.SetValue("MUIVerb", "Compress");
compressKey.SetValue("SubCommands", "");
using var compressShellKey = compressKey.CreateSubKey("shell");
using var compress10MB = compressShellKey.CreateSubKey("1_Compress_010MB");
compress10MB.SetValue("", "Compress to <10MB");
using var compress10MBCmd = compress10MB.CreateSubKey("command");
compress10MBCmd.SetValue("", $"\"{execPath}\" \"%1\" compress 10");
using var compress20MB = compressShellKey.CreateSubKey("2_Compress_020MB");
compress20MB.SetValue("", "Compress to <20MB");
using var compress20MBCmd = compress20MB.CreateSubKey("command");
compress20MBCmd.SetValue("", $"\"{execPath}\" \"%1\" compress 20");
using var compress50MB = compressShellKey.CreateSubKey("3_Compress_050MB");
compress50MB.SetValue("", "Compress to <50MB");
using var compress50MBCmd = compress50MB.CreateSubKey("command");
compress50MBCmd.SetValue("", $"\"{execPath}\" \"%1\" compress 50");
using var compress100MB = compressShellKey.CreateSubKey("4_Compress_100MB");
compress100MB.SetValue("", "Compress to <100MB");
using var compress100MBCmd = compress100MB.CreateSubKey("command");
compress100MBCmd.SetValue("", $"\"{execPath}\" \"%1\" compress 100");
using var compress500MB = compressShellKey.CreateSubKey("5_Compress_500MB");
compress500MB.SetValue("", "Compress to <500MB");
using var compress500MBCmd = compress500MB.CreateSubKey("command");
compress500MBCmd.SetValue("", $"\"{execPath}\" \"%1\" compress 500");
}
if (type == "image") {
using var resizeKey = toolsShellKey.CreateSubKey("Resize50");
resizeKey.SetValue("", "Resize to 50%");
using var resizeCmdKey = resizeKey.CreateSubKey("command");
resizeCmdKey.SetValue("", $"\"{execPath}\" \"%1\" resize50");
using var resize75Key = toolsShellKey.CreateSubKey("Resize75");
resize75Key.SetValue("", "Resize to 75%");
using var resize75CmdKey = resize75Key.CreateSubKey("command");
resize75CmdKey.SetValue("", $"\"{execPath}\" \"%1\" resize75");
}
foreach (var format in conversions) {
if (format == extension.TrimStart('.'))
continue;
using var formatKey = shellKey.CreateSubKey(format.ToUpper());
formatKey.SetValue("", format.ToUpper());
using var cmdKey = formatKey.CreateSubKey("command");
cmdKey.SetValue("", $"\"{execPath}\" \"%1\" {format}");
}
}
}
static void UnregisterContextMenus() {
foreach (var mapping in FormatMappings) {
string extension = mapping.Key;
try {
Registry.ClassesRoot.DeleteSubKeyTree($@"SystemFileAssociations\{extension}\shell\Convert To", false);
}
catch (Exception ex) {
MessageBox.Show($"Error removing menu for {extension}: {ex.Message}", "Error");
}
}
try {
Registry.CurrentUser.DeleteSubKeyTree(@"Software\Classes\MediaConverter", false);
}
catch { }
}
static void PerformConversionWithProgress(string input, string output) {
string backupPath = null;
bool isReplacing = File.Exists(output);
if (isReplacing) {
backupPath = Path.Combine(
Path.GetDirectoryName(output),
Path.GetFileNameWithoutExtension(output) + ".backup" + Path.GetExtension(output)
);
try {
File.Copy(output, backupPath, true);
}
catch (Exception ex) {
MessageBox.Show($"Warning: Could not create backup: {ex.Message}", "Backup Warning");
backupPath = null;
}
}
using var progressForm = new ProgressForm();
Process ffmpegProcess = null;
var conversionTask = Task.Run(() => {
string inputExt = Path.GetExtension(input).ToLower();
string outputExt = Path.GetExtension(output).ToLower();
var (inputType, _) = FormatMappings[inputExt];
string arguments = "";
if (inputType == "image") {
switch (outputExt) {
case ".webp":
arguments = $"-i \"{input}\" -quality 90 -compression_level 6 \"{output}\"";
break;
case ".jpg":
case ".jpeg":
arguments = $"-i \"{input}\" -quality 95 \"{output}\"";
break;
case ".png":
arguments = $"-i \"{input}\" -compression_level 9 \"{output}\"";
break;
case ".tiff":
arguments = $"-i \"{input}\" -compression_algo lzw \"{output}\"";
break;
case ".gif":
if (inputExt == ".gif") {
arguments =
$"-i \"{input}\" -lavfi \"fps=15,scale=trunc(iw/2)*2:trunc(ih/2)*2:flags=lanczos\" \"{output}\"";
}
else {
arguments = $"-i \"{input}\" \"{output}\"";
}
break;
case ".bmp":
arguments = $"-i \"{input}\" -pix_fmt rgb24 \"{output}\"";
break;
case ".ico":
arguments = $"-i \"{input}\" -vf scale=256:256 \"{output}\"";
break;
case ".heic":
arguments = $"-i \"{input}\" -quality 90 \"{output}\"";
break;
default:
arguments = $"-i \"{input}\" \"{output}\"";
break;
}
}
else if (inputType == "audio") {
switch (outputExt) {
case ".mp3":
arguments = $"-i \"{input}\" -vn -codec:a libmp3lame -q:a 0 \"{output}\"";
break;
case ".m4a":
arguments = $"-i \"{input}\" -vn -c:a aac -b:a 256k \"{output}\"";
break;
case ".flac":
arguments = $"-i \"{input}\" -vn -codec:a flac -compression_level 12 \"{output}\"";
break;
case ".opus":
arguments = $"-i \"{input}\" -vn -c:a libopus -b:a 192k \"{output}\"";
break;
case ".ogg":
arguments = $"-i \"{input}\" -vn -c:a libvorbis -q:a 7 \"{output}\"";
break;
case ".wav":
arguments = $"-i \"{input}\" -vn -c:a pcm_s24le \"{output}\"";
break;
case ".wma":
arguments = $"-i \"{input}\" -vn -c:a wmav2 -b:a 256k \"{output}\"";
break;
case ".aac":
arguments = $"-i \"{input}\" -vn -c:a aac -b:a 256k \"{output}\"";
break;
case ".ac3":
arguments = $"-i \"{input}\" -vn -c:a ac3 -b:a 448k \"{output}\"";
break;
default:
arguments = $"-i \"{input}\" -vn \"{output}\"";
break;
}
}
else if (inputType == "video") {
string videoCodec, audioCodec, extraParams = "";
switch (outputExt) {
case ".mp4":
videoCodec = "-c:v libx264 -crf 23 -preset medium";
audioCodec = "-c:a aac -b:a 192k";
extraParams = "-movflags +faststart";
break;
case ".mkv":
videoCodec = "-c:v libx264 -crf 21 -preset slower";
audioCodec = "-c:a libopus -b:a 192k";
extraParams = "";
break;
case ".webm":
videoCodec = "-c:v libvpx-vp9 -crf 30 -b:v 0";
audioCodec = "-c:a libopus -b:a 128k";
extraParams = "-deadline good -cpu-used 2";
break;
case ".avi":
videoCodec = "-c:v mpeg4 -qscale:v 3";
audioCodec = "-c:a mp3 -q:a 3";
extraParams = "";
break;
case ".wmv":
videoCodec = "-c:v wmv2 -qscale:v 3";
audioCodec = "-c:a wmav2 -b:a 256k";
extraParams = "";
break;
case ".flv":
videoCodec = "-c:v flv -qscale:v 3";
audioCodec = "-c:a mp3 -q:a 3";
extraParams = "";
break;
case ".mov":
videoCodec = "-c:v prores_ks -profile:v 3";
audioCodec = "-c:a pcm_s24le";
extraParams = "";
break;
case ".ts":
videoCodec = "-c:v libx264 -crf 23 -preset medium";
audioCodec = "-c:a aac -b:a 192k";
extraParams = "-f mpegts";
break;
case ".3gp":
videoCodec = "-c:v libx264 -crf 28 -preset faster -profile:v baseline -level 3.0";
audioCodec = "-c:a aac -b:a 128k -ac 2";
extraParams = "";
break;
case ".mp3":
videoCodec = "-vn";
audioCodec = "-codec:a libmp3lame -q:a 0";
extraParams = "";
break;
case ".m4a":
videoCodec = "-vn";
audioCodec = "-c:a aac -b:a 256k";
extraParams = "";
break;
default:
videoCodec = "-c:v libx264 -crf 23";
audioCodec = "-c:a aac -b:a 192k";
extraParams = "";
break;
}
arguments = $"-i \"{input}\" {videoCodec} {audioCodec} {extraParams} \"{output}\"";
if (inputType == "audio" && outputExt != ".mp3" && outputExt != ".m4a") {
arguments =
$"-i \"{input}\" -f lavfi -i color=c=black:s=1920x1080 -shortest {videoCodec} {audioCodec} {extraParams} \"{output}\"";
}
}
var startInfo = new ProcessStartInfo {
FileName = "ffmpeg",
Arguments = arguments,
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
LoadUserProfile = false,
ErrorDialog = false,
WorkingDirectory = Path.GetDirectoryName(output),
StandardErrorEncoding = System.Text.Encoding.UTF8
};
ffmpegProcess = new Process { StartInfo = startInfo };
TimeSpan duration = TimeSpan.Zero;
TimeSpan currentTime = TimeSpan.Zero;
ffmpegProcess.ErrorDataReceived += (sender, e) => {
if (string.IsNullOrEmpty(e.Data))
return;
string data = e.Data;
if (duration == TimeSpan.Zero) {
var durationMatch = Regex.Match(data, @"Duration: (\d+):(\d+):(\d+)\.(\d+)");
if (durationMatch.Success) {
int hours = int.Parse(durationMatch.Groups[1].Value);
int minutes = int.Parse(durationMatch.Groups[2].Value);
int seconds = int.Parse(durationMatch.Groups[3].Value);
int milliseconds = int.Parse(durationMatch.Groups[4].Value) * 10;
duration = new TimeSpan(0, hours, minutes, seconds, milliseconds);
}
}
var timeMatch = Regex.Match(data, @"time=(\d+):(\d+):(\d+)\.(\d+)");
if (timeMatch.Success) {
int hours = int.Parse(timeMatch.Groups[1].Value);
int minutes = int.Parse(timeMatch.Groups[2].Value);
int seconds = int.Parse(timeMatch.Groups[3].Value);
int milliseconds = int.Parse(timeMatch.Groups[4].Value) * 10;
currentTime = new TimeSpan(0, hours, minutes, seconds, milliseconds);
if (duration != TimeSpan.Zero) {
int percentage = (int)((currentTime.TotalMilliseconds / duration.TotalMilliseconds) * 100);
percentage = Math.Min(99, Math.Max(0, percentage));
var forms = Application.OpenForms;
foreach (Form form in forms) {
if (form is ProgressForm progressForm) {
progressForm.BeginInvoke(new Action(() => {
progressForm.UpdateProgress(percentage);
}));
break;
}
}
}
}
};
progressForm.Invoke(new Action(() => {
progressForm.SetProcessInfo(ffmpegProcess, output, isReplacing, backupPath);
}));
ffmpegProcess.Start();
ffmpegProcess.BeginErrorReadLine();
ffmpegProcess.WaitForExit();
if (ffmpegProcess.ExitCode != 0 && !progressForm.WasCancelled()) {
string errorSummary = "FFmpeg failed to complete the operation.";
throw new Exception($"FFmpeg exited with code {ffmpegProcess.ExitCode}. {errorSummary}");
}
if (isReplacing && File.Exists(backupPath)) {
try {
File.Delete(backupPath);
}
catch {
}
}
});
conversionTask.ContinueWith(t => {
if (t.IsFaulted) {
progressForm.Invoke(new Action(() => {
if (!progressForm.WasCancelled()) {
progressForm.SetError(t.Exception?.InnerException?.Message ?? "Unknown error");
}
else {
progressForm.Close();
}
}));
}
else {
progressForm.Invoke(new Action(() => { progressForm.SetCompleted(); }));
}
});
Application.Run(progressForm);
try {
conversionTask.Wait();
}
catch (AggregateException ae) {
if (ae.InnerException != null)
throw ae.InnerException;
throw;
}
}
private static string GetVideoCodec(string gpuType) {
switch (gpuType) {
case "nvidia":
return "h264_nvenc";
case "amd":
return "h264_amf";
case "intel":
return "h264_qsv";
default:
return "libx264 -preset faster -crf 23";
}
}
static void PerformCompressWithProgress(string input, string output, int targetSizeMB = 20) {
string backupPath = null;
bool isReplacing = File.Exists(output);
int compressionAttempt = 1;
int maxAttempts = 5;
if (isReplacing) {
backupPath = Path.Combine(
Path.GetDirectoryName(output),
Path.GetFileNameWithoutExtension(output) + ".backup" + Path.GetExtension(output)
);
try {
File.Copy(output, backupPath, true);
}
catch (Exception ex) {
MessageBox.Show($"Warning: Could not create backup: {ex.Message}", "Backup Warning");
backupPath = null;
}
}
using var progressForm = new ProgressForm();
Process ffmpegProcess = null;
var compressTask = Task.Run(() => {
bool compressionSuccessful = false;
string tempOutputPath = Path.Combine(
Path.GetTempPath(),
Path.GetFileNameWithoutExtension(output) + "_temp" + Path.GetExtension(output)
);
string currentInput = input;
string currentOutput = output;
string gpuType = DetectGpuType();
bool useGenericEncoder = false;
bool hardwareEncodingFailed = false;
while (!compressionSuccessful && compressionAttempt <= maxAttempts) {
if (compressionAttempt > 1) {
progressForm.BeginInvoke(new Action(() => {
progressForm.SetStatusText($"Still exceeding size limit. Attempt {compressionAttempt}/{maxAttempts} with stronger compression...");
progressForm.UpdateProgress(0);
}));
currentInput = output;
currentOutput = tempOutputPath;
}
if (hardwareEncodingFailed) {
gpuType = "generic";
useGenericEncoder = true;
}