-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
Converter.cs
346 lines (299 loc) · 10.8 KB
/
Converter.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CliWrap.Builders;
using YoutubeExplode.Converter.Utils;
using YoutubeExplode.Converter.Utils.Extensions;
using YoutubeExplode.Videos;
using YoutubeExplode.Videos.ClosedCaptions;
using YoutubeExplode.Videos.Streams;
namespace YoutubeExplode.Converter;
internal partial class Converter(VideoClient videoClient, FFmpeg ffmpeg, ConversionPreset preset)
{
private async ValueTask ProcessAsync(
string filePath,
Container container,
IReadOnlyList<StreamInput> streamInputs,
IReadOnlyList<SubtitleInput> subtitleInputs,
IProgress<double>? progress = null,
CancellationToken cancellationToken = default
)
{
var arguments = new ArgumentsBuilder();
// Stream inputs
foreach (var streamInput in streamInputs)
{
arguments.Add("-i").Add(streamInput.FilePath);
}
// Subtitle inputs
foreach (var subtitleInput in subtitleInputs)
{
arguments
// Fix invalid subtitle durations for each input
// https://github.com/Tyrrrz/YoutubeExplode/issues/756
.Add("-fix_sub_duration")
.Add("-i")
.Add(subtitleInput.FilePath);
}
// Explicitly specify that all inputs should be used, because by default
// FFmpeg only picks one input per stream type (audio, video, subtitle).
for (var i = 0; i < streamInputs.Count + subtitleInputs.Count; i++)
{
arguments.Add("-map").Add(i);
}
// Output format and encoding preset
arguments.Add("-f").Add(container.Name).Add("-preset").Add(preset);
// Avoid transcoding inputs that have the same container as the output
{
var lastAudioStreamIndex = 0;
var lastVideoStreamIndex = 0;
foreach (var streamInput in streamInputs)
{
// Note: a muxed stream input will map to two separate audio and video streams
if (streamInput.Info is IAudioStreamInfo audioStreamInfo)
{
if (audioStreamInfo.Container == container)
{
arguments.Add($"-c:a:{lastAudioStreamIndex}").Add("copy");
}
lastAudioStreamIndex++;
}
if (streamInput.Info is IVideoStreamInfo videoStreamInfo)
{
if (videoStreamInfo.Container == container)
{
arguments.Add($"-c:v:{lastVideoStreamIndex}").Add("copy");
}
lastVideoStreamIndex++;
}
}
}
// MP4: explicitly specify the codec for subtitles, otherwise they won't get embedded
if (container == Container.Mp4 && subtitleInputs.Any())
{
arguments.Add("-c:s").Add("mov_text");
}
// MP3: explicitly specify the bitrate for audio streams, otherwise their metadata
// might contain invalid total duration.
// https://superuser.com/a/893044
if (container == Container.Mp3)
{
var lastAudioStreamIndex = 0;
foreach (var streamInput in streamInputs)
{
if (streamInput.Info is IAudioStreamInfo audioStreamInfo)
{
arguments
.Add($"-b:a:{lastAudioStreamIndex++}")
.Add(Math.Round(audioStreamInfo.Bitrate.KiloBitsPerSecond) + "K");
}
}
}
// Metadata for stream inputs
{
var lastAudioStreamIndex = 0;
var lastVideoStreamIndex = 0;
foreach (var streamInput in streamInputs)
{
// Note: a muxed stream input will map to two separate audio and video streams
if (streamInput.Info is IAudioStreamInfo audioStreamInfo)
{
arguments
.Add($"-metadata:s:a:{lastAudioStreamIndex++}")
.Add($"title={audioStreamInfo.Bitrate}");
}
if (streamInput.Info is IVideoStreamInfo videoStreamInfo)
{
arguments
.Add($"-metadata:s:v:{lastVideoStreamIndex++}")
.Add(
$"title={videoStreamInfo.VideoQuality.Label} | {videoStreamInfo.Bitrate}"
);
}
}
}
// Metadata for subtitles
foreach (var (i, subtitleInput) in subtitleInputs.Index())
{
// Language codes can be stored in any format, but most players expect
// three-letter codes, so we'll try to convert to that first.
var languageCode =
subtitleInput.Info.Language.TryGetThreeLetterCode()
?? subtitleInput.Info.Language.Code;
arguments
.Add($"-metadata:s:s:{i}")
.Add($"language={languageCode}")
.Add($"-metadata:s:s:{i}")
.Add($"title={subtitleInput.Info.Language.Name}");
}
// Enable progress reporting
arguments
// Info log level is required to extract total stream duration
.Add("-loglevel")
.Add("info")
.Add("-stats");
// Misc settings
arguments
.Add("-hide_banner")
.Add("-threads")
.Add(Environment.ProcessorCount)
.Add("-nostdin")
.Add("-y");
// Output
arguments.Add(filePath);
await ffmpeg.ExecuteAsync(arguments.Build(), progress, cancellationToken);
}
private async ValueTask PopulateStreamInputsAsync(
string baseFilePath,
IReadOnlyList<IStreamInfo> streamInfos,
ICollection<StreamInput> streamInputs,
IProgress<double>? progress = null,
CancellationToken cancellationToken = default
)
{
var progressMuxer = progress?.Pipe(p => new ProgressMuxer(p));
var progresses = streamInfos
.Select(s => progressMuxer?.CreateInput(s.Size.MegaBytes))
.ToArray();
var lastIndex = 0;
foreach (var (streamInfo, streamProgress) in streamInfos.Zip(progresses))
{
var streamInput = new StreamInput(
streamInfo,
$"{baseFilePath}.stream-{lastIndex++}.tmp"
);
streamInputs.Add(streamInput);
await videoClient.Streams.DownloadAsync(
streamInfo,
streamInput.FilePath,
streamProgress,
cancellationToken
);
}
progress?.Report(1);
}
private async ValueTask PopulateSubtitleInputsAsync(
string baseFilePath,
IReadOnlyList<ClosedCaptionTrackInfo> closedCaptionTrackInfos,
ICollection<SubtitleInput> subtitleInputs,
IProgress<double>? progress = null,
CancellationToken cancellationToken = default
)
{
var progressMuxer = progress?.Pipe(p => new ProgressMuxer(p));
var progresses = closedCaptionTrackInfos
.Select(_ => progressMuxer?.CreateInput())
.ToArray();
var lastIndex = 0;
foreach (var (trackInfo, trackProgress) in closedCaptionTrackInfos.Zip(progresses))
{
var subtitleInput = new SubtitleInput(
trackInfo,
$"{baseFilePath}.subtitles-{lastIndex++}.tmp"
);
subtitleInputs.Add(subtitleInput);
await videoClient.ClosedCaptions.DownloadAsync(
trackInfo,
subtitleInput.FilePath,
trackProgress,
cancellationToken
);
}
progress?.Report(1);
}
public async ValueTask ProcessAsync(
string filePath,
Container container,
IReadOnlyList<IStreamInfo> streamInfos,
IReadOnlyList<ClosedCaptionTrackInfo> closedCaptionTrackInfos,
IProgress<double>? progress = null,
CancellationToken cancellationToken = default
)
{
if (!streamInfos.Any())
throw new InvalidOperationException("No streams provided.");
// Configure progress aggregation
var progressMuxer = progress?.Pipe(p => new ProgressMuxer(p));
var streamDownloadProgress = progressMuxer?.CreateInput();
var subtitleDownloadProgress = progressMuxer?.CreateInput(0.01);
var conversionProgress = progressMuxer?.CreateInput(
0.05
+
// Increase weight for each stream that needs to be transcoded
5 * streamInfos.Count(s => s.Container != container)
);
// Populate inputs
var streamInputs = new List<StreamInput>(streamInfos.Count);
var subtitleInputs = new List<SubtitleInput>(closedCaptionTrackInfos.Count);
try
{
await PopulateStreamInputsAsync(
filePath,
streamInfos,
streamInputs,
streamDownloadProgress,
cancellationToken
);
await PopulateSubtitleInputsAsync(
filePath,
closedCaptionTrackInfos,
subtitleInputs,
subtitleDownloadProgress,
cancellationToken
);
await ProcessAsync(
filePath,
container,
streamInputs,
subtitleInputs,
conversionProgress,
cancellationToken
);
}
finally
{
foreach (var inputStream in streamInputs)
inputStream.Dispose();
foreach (var inputClosedCaptionTrack in subtitleInputs)
inputClosedCaptionTrack.Dispose();
}
}
}
internal partial class Converter
{
private class StreamInput(IStreamInfo info, string filePath) : IDisposable
{
public IStreamInfo Info { get; } = info;
public string FilePath { get; } = filePath;
public void Dispose()
{
try
{
File.Delete(FilePath);
}
catch
{
// Ignore
}
}
}
private class SubtitleInput(ClosedCaptionTrackInfo info, string filePath) : IDisposable
{
public ClosedCaptionTrackInfo Info { get; } = info;
public string FilePath { get; } = filePath;
public void Dispose()
{
try
{
File.Delete(FilePath);
}
catch
{
// Ignore
}
}
}
}