-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
350 lines (294 loc) · 13.9 KB
/
Program.cs
File metadata and controls
350 lines (294 loc) · 13.9 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
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace SplitBySilence;
internal class Program
{
private static async Task<int> Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
if (args.Length == 0 || HasFlag(args, "-h", "--help"))
{
PrintHelp();
return 0;
}
var input = GetOption(args, "--input") ?? args[0];
if (string.IsNullOrWhiteSpace(input) || !File.Exists(input))
{
await Console.Error.WriteLineAsync("Input file is required and must exist. Use --input <path> or pass it as the first argument.");
return 2;
}
var outDir = GetOption(args, "--outdir") ??
Path.Combine(Path.GetDirectoryName(Path.GetFullPath(input))!,
Path.GetFileNameWithoutExtension(input) + "_split");
Directory.CreateDirectory(outDir);
var silenceDb = ParseDouble(GetOption(args, "--silenceDb"), -35.0); // dB threshold for silence
var minSilence = ParseDouble(GetOption(args, "--minSilence"), 1.5); // seconds: gap considered a split
var minTrack = ParseDouble(GetOption(args, "--minTrack"), 60.0); // seconds: ignore splits that create tiny tracks
var pad = ParseDouble(GetOption(args, "--pad"), 0.0); // seconds: optionally pad start/end of cuts
var ffmpegPath = GetOption(args, "--ffmpeg") ?? "ffmpeg";
var ffprobePath = GetOption(args, "--ffprobe") ?? "ffprobe";
var dryRun = HasFlag(args, "--dry-run");
var verbose = HasFlag(args, "--verbose");
// 0) Verify ffmpeg/ffprobe are available
if (!await ToolExists(ffmpegPath))
{
await Console.Error.WriteLineAsync("ffmpeg not found. Install FFmpeg and ensure it's on PATH, or pass --ffmpeg <path>.");
return 3;
}
if (!await ToolExists(ffprobePath))
{
await Console.Error.WriteLineAsync("ffprobe not found. Install FFmpeg (includes ffprobe) or pass --ffprobe <path>.");
return 4;
}
// 1) Get total duration (seconds)
var durationStr = await RunAndCapture(ffprobePath,
$"-v error -show_entries format=duration -of default=nw=1:nk=1 \"{input}\"");
if (!double.TryParse(durationStr.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var totalDuration))
{
await Console.Error.WriteLineAsync("Could not read media duration via ffprobe.");
return 5;
}
// 2) Detect silences (ffmpeg logs to stderr)
var detectArgs =
$"-hide_banner -nostats -i \"{input}\" -af \"silencedetect=noise={silenceDb.ToString("0.##", CultureInfo.InvariantCulture)}dB:d={minSilence.ToString("0.###", CultureInfo.InvariantCulture)}\" -f null -";
var detectionLog = await RunAndCapture(ffmpegPath, detectArgs, captureStdOut: false); // capture stderr
// 3) Parse silence_start / silence_end from ffmpeg output
var silences = ParseSilences(detectionLog, verbose);
// 4) Convert silences to music segments [start, end)
var segments = BuildSegmentsFromSilence(silences, totalDuration, minTrack, pad, verbose);
if (segments.Count == 0)
{
Console.WriteLine("No valid segments detected (try lowering --silenceDb or --minSilence).");
return 0;
}
// 5) Export segments with stream copy (no re-encode)
Console.WriteLine($"→ Exporting {segments.Count} track(s) to: {outDir}");
var baseName = Path.GetFileNameWithoutExtension(input);
// Manifest file (CSV)
var manifestPath = Path.Combine(outDir, $"{baseName}_tracks.csv");
await File.WriteAllTextAsync(manifestPath, "Index,Start,End,Duration,File\n", Encoding.UTF8);
var index = 1;
foreach (var seg in segments)
{
var name = $"{baseName}_track_{index:00}.mp3";
var outPath = Path.Combine(outDir, SanitizeFilename(name));
// Use accurate seeking: put -ss/-to after -i when copying
// NOTE: -to is absolute end timestamp (not duration) when placed after -i.
var ss = ToFfmpegTs(seg.Start);
var to = ToFfmpegTs(seg.End);
var cutArgs = $"-hide_banner -y -i \"{input}\" -ss {ss} -to {to} -c copy -avoid_negative_ts make_zero \"{outPath}\"";
Console.WriteLine($"[{index:00}] {ss} → {to} ({Human(seg.End - seg.Start)})");
if (!dryRun)
{
var cutLog = await RunAndCapture(ffmpegPath, cutArgs);
if (verbose) Console.WriteLine(cutLog);
if (!File.Exists(outPath))
{
await Console.Error.WriteLineAsync($"Failed to create: {outPath}");
}
}
await File.AppendAllTextAsync(manifestPath,
$"{index},{ss},{to},{Human(seg.End - seg.Start)},{Path.GetFileName(outPath)}\n", Encoding.UTF8);
index++;
}
Console.WriteLine($"Done. Manifest: {manifestPath}");
return 0;
}
private static void PrintHelp()
{
Console.WriteLine("""
MP3 Splitter by Silence (no re-encode) — .NET 9
Usage:
dotnet run --project SplitBySilence.csproj -- --input "C:\music\long_mix.mp3" [options]
Options:
--input Path to input .mp3 (or as 1st positional arg)
--outdir Output directory (default: <inputDir>\<inputName>_split)
--silenceDb Silence threshold in dBFS (default: -35)
--minSilence Minimum silence duration in seconds (default: 1.5)
--minTrack Minimum track length in seconds (default: 60)
--pad Add/subtract seconds at cut boundaries (default: 0)
--ffmpeg Path to ffmpeg (default: ffmpeg)
--ffprobe Path to ffprobe (default: ffprobe)
--dry-run Detect & plan only (don’t write files)
--verbose Print extra logs
-h, --help Show this help
Tips:
• If tracks aren’t splitting, try lower --silenceDb (e.g., -40) or bigger --minSilence (e.g., 2).
• If tracks start/stop a hair early/late, try --pad 0.15 (adds 150ms before/after).
""");
}
// ---------- Core logic ----------
private static List<SilenceSpan> ParseSilences(string ffmpegLog, bool verbose)
{
var starts = new List<double>();
var spans = new List<SilenceSpan>();
var startRx = new Regex(@"silence_start:\s*([0-9]+(?:\.[0-9]+)?)", RegexOptions.Compiled);
var endRx = new Regex(@"silence_end:\s*([0-9]+(?:\.[0-9]+)?)", RegexOptions.Compiled);
using var sr = new StringReader(ffmpegLog);
while (sr.ReadLine() is { } line)
{
var m1 = startRx.Match(line);
if (m1.Success)
{
var t = double.Parse(m1.Groups[1].Value, CultureInfo.InvariantCulture);
starts.Add(t);
if (verbose) Console.WriteLine($" silence_start @ {t:0.###}s");
continue;
}
var m2 = endRx.Match(line);
if (m2.Success && starts.Count > 0)
{
var t = double.Parse(m2.Groups[1].Value, CultureInfo.InvariantCulture);
var s = starts[0];
starts.RemoveAt(0);
spans.Add(new SilenceSpan(s, t));
if (verbose) Console.WriteLine($" silence_end @ {t:0.###}s (span {s:0.###} → {t:0.###})");
}
}
// Any trailing start without end is ignored (often logging truncation)
spans.Sort((a, b) => a.Start.CompareTo(b.Start));
return spans;
}
private static List<Segment> BuildSegmentsFromSilence(
List<SilenceSpan> silences,
double totalDuration,
double minTrack,
double pad,
bool verbose)
{
var segments = new List<Segment>();
var currentStart = 0.0;
// If audio starts with initial silence, skip it
if (silences.Count > 0 && silences[0].Start <= 1.0 && silences[0].End <= totalDuration)
{
currentStart = silences[0].End; // trim leading silence
}
foreach (var s in silences)
{
var segEnd = s.Start;
var duration = segEnd - currentStart;
if (duration >= minTrack)
{
// Optional padding (keeps inside [0, total])
var startPadded = Math.Max(0.0, currentStart - pad);
var endPadded = Math.Min(totalDuration, segEnd + pad);
segments.Add(new Segment(startPadded, endPadded));
currentStart = s.End; // start next after the silent gap
}
else
{
// Too small to be a real track -> treat as short pause, keep accumulating
if (verbose)
Console.WriteLine($" Ignored short piece {duration:0.###}s at {currentStart:0.###} → {segEnd:0.###}");
}
}
// Tail segment
var end = totalDuration;
if (totalDuration - currentStart >= Math.Max(5.0, Math.Min(30.0, minTrack / 2))) // avoid tiny tail slivers
{
// If the last silence is very near the end, trim trailing silence
var lastSilence = silences.LastOrDefault();
if (lastSilence != default && (end - lastSilence.End) < 1.0) // trailing silence ~<1s after lastSilence
end = lastSilence.Start;
var startPadded = Math.Max(0.0, currentStart - pad);
var endPadded = Math.Min(totalDuration, end + pad);
if (endPadded > startPadded)
segments.Add(new Segment(startPadded, endPadded));
}
// Merge accidental micro-gaps
segments = MergeAdjacent(segments, gapThreshold: 0.25);
if (verbose)
{
Console.WriteLine("Planned segments:");
for (var i = 0; i < segments.Count; i++)
Console.WriteLine($" [{i + 1:00}] {segments[i].Start:0.###} → {segments[i].End:0.###} ({Human(segments[i].End - segments[i].Start)})");
}
return segments;
}
private static List<Segment> MergeAdjacent(List<Segment> segs, double gapThreshold)
{
if (segs.Count <= 1) return segs;
var merged = new List<Segment> { segs[0] };
for (var i = 1; i < segs.Count; i++)
{
var prev = merged[^1];
var cur = segs[i];
var gap = cur.Start - prev.End;
if (gap >= 0 && gap <= gapThreshold)
{
merged[^1] = new Segment(prev.Start, cur.End);
}
else
{
merged.Add(cur);
}
}
return merged;
}
// ---------- Helpers ----------
private static async Task<bool> ToolExists(string exe)
{
try
{
var (exitCode, _, _) = await Run(exe, "-version");
return exitCode == 0;
}
catch { return false; }
}
private static async Task<string> RunAndCapture(string exe, string args, bool captureStdOut = true)
{
var (exit, stdout, stderr) = await Run(exe, args);
// ffmpeg prints to stderr for processing; honor captureStdOut toggle
return captureStdOut ? stdout : stdout + Environment.NewLine + stderr;
}
private static async Task<(int exit, string stdout, string stderr)> Run(string exe, string args)
{
var psi = new ProcessStartInfo
{
FileName = exe,
Arguments = args,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
};
using var p = Process.Start(psi)!;
var stdoutTask = p.StandardOutput.ReadToEndAsync();
var stderrTask = p.StandardError.ReadToEndAsync();
await Task.WhenAll(stdoutTask, stderrTask);
await p.WaitForExitAsync();
return (p.ExitCode, stdoutTask.Result, stderrTask.Result);
}
private static string GetOption(string[] args, string name)
{
// Supports: --name value or --name=value
for (var i = 0; i < args.Length; i++)
{
var a = args[i];
if (a.StartsWith(name + "=", StringComparison.OrdinalIgnoreCase))
return a[(name.Length + 1)..].Trim('"');
if (a.Equals(name, StringComparison.OrdinalIgnoreCase) && i + 1 < args.Length)
return args[i + 1].Trim('"');
}
return null!;
}
private static bool HasFlag(string[] args, params string[] flags)
=> args.Any(a => flags.Any(f => string.Equals(a, f, StringComparison.OrdinalIgnoreCase)));
private static double ParseDouble(string? s, double def)
=> double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : def;
private static string ToFfmpegTs(double seconds)
=> seconds.ToString("0.###", CultureInfo.InvariantCulture);
private static string Human(double seconds)
{
var ts = TimeSpan.FromSeconds(Math.Max(0, seconds));
return ts.ToString(ts.TotalHours >= 1 ? @"h\:mm\:ss" : @"m\:ss");
}
private static string SanitizeFilename(string name)
{
return Path.GetInvalidFileNameChars().Aggregate(name, (current, c) => current.Replace(c, '_'));
}
private readonly record struct SilenceSpan(double Start, double End);
private readonly record struct Segment(double Start, double End);
}