-
Notifications
You must be signed in to change notification settings - Fork 7
/
Download.cs
301 lines (255 loc) · 11.3 KB
/
Download.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
using System.Globalization;
using System.Text.RegularExpressions;
using Serilog;
using Xabe.FFmpeg;
using YoutubeDLSharp;
using YoutubeDLSharp.Options;
using YoutubeSegmentDownloader.Extension;
using YtdlpVideoData = YoutubeSegmentDownloader.Models.YtdlpVideoData.ytdlpVideoData;
namespace YoutubeSegmentDownloader;
internal partial class Download(string id,
float start,
float end,
DirectoryInfo outputDirectory,
string format,
string browser)
{
public bool Finished;
public string? OutputFilePath;
public bool Succeeded;
private string Link =>
id.Contains('/')
? id
: @$"https://youtu.be/{id}";
public async Task StartAsync(CancellationToken? cancellationToken = default)
{
cancellationToken ??= CancellationToken.None;
Log.Information("Start the download process...");
Succeeded = false;
Finished = false;
string tempFilePath1 = Path.ChangeExtension(Path.GetTempFileName(), ".mp4");
string tempFilePath2 = Path.ChangeExtension(Path.GetTempFileName(), ".mp4");
Log.Debug("Create temporary files:");
Log.Debug("{TempFilePath}", tempFilePath1);
Log.Debug("{TempFilePath}", tempFilePath2);
try
{
OptionSet optionSet = CreateOptionSet();
YoutubeDL ytdl = new()
{
YoutubeDLPath = Path.Combine(ExternalProgram.YtdlpPath ?? "./", "yt-dlp.exe"),
FFmpegPath = Path.Combine(ExternalProgram.FFmpegPath ?? "./", "ffmpeg.exe"),
//OutputFolder = outputDirectory.FullName,
OutputFileTemplate = tempFilePath1,
OverwriteFiles = true,
IgnoreDownloadErrors = true
};
YtdlpVideoData? videoData = await FetchVideoInfoAsync(ytdl, optionSet, cancellationToken);
if (null == videoData) return;
OutputFilePath = CalculatePath(videoData.Title,
DateTime.ParseExact(videoData.UploadDate ?? "19700101",
"yyyyMMdd",
CultureInfo.InvariantCulture),
videoData.Id);
bool downloadSuccess = await DownloadVideoAsync(ytdl, optionSet, cancellationToken);
if (!downloadSuccess) return;
if (end == 0)
{
Log.Information("Move file to {filePath}", OutputFilePath);
File.Move(tempFilePath1, OutputFilePath, true);
}
else
{
_ = await CutWithFFmpegAsync(tempFilePath1, tempFilePath2, cancellationToken);
File.Move(tempFilePath2, OutputFilePath, true);
}
Log.Information("Download completed:");
Log.Information(OutputFilePath);
Succeeded = true;
}
catch (Exception e)
{
if (e is TaskCanceledException or OperationCanceledException)
throw;
Log.Error("vvvvvvvvvvvvvvvvvvvvv");
Log.Error(e.Message);
Log.Error("^^^^^^^^^^^^^^^^^^^^^");
}
finally
{
// Wait 500 ms to ensure the file is released
await Task.Delay(500);
File.Delete(tempFilePath1);
File.Delete(tempFilePath2);
File.Delete(Path.ChangeExtension(tempFilePath1, "tmp"));
File.Delete(Path.ChangeExtension(tempFilePath2, "tmp"));
Log.Information("Clean up temporary files.");
Log.Information("Process ends.");
Finished = true;
}
}
private OptionSet CreateOptionSet()
{
OptionSet optionSet = new()
{
NoCheckCertificates = true,
ExtractorArgs = "youtube:skip=dash",
Color = "never"
};
if (!string.IsNullOrEmpty(format))
{
optionSet.Format = format;
}
else
{
// Workaround for FFmpeg sometimes uses 251 as bestvideo
optionSet.AddCustomOption("-S", "res");
}
if (!string.IsNullOrEmpty(browser))
{
optionSet.AddCustomOption("--cookies-from-browser", browser);
}
if (end != 0)
{
optionSet.Downloader = "ffmpeg";
optionSet.DownloaderArgs = $"ffmpeg_i:-ss {start} -to {end}";
}
return optionSet;
}
/// <summary>
/// 取得影片資訊
/// </summary>
/// <param name="ytdl"></param>
/// <param name="optionSet"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<YtdlpVideoData?> FetchVideoInfoAsync(YoutubeDL ytdl, OptionSet optionSet, CancellationToken? cancellationToken = default)
{
Log.Information("Start getting video information...");
RunResult<YtdlpVideoData> result =
await ytdl.RunVideoDataFetch_Alt(Link, overrideOptions: optionSet, ct: cancellationToken ?? CancellationToken.None);
if (!result.Success)
{
Log.Error("vvvvvvvvvvvvvvvvvvvvv");
Log.Error(string.Join("\n", result.ErrorOutput));
Log.Error("^^^^^^^^^^^^^^^^^^^^^");
Log.Error("Failed to get video information! VideoId: {id}", id);
Log.Error("Please ensure that your network connection is stable and that you have the necessary permissions to access the video.");
Log.Error("Additionally, if you are using the 'Cookies from browser' feature, please close your browser.");
return null;
}
float duration = result.Data.Duration ?? 0;
Log.Information("{title}", result.Data.Title);
Log.Information("{duration}", duration);
if (result.Data.Duration < start)
{
Log.Error("Segment input invalid!");
Log.Error("Start, End time should be smaller then video duration.");
return null;
}
return result.Data;
}
/// <summary>
/// 下載影片
/// </summary>
/// <param name="ytdl"></param>
/// <param name="optionSet"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<bool> DownloadVideoAsync(YoutubeDL ytdl, OptionSet optionSet, CancellationToken? cancellationToken = default)
{
Log.Information("Start downloading video...");
var lastProgress = 0.0f;
RunResult<string>? result =
await ytdl.RunVideoDownload(Link,
mergeFormat: DownloadMergeFormat.Mp4,
progress: new Progress<DownloadProgress>(s => Log.Verbose(s.Data)),
output: new Progress<string>(rawProgress =>
{
Match m = DownloadPercentage().Match(rawProgress);
if (!m.Success)
{
Log.Verbose(rawProgress);
return;
}
var currentProgress = float.Parse(m.Groups[1].Value);
if (isProgressEqualOrMinorChange(currentProgress, lastProgress))
return;
lastProgress = currentProgress;
Log.Verbose(rawProgress);
}),
overrideOptions: optionSet,
ct: cancellationToken ?? CancellationToken.None);
if (!result.Success)
{
Log.Error("Failed to download video! Please try again later.");
foreach (string? str in result.ErrorOutput)
{
Log.Information(str);
}
return false;
}
Log.Information("Video downloaded.");
return true;
static bool isProgressEqualOrMinorChange(float currentProgress, float lastProgress)
=> Math.Abs(currentProgress - lastProgress) < float.Epsilon
|| (currentProgress < lastProgress && lastProgress - currentProgress < 1);
}
/// <summary>
/// 剪切影片
/// </summary>
/// <param name="inputPath"></param>
/// <param name="outputPath"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<IConversionResult> CutWithFFmpegAsync(string inputPath, string outputPath, CancellationToken? cancellationToken = default)
{
Log.Information("Start cutting video with FFmpeg...");
float duration = end - start;
FFmpeg.SetExecutablesPath(ExternalProgram.FFmpegPath);
IMediaInfo? mediaInfo = await FFmpeg.GetMediaInfo(inputPath);
// How to Encode Videos for YouTube, Facebook, Vimeo, twitch, and other Video Sharing Sites
// https://trac.ffmpeg.org/wiki/Encode/YouTube
IConversion? conversion = FFmpeg.Conversions.New()
.AddParameter($"-sseof -{duration}", ParameterPosition.PreInput)
.AddStream(mediaInfo.Streams)
.AddParameter("-c:v libx264 -preset slow -crf 18 -c:a aac -b:a 192k -pix_fmt yuv420p")
.AddParameter("-movflags +faststart")
.SetOutput(outputPath)
.SetOverwriteOutput(true);
conversion.OnDataReceived += (_, e) =>
{
if (e.Data != null) Log.Verbose(e.Data);
};
Log.Debug("FFmpeg arguments: {arguments}", conversion.Build());
return await conversion.Start(cancellationToken ?? CancellationToken.None);
}
/// <summary>
/// 路徑做檢查和轉換
/// </summary>
/// <param name="title">影片標題,用做檔名</param>
/// <param name="date">影片日期,用做檔名</param>
/// <param name="videoId"></param>
/// <returns></returns>
private string CalculatePath(string? title, DateTime? date, string? videoId)
{
title ??= "";
// 取代掉檔名中的非法字元
title = string.Join(string.Empty, title.Split(Path.GetInvalidFileNameChars()))
.Replace(".", string.Empty);
// 截短
if (title.Length > 80)
{
Log.Warning("The title is too long! Limit it to 80 characters.");
title = title[..80];
}
// skipcq: CS-W1091
date ??= DateTime.Now;
string newPath = Path.Combine(outputDirectory.FullName,
$"{date:yyyyMMdd} {title} ({videoId ?? id}) [{start}_{end}].mp4");
Log.Debug("Calculate output file path as {newPath}", newPath);
return newPath;
}
[GeneratedRegex(@"^\[download\]\s+(\d+\.\d+)%")]
private static partial Regex DownloadPercentage();
}