-
Notifications
You must be signed in to change notification settings - Fork 852
/
CommandLineConverter.cs
2007 lines (1871 loc) · 111 KB
/
CommandLineConverter.cs
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 Nikse.SubtitleEdit.Core.BluRaySup;
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.ContainerFormats.Matroska;
using Nikse.SubtitleEdit.Core.ContainerFormats.Mp4;
using Nikse.SubtitleEdit.Core.ContainerFormats.TransportStream;
using Nikse.SubtitleEdit.Core.Interfaces;
using Nikse.SubtitleEdit.Core.SubtitleFormats;
using Nikse.SubtitleEdit.Core.VobSub;
using Nikse.SubtitleEdit.Forms;
using Nikse.SubtitleEdit.Forms.Ocr;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Nikse.SubtitleEdit.Logic.CommandLineConvert
{
public static class CommandLineConverter
{
private static StreamWriter _stdOutWriter;
private static string _currentFolder;
private static bool _consoleAttached;
public delegate void BatchConvertProgress(string progress);
public enum BatchAction
{
FixCommonErrors,
MergeShortLines,
MergeSameTexts,
MergeSameTimeCodes,
RemoveTextForHI,
RemoveFormatting,
RemoveStyle,
RedoCasing,
ReverseRtlStartEnd,
BridgeGaps,
MultipleReplace,
FixRtl,
SplitLongLines,
BalanceLines,
SetMinGap,
ChangeFrameRate,
OffsetTimeCodes,
ChangeSpeed,
AdjustDisplayDuration,
ApplyDurationLimits,
RemoveLineBreaks,
DeleteLines,
AssaChangeRes,
}
internal static void ConvertOrReturn(string productIdentifier, string[] commandLineArguments)
{
if (commandLineArguments.Length > 1)
{
var action = (Func<string[], int>)null;
var firstArgument = commandLineArguments[1].Trim().ToLowerInvariant();
if (firstArgument == "/convert" || firstArgument == "-convert")
{
action = Convert;
}
else if (firstArgument == "/help" || firstArgument == "-help" || firstArgument == "/?" || firstArgument == "-?")
{
action = Help;
}
if (action != null)
{
_currentFolder = Directory.GetCurrentDirectory();
AttachConsole();
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine($"{productIdentifier} - Batch converter");
_stdOutWriter.WriteLine();
var result = action(commandLineArguments);
DetachConsole();
Environment.Exit(result);
}
}
}
private static int Help(string[] arguments)
{
var secondArgument = arguments.Length > 2 ? arguments[2].Trim().ToLowerInvariant() : null;
if (secondArgument == "formats" || secondArgument == "/formats" || secondArgument == "-formats" || secondArgument == "/list" || secondArgument == "-list")
{
_stdOutWriter.WriteLine("- Supported formats (input/output):");
foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
{
_stdOutWriter.WriteLine(" " + format.Name.RemoveChar(' '));
}
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine("- Supported formats (input only):");
_stdOutWriter.WriteLine(" " + CapMakerPlus.NameOfFormat);
_stdOutWriter.WriteLine(" " + Captionate.NameOfFormat);
_stdOutWriter.WriteLine(" " + Cavena890.NameOfFormat);
_stdOutWriter.WriteLine(" " + CheetahCaption.NameOfFormat);
_stdOutWriter.WriteLine(" " + Chk.NameOfFormat);
_stdOutWriter.WriteLine(" Matroska (.mkv)");
_stdOutWriter.WriteLine(" Matroska subtitle (.mks)");
_stdOutWriter.WriteLine(" " + NciCaption.NameOfFormat);
_stdOutWriter.WriteLine(" " + AvidStl.NameOfFormat);
_stdOutWriter.WriteLine(" " + Pac.NameOfFormat);
_stdOutWriter.WriteLine(" " + Spt.NameOfFormat);
_stdOutWriter.WriteLine(" " + Ultech130.NameOfFormat);
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.RemoveChar(' ') + "'");
_stdOutWriter.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.RemoveChar(' ') + "'");
_stdOutWriter.WriteLine("- For DOST/image .dost/image output use: '" + BatchConvert.DostImageSubtitle.RemoveChar(' ') + "'");
_stdOutWriter.WriteLine("- For BDN/XML .xml/image output use: '" + BatchConvert.BdnXmlSubtitle.RemoveChar(' ') + "'");
_stdOutWriter.WriteLine("- For FCP/image .xml/image output use: '" + BatchConvert.FcpImageSubtitle.RemoveChar(' ') + "'");
_stdOutWriter.WriteLine("- For plain text only output use: '" + LanguageSettings.Current.BatchConvert.PlainText.RemoveChar(' ') + "'");
}
else
{
_stdOutWriter.WriteLine("- Usage: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [<optional-parameters>]");
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine(" pattern:");
_stdOutWriter.WriteLine(" one or more file name patterns separated by commas");
_stdOutWriter.WriteLine(" relative patterns are relative to /inputfolder if specified");
_stdOutWriter.WriteLine(" optional-parameters:");
_stdOutWriter.WriteLine(" /offset:hh:mm:ss:ms");
_stdOutWriter.WriteLine(" /fps:<frame rate>");
_stdOutWriter.WriteLine(" /targetfps:<frame rate>");
_stdOutWriter.WriteLine(" /encoding:<encoding name>");
_stdOutWriter.WriteLine(" /pac-codepage:<code page>");
_stdOutWriter.WriteLine(" /track-number:<comma separated track number list>");
_stdOutWriter.WriteLine(" /resolution:<width>x<height>");
_stdOutWriter.WriteLine(" /inputfolder:<folder name>");
_stdOutWriter.WriteLine(" /outputfolder:<folder name>");
_stdOutWriter.WriteLine(" /overwrite");
_stdOutWriter.WriteLine(" /forcedonly");
_stdOutWriter.WriteLine(" /teletextonly");
_stdOutWriter.WriteLine(" /multiplereplace:<comma separated file name list> ('.' represents the default replace rules)");
_stdOutWriter.WriteLine(" /multiplereplace (equivalent to /multiplereplace:.)");
_stdOutWriter.WriteLine(" /ebuheaderfile:<file name>");
_stdOutWriter.WriteLine(" /ocrengine:<ocr engine> (\"tesseract\"/\"nOCR\")");
_stdOutWriter.WriteLine(" /renumber:<starting number>");
_stdOutWriter.WriteLine(" /adjustduration:<ms>");
//_stdOutWriter.WriteLine(" /ocrdb:<ocr db/dictionary> (e.g. \"eng\" or \"latin\")");
_stdOutWriter.WriteLine(" The following operations are applied in command line order");
_stdOutWriter.WriteLine(" from left to right, and can be specified multiple times.");
_stdOutWriter.WriteLine(" /" + BatchAction.ApplyDurationLimits);
_stdOutWriter.WriteLine(" /" + BatchAction.FixCommonErrors);
_stdOutWriter.WriteLine(" /" + BatchAction.RemoveLineBreaks);
_stdOutWriter.WriteLine(" /" + BatchAction.MergeSameTimeCodes);
_stdOutWriter.WriteLine(" /" + BatchAction.MergeSameTexts);
_stdOutWriter.WriteLine(" /" + BatchAction.MergeShortLines);
_stdOutWriter.WriteLine(" /" + BatchAction.ReverseRtlStartEnd);
_stdOutWriter.WriteLine(" /" + BatchAction.RemoveFormatting);
_stdOutWriter.WriteLine(" /" + BatchAction.RemoveTextForHI);
_stdOutWriter.WriteLine(" /" + BatchAction.RedoCasing);
_stdOutWriter.WriteLine(" /" + BatchAction.BalanceLines);
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine(" Example: SubtitleEdit /convert *.srt sami");
_stdOutWriter.WriteLine(" Show this usage message: SubtitleEdit /help");
_stdOutWriter.WriteLine(" List available formats: SubtitleEdit /help formats");
}
_stdOutWriter.WriteLine();
return 0;
}
private static int Convert(string[] arguments) // E.g.: /convert *.txt SubRip
{
if (arguments.Length < 4)
{
return Help(arguments);
}
int count = 0;
int converted = 0;
int errors = 0;
try
{
var pattern = arguments[2].Trim();
var targetFormat = arguments[3].Trim().RemoveChar(' ').ToLowerInvariant();
// name shortcuts
if (targetFormat == "ass")
{
targetFormat = AdvancedSubStationAlpha.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "ssa")
{
targetFormat = SubStationAlpha.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "srt")
{
targetFormat = SubRip.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "smi")
{
targetFormat = "sami";
}
else if (targetFormat == "itt")
{
targetFormat = ItunesTimedText.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "ttml")
{
targetFormat = TimedText10.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "netflix")
{
targetFormat = NetflixTimedText.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
else if (targetFormat == "sup" || targetFormat == "bluray" || targetFormat == "blu-ray" || targetFormat == "bluraysup" || targetFormat == "bluray-sup" || targetFormat == "bdsup")
{
targetFormat = BatchConvert.BluRaySubtitle;
}
else if (targetFormat == "ebu")
{
targetFormat = Ebu.NameOfFormat.RemoveChar(' ').ToLowerInvariant();
}
var unconsumedArguments = arguments.Skip(4).Select(s => s.Trim()).Where(s => s.Length > 0).ToList();
var offset = GetOffset(unconsumedArguments);
var resolution = GetResolution(unconsumedArguments);
var renumber = GetRenumber(unconsumedArguments);
var adjustDurationMs = GetAdjustDurationMs(unconsumedArguments, "adjustduration");
var targetFrameRate = GetFrameRate(unconsumedArguments, "targetfps");
var frameRate = GetFrameRate(unconsumedArguments, "fps");
if (frameRate.HasValue)
{
Configuration.Settings.General.CurrentFrameRate = frameRate.Value;
}
var ocrEngine = GetOcrEngine(unconsumedArguments);
var ocrDb = GetOcrDb(unconsumedArguments);
var targetEncoding = new TextEncoding(Encoding.UTF8, TextEncoding.Utf8WithBom);
if (Configuration.Settings.General.DefaultEncoding == TextEncoding.Utf8WithoutBom)
{
targetEncoding = new TextEncoding(Encoding.UTF8, TextEncoding.Utf8WithoutBom);
}
try
{
var encodingName = GetArgument(unconsumedArguments, "encoding:");
if (encodingName.Length > 0)
{
if (encodingName.Equals("utf8", StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals("utf-8", StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals("utf-8-bom", StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals(TextEncoding.Utf8WithBom.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals(TextEncoding.Utf8WithBom.Replace(" ", "-"), StringComparison.OrdinalIgnoreCase))
{
targetEncoding = new TextEncoding(Encoding.UTF8, TextEncoding.Utf8WithBom);
}
else if (encodingName.Equals("utf-8-no-bom", StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals(TextEncoding.Utf8WithoutBom.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase) ||
encodingName.Equals(TextEncoding.Utf8WithoutBom.Replace(" ", "-"), StringComparison.OrdinalIgnoreCase))
{
targetEncoding = new TextEncoding(Encoding.UTF8, TextEncoding.Utf8WithoutBom);
}
else
{
targetEncoding = new TextEncoding(Encoding.GetEncoding(encodingName), null);
}
}
}
catch (Exception exception)
{
_stdOutWriter.WriteLine($"Unable to set target encoding ({exception.Message}) - using UTF-8");
}
var outputFolder = string.Empty;
{
var folder = GetArgument(unconsumedArguments, "outputfolder:");
if (folder.Length > 0)
{
if (Directory.Exists(folder))
{
outputFolder = folder;
}
else
{
throw new DirectoryNotFoundException($"The /outputfolder '{folder}' does not exist.");
}
}
}
var inputFolder = _currentFolder;
{
var folder = GetArgument(unconsumedArguments, "inputfolder:");
if (folder.Length > 0)
{
if (Directory.Exists(folder))
{
inputFolder = folder;
}
else
{
throw new DirectoryNotFoundException($"The /inputfolder '{folder}' does not exist.");
}
}
}
int pacCodePage = -1;
{
var pcp = GetArgument(unconsumedArguments, "pac-codepage:");
if (pcp.Length > 0)
{
if (pcp.Equals("Latin", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageLatin;
}
else if (pcp.Equals("Greek", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageGreek;
}
else if (pcp.Equals("Czech", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageLatinCzech;
}
else if (pcp.Equals("Arabic", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageArabic;
}
else if (pcp.Equals("Hebrew", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageHebrew;
}
else if (pcp.Equals("Thai", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageThai;
}
else if (pcp.Equals("Cyrillic", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageCyrillic;
}
else if (pcp.Equals("CHT", StringComparison.OrdinalIgnoreCase) || pcp.RemoveChar(' ').Equals("TraditionalChinese", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageChineseTraditional;
}
else if (pcp.Equals("CHS", StringComparison.OrdinalIgnoreCase) || pcp.RemoveChar(' ').Equals("SimplifiedChinese", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageChineseSimplified;
}
else if (pcp.Equals("Korean", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageKorean;
}
else if (pcp.Equals("Japanese", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageJapanese;
}
else if (pcp.Equals("Turkish", StringComparison.OrdinalIgnoreCase))
{
pacCodePage = Pac.CodePageLatinTurkish;
}
else if (!int.TryParse(pcp, out pacCodePage) || !Pac.IsValidCodePage(pacCodePage))
{
throw new FormatException($"The /pac-codepage value '{pcp}' is invalid.");
}
}
}
var multipleReplaceImportFiles = new HashSet<string>(FilePathComparer.Native);
{
var mra = GetArgument(unconsumedArguments, "multiplereplace:");
if (mra.Length > 0)
{
if (mra.Contains(',') && !File.Exists(mra))
{
foreach (var fn in mra.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var fileName = fn.Trim();
if (fileName.Length > 0)
{
multipleReplaceImportFiles.Add(fileName);
}
}
}
else
{
multipleReplaceImportFiles.Add(mra);
}
}
else if (GetArgument(unconsumedArguments, "multiplereplace").Length > 0)
{
multipleReplaceImportFiles.Add(".");
}
}
var trackNumbers = new HashSet<long>();
foreach (var trackNumber in GetArgument(unconsumedArguments, "track-number:").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(tn => tn.Trim()).Where(tn => tn.Length > 0))
{
if (!int.TryParse(trackNumber, NumberStyles.None, CultureInfo.CurrentCulture, out var number) && !int.TryParse(trackNumber, NumberStyles.None, CultureInfo.InvariantCulture, out number))
{
throw new FormatException($"The track number '{trackNumber}' is invalid.");
}
trackNumbers.Add(number);
}
var actions = GetArgumentActions(unconsumedArguments);
bool overwrite = GetArgument(unconsumedArguments, "overwrite").Length > 0;
bool forcedOnly = GetArgument(unconsumedArguments, "forcedonly").Length > 0;
bool teletextOnly = GetArgument(unconsumedArguments, "teletextonly").Length > 0;
var patterns = new List<string>();
if (pattern.Contains(',') && !File.Exists(pattern))
{
patterns.AddRange(pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(fn => fn.Trim()).Where(fn => fn.Length > 0));
}
else
{
patterns.Add(pattern);
}
var files = new HashSet<string>(FilePathComparer.Native);
foreach (var p in patterns)
{
var folderName = Path.GetDirectoryName(p);
var fileName = Path.GetFileName(p);
if (string.IsNullOrEmpty(folderName) || string.IsNullOrEmpty(fileName))
{
folderName = inputFolder;
fileName = p;
}
else if (!Path.IsPathRooted(folderName))
{
folderName = Path.Combine(inputFolder, folderName);
}
foreach (var fn in Directory.EnumerateFiles(folderName, fileName))
{
files.Add(fn); // silently ignore duplicates
}
}
var ebuHeaderFile = string.Empty;
var ebuHeaderFileTemp = GetArgument(unconsumedArguments, "ebuheaderfile:");
if (ebuHeaderFileTemp.Length > 0)
{
if (!File.Exists(ebuHeaderFileTemp))
{
throw new FileNotFoundException($"The /ebuheaderfile '{ebuHeaderFileTemp}' does not exist.");
}
if (!new Ebu().IsMine(null, ebuHeaderFileTemp))
{
throw new FormatException($"The /ebuheaderfile '{ebuHeaderFileTemp}' is not an EBU STL file.");
}
ebuHeaderFile = ebuHeaderFileTemp;
}
if (unconsumedArguments.Count > 0)
{
foreach (var argument in unconsumedArguments)
{
if (argument.StartsWith('/') || argument.StartsWith('-'))
{
_stdOutWriter.WriteLine($"ERROR: Unknown or multiply defined option '{argument}'.");
}
else
{
_stdOutWriter.WriteLine($"ERROR: Unexpected argument '{argument}'.");
}
}
throw new ArgumentException();
}
var formats = SubtitleFormat.AllSubtitleFormats.ToList();
foreach (var fileName in files)
{
count++;
var fileInfo = new FileInfo(fileName);
if (fileInfo.Exists)
{
var sub = new Subtitle();
var format = default(SubtitleFormat);
bool done = false;
if (fileInfo.Extension.Equals(".mkv", StringComparison.OrdinalIgnoreCase) || fileInfo.Extension.Equals(".mks", StringComparison.OrdinalIgnoreCase))
{
using (var matroska = new MatroskaFile(fileName))
{
if (matroska.IsValid)
{
var mkvFileNames = new HashSet<string>(FilePathComparer.Native);
var tracks = matroska.GetTracks(true);
if (tracks.Count > 0)
{
foreach (var track in tracks.Where(p => !forcedOnly || p.IsForced))
{
if (trackNumbers.Count == 0 || trackNumbers.Contains(track.TrackNumber))
{
var lang = track.Language.RemoveChar('?').RemoveChar('!').RemoveChar('*').RemoveChar(',').RemoveChar('/').Trim();
if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
{
var vobSubs = BatchConvert.LoadVobSubFromMatroska(track, matroska, out var idx);
if (vobSubs.Count > 0)
{
_stdOutWriter.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
using (var vobSubOcr = new VobSubOcr())
{
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.FileName = Path.GetFileName(fileName);
vobSubOcr.InitializeBatch(vobSubs, idx.Palette, Configuration.Settings.VobSubOcr, fileName, false, lang, ocrEngine);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
}
}
var newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + "." + lang + ".mkv";
if (!mkvFileNames.Add(newFileName))
{
newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + ".#" + track.TrackNumber + "." + lang + ".mkv";
mkvFileNames.Add(newFileName);
}
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
{
var bluRaySubtitles = BatchConvert.LoadBluRaySupFromMatroska(track, matroska, IntPtr.Zero);
if (bluRaySubtitles.Count > 0)
{
var newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + "." + lang + ".mkv";
if (string.Equals(targetFormat.RemoveChar(' '), BatchConvert.BluRaySubtitle.RemoveChar(' '), StringComparison.InvariantCultureIgnoreCase))
{
var outputFileName = FormatOutputFileNameForBatchConvert(Utilities.GetPathAndFileNameWithoutExtension(newFileName) + Path.GetExtension(newFileName), ".sup", outputFolder, overwrite);
converted++;
_stdOutWriter?.Write($"{count}: {Path.GetFileName(fileName)} -> {outputFileName}...");
BluRaySupToBluRaySup.ConvertFromBluRaySupToBluRaySup(outputFileName, bluRaySubtitles, resolution);
_stdOutWriter?.WriteLine(" done.");
}
else
{
_stdOutWriter.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
using (var vobSubOcr = new VobSubOcr())
{
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.FileName = Path.GetFileName(fileName);
vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName, false, lang, ocrEngine);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
}
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, renumber: renumber, adjustDurationMs: adjustDurationMs);
}
if (!mkvFileNames.Add(newFileName))
{
newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + ".#" + track.TrackNumber + "." + lang + ".mkv";
mkvFileNames.Add(newFileName);
}
}
done = true;
}
else
{
var ss = matroska.GetSubtitle(track.TrackNumber, null);
format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub);
var newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + "." + lang + ".mkv";
if (!mkvFileNames.Add(newFileName))
{
newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + ".#" + track.TrackNumber + "." + lang + ".mkv";
mkvFileNames.Add(newFileName);
}
if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
{
if (!AdvancedSubStationAlpha.NameOfFormat.RemoveChar(' ').Equals(targetFormat, StringComparison.OrdinalIgnoreCase) &&
!SubStationAlpha.NameOfFormat.RemoveChar(' ').Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
{
foreach (SubtitleFormat sf in formats)
{
if (sf.Name.RemoveChar(' ').Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
{
format.RemoveNativeFormatting(sub, sf);
break;
}
}
}
}
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
}
}
}
else
{
_stdOutWriter.WriteLine($"No subtitle tracks in Matroska file '{fileName}'.");
done = true;
}
}
else
{
_stdOutWriter.WriteLine($"Invalid Matroska file '{fileName}'!");
done = true;
}
}
}
if (!done && FileUtil.IsBluRaySup(fileName))
{
_stdOutWriter.WriteLine("Found Blu-Ray subtitle format");
ConvertBluRaySubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, forcedOnly, ocrEngine, ocrDb, resolution, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
else if (!done && FileUtil.IsVobSub(fileName))
{
_stdOutWriter.WriteLine("Found VobSub subtitle format");
ConvertVobSubSubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, forcedOnly, ocrEngine, ocrDb, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
if ((fileInfo.Extension == ".mp4" || fileInfo.Extension == ".m4v" || fileInfo.Extension == ".3gp") && fileInfo.Length > 10000)
{
var mp4Parser = new MP4Parser(fileName);
var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
foreach (var track in mp4SubtitleTracks)
{
if (trackNumbers.Count == 0 || trackNumbers.Contains(track.Tkhd.TrackId))
{
if (track.Mdia.IsVobSubSubtitle)
{
var subPicturesWithTimeCodes = new List<VobSubOcr.SubPicturesWithSeparateTimeCodes>();
var paragraphs = track.Mdia.Minf.Stbl.GetParagraphs();
for (int i = 0; i < paragraphs.Count; i++)
{
if (track.Mdia.Minf.Stbl.SubPictures.Count > i)
{
var start = paragraphs[i].StartTime.TimeSpan;
var end = paragraphs[i].EndTime.TimeSpan;
subPicturesWithTimeCodes.Add(new VobSubOcr.SubPicturesWithSeparateTimeCodes(track.Mdia.Minf.Stbl.SubPictures[i], start, end));
}
}
_stdOutWriter.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
using (var vobSubOcr = new VobSubOcr())
{
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.FileName = Path.GetFileName(fileName);
vobSubOcr.InitializeBatch(subPicturesWithTimeCodes, fileName, ocrDb, ocrEngine);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
}
var newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + ".mp4";
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
else
{
var newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + ".mp4";
sub.Paragraphs.AddRange(track.Mdia.Minf.Stbl.GetParagraphs());
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, renumber: renumber, adjustDurationMs: adjustDurationMs);
done = true;
}
}
}
}
if (!done && (Path.GetExtension(fileName).Equals(".ts", StringComparison.OrdinalIgnoreCase) ||
Path.GetExtension(fileName).Equals(".mts", StringComparison.OrdinalIgnoreCase) ||
Path.GetExtension(fileName).Equals(".m2ts", StringComparison.OrdinalIgnoreCase)) && (FileUtil.IsTransportStream(fileName) || FileUtil.IsM2TransportStream(fileName)))
{
var ok = TsConvert.ConvertFromTs(targetFormat, fileName, outputFolder, overwrite, ref count, ref converted, ref errors, formats, _stdOutWriter, null, resolution, targetEncoding, actions, offset, pacCodePage, targetFrameRate, multipleReplaceImportFiles, ocrEngine, teletextOnly);
if (ok)
{
converted++;
}
done = true;
}
if (!done && fileInfo.Length < 10 * 1024 * 1024) // max 10 mb
{
format = sub.LoadSubtitle(fileName, out _, null, true, frameRate);
if (format == null || format.GetType() == typeof(Ebu))
{
var ebu = new Ebu();
if (ebu.IsMine(null, fileName))
{
ebu.LoadSubtitle(sub, null, fileName);
format = ebu;
}
}
if (format == null)
{
foreach (var f in SubtitleFormat.GetBinaryFormats(true))
{
if (f.IsMine(null, fileName))
{
if (f is Pac pacFormat)
{
pacFormat.CodePage = pacCodePage;
}
f.LoadSubtitle(sub, null, fileName);
format = f;
break;
}
}
}
if (format == null)
{
var encoding = LanguageAutoDetect.GetEncodingFromFile(fileName);
var lines = FileUtil.ReadAllTextShared(fileName, encoding).SplitToLines();
foreach (var f in SubtitleFormat.GetTextOtherFormats())
{
if (f.IsMine(lines, fileName))
{
f.LoadSubtitle(sub, lines, fileName);
format = f;
break;
}
}
}
if (format != null && IsImageBased(format))
{
var tFormat = GetTargetformat(targetFormat, formats);
if (!IsImageBased(tFormat) && tFormat != null)
{
_stdOutWriter.WriteLine($"Found image based subtitle format: {format.FriendlyName}");
var subtitle = new Subtitle();
format.LoadSubtitle(subtitle, File.ReadAllText(fileName).SplitToLines(), fileName);
if (subtitle != null)
{
subtitle.FileName = fileName;
ConvertImageListSubtitle(fileName, subtitle, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, string.Empty, ocrEngine, renumber, adjustDurationMs);
}
done = true;
}
}
}
if (!done && format == null)
{
if (fileInfo.Length < 1024 * 1024) // max 1 mb
{
_stdOutWriter.WriteLine($"{fileName}: {targetFormat} - input file format unknown!");
}
else
{
_stdOutWriter.WriteLine($"{fileName}: {targetFormat} - input file too large!");
}
}
else if (!done)
{
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, ebuHeaderFile: ebuHeaderFile, renumber: renumber, adjustDurationMs: adjustDurationMs);
}
}
else
{
_stdOutWriter.WriteLine($"{count}: {fileName} - file not found!");
errors++;
}
}
}
catch (Exception exception)
{
if (exception.Message.Length > 0)
{
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine($"ERROR: {exception.Message}{Environment.NewLine}{exception.StackTrace}");
}
else
{
_stdOutWriter.WriteLine("Try 'SubtitleEdit /?' or 'SubtitleEdit -?' for more information.");
}
_stdOutWriter.WriteLine();
errors++;
}
if (count > 0)
{
_stdOutWriter.WriteLine();
_stdOutWriter.WriteLine($"{converted} file(s) converted");
_stdOutWriter.WriteLine();
}
return (count == converted && errors == 0) ? 0 : 1;
}
private static SubtitleFormat GetTargetformat(string targetFormat, IEnumerable<SubtitleFormat> formats)
{
string targetFormatNoWhiteSpace = targetFormat.RemoveChar(' ');
foreach (var sf in formats)
{
if (sf.IsTextBased && sf.Name.RemoveChar(' ').Equals(targetFormatNoWhiteSpace, StringComparison.OrdinalIgnoreCase))
{
return sf;
}
}
return null;
}
private static void ConvertBluRaySubtitle(string fileName, string targetFormat, TimeSpan offset, TextEncoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, List<SubtitleFormat> formats, bool overwrite, int pacCodePage, double? targetFrameRate, ICollection<string> multipleReplaceImportFiles, List<BatchAction> actions, bool forcedOnly, string ocrEngine, string ocrDb, Point? resolution, int? renumber, double? adjustDurationMs)
{
var format = Utilities.GetSubtitleFormatByFriendlyName(targetFormat) ?? new SubRip();
_stdOutWriter?.WriteLine($"Loading subtitles from file \"{fileName}\"");
var log = new StringBuilder();
var bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log);
Subtitle sub;
using (var vobSubOcr = new VobSubOcr())
{
_stdOutWriter?.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.FileName = Path.GetFileName(fileName);
vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName, forcedOnly, ocrDb, ocrEngine);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
_stdOutWriter?.WriteLine($"Extracted subtitles from file \"{fileName}\"");
}
if (sub != null)
{
_stdOutWriter?.WriteLine("Converted subtitle");
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, renumber: renumber, adjustDurationMs: adjustDurationMs);
}
}
private static void ConvertVobSubSubtitle(string fileName, string targetFormat, TimeSpan offset, TextEncoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, List<SubtitleFormat> formats, bool overwrite, int pacCodePage, double? targetFrameRate, ICollection<string> multipleReplaceImportFiles, List<BatchAction> actions, bool forcedOnly, string ocrEngine, string ocrDb, int? renumber, double? adjustDurationMs)
{
var format = Utilities.GetSubtitleFormatByFriendlyName(targetFormat) ?? new SubRip();
_stdOutWriter?.WriteLine($"Loading subtitles from file \"{fileName}\"");
Subtitle sub;
using (var vobSubOcr = new VobSubOcr())
{
_stdOutWriter?.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr, forcedOnly, ocrEngine, ocrDb);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
_stdOutWriter?.WriteLine($"Extracted subtitles from file \"{fileName}\"");
}
if (sub != null)
{
_stdOutWriter?.WriteLine("Converted subtitle");
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, renumber: renumber, adjustDurationMs: adjustDurationMs);
}
}
private static void ConvertImageListSubtitle(string fileName, Subtitle subtitle, string targetFormat, TimeSpan offset, TextEncoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, List<SubtitleFormat> formats, bool overwrite, int pacCodePage, double? targetFrameRate, ICollection<string> multipleReplaceImportFiles, List<BatchAction> actions, string language, string ocrEngine, int? renumber, double? adjustDurationMs)
{
var format = Utilities.GetSubtitleFormatByFriendlyName(targetFormat) ?? new SubRip();
_stdOutWriter?.WriteLine($"Loading subtitles from file \"{fileName}\"");
Subtitle sub;
using (var vobSubOcr = new VobSubOcr())
{
_stdOutWriter?.WriteLine($"Using OCR via {ocrEngine} to extract subtitles");
vobSubOcr.ProgressCallback = progress =>
{
_stdOutWriter?.Write($"\r{LanguageSettings.Current.BatchConvert.Ocr} : {progress}");
};
vobSubOcr.InitializeBatch(subtitle, Configuration.Settings.VobSubOcr, GetTargetformat(targetFormat, formats).Name == new Son().Name, language, ocrEngine);
_stdOutWriter?.WriteLine();
sub = vobSubOcr.SubtitleFromOcr;
_stdOutWriter?.WriteLine($"Extracted subtitles from file \"{fileName}\"");
}
if (sub != null)
{
_stdOutWriter?.WriteLine("Converted subtitle");
BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, renumber: renumber, adjustDurationMs: adjustDurationMs);
}
}
/// <summary>
/// Gets a frame rate argument from the command line
/// </summary>
/// <param name="commandLineArguments">All unresolved arguments from the command line</param>
/// <param name="requestedFrameRateName">The name of the frame rate argument that is requested</param>
private static double? GetFrameRate(IList<string> commandLineArguments, string requestedFrameRateName)
{
const double minimumFrameRate = 1.0;
const double maximumFrameRate = 200.0;
var fps = GetArgument(commandLineArguments, requestedFrameRateName + ':');
if (fps.Length > 0)
{
if (fps.Length > 1)
{
fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var d) && d >= minimumFrameRate && d <= maximumFrameRate)
{
return d;
}
}
throw new FormatException($"The /{requestedFrameRateName} value '{fps}' is invalid - number between {minimumFrameRate} and {maximumFrameRate} expected.");
}
return null;
}
private static double? GetAdjustDurationMs(IList<string> commandLineArguments, string name)
{
const double minimumValue = -10_000.0;
const double maximumValue = 20_000.0;
var fps = GetArgument(commandLineArguments, name + ':');
if (fps.Length > 0)
{
if (fps.Length > 1)
{
fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
if (double.TryParse(fps, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var d) && d >= minimumValue && d <= maximumValue)
{
return d;
}
}
throw new FormatException($"The /{name} value '{fps}' is invalid - number between {minimumValue} and {maximumValue} expected.");
}
return null;
}
private static string GetOcrEngine(IList<string> commandLineArguments)
{
var ocrEngine = GetArgument(commandLineArguments, "ocrengine:");
if (ocrEngine.Length > 0)
{
if (string.Equals(ocrEngine, "tesseract", StringComparison.InvariantCultureIgnoreCase) || string.Equals(ocrEngine, "nocr", StringComparison.InvariantCultureIgnoreCase))
{
return ocrEngine;
}
throw new FormatException($"The /ocrengine value '{ocrEngine}' is invalid - 'tesseract' or 'nOCR' expected.");
}
return "tesseract";
}
private static string GetOcrDb(IList<string> commandLineArguments)
{
var ocrDb = GetArgument(commandLineArguments, "ocrdb:");
if (ocrDb.Length > 0)
{
return ocrDb;
}
return null;
}
/// <summary>
/// Gets an offset argument from the command line (/offset:[+|-][[[hh:]mm:]ss.]ms)
/// </summary>
/// <param name="commandLineArguments">All unresolved arguments from the command line</param>
private static TimeSpan GetOffset(IList<string> commandLineArguments)
{
var offsetArgument = GetArgument(commandLineArguments, "offset:", "0");
var offset = offsetArgument;
var negate = false;
while (offset.Length > 0)
{
if (offset[0] == '-')
{
offset = offset.Substring(1);
negate = !negate;
continue;
}
if (offset[0] == '+')
{
offset = offset.Substring(1);
continue;
}
break;
}
if (int.TryParse(offset, NumberStyles.None, CultureInfo.CurrentCulture, out var number) || int.TryParse(offset, NumberStyles.None, CultureInfo.InvariantCulture, out number))
{
var result = TimeSpan.FromMilliseconds(number);
if (negate)
{
result = result.Negate();
}