-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
VideosDownloader.cs
374 lines (343 loc) · 16.5 KB
/
VideosDownloader.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
using ExtraMetadataLoader.Helpers;
using ExtraMetadataLoader.Models;
using Newtonsoft.Json;
using Playnite.SDK;
using Playnite.SDK.Models;
using PlayniteUtilitiesCommon;
using PluginsCommon;
using FlowHttp;
using SteamCommon;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ExtraMetadataLoader.Services
{
class VideosDownloader
{
private readonly IPlayniteAPI playniteApi;
private static readonly ILogger logger = LogManager.GetLogger();
private readonly ExtraMetadataLoaderSettings settings;
private readonly ExtraMetadataHelper extraMetadataHelper;
private const string steamMicrotrailerUrlTemplate = @"https://steamcdn-a.akamaihd.net/steam/apps/{0}/microtrailer.mp4";
private readonly string tempDownloadPath = Path.Combine(Path.GetTempPath(), "VideoTemp.mp4");
public VideosDownloader(IPlayniteAPI playniteApi, ExtraMetadataLoaderSettings settings, ExtraMetadataHelper extraMetadataHelper)
{
this.playniteApi = playniteApi;
this.settings = settings;
this.extraMetadataHelper = extraMetadataHelper;
}
public bool DownloadSteamVideo(Game game, bool overwrite, bool isBackgroundDownload, CancellationToken cancelToken, bool downloadVideo = false, bool downloadVideoMicro = false)
{
logger.Debug($"DownloadSteamVideo starting for game {game.Name}");
var videoPath = extraMetadataHelper.GetGameVideoPath(game, true);
var videoMicroPath = extraMetadataHelper.GetGameVideoMicroPath(game, true);
if (FileSystem.FileExists(videoPath) && !overwrite)
{
downloadVideo = false;
}
if (FileSystem.FileExists(videoMicroPath) && !overwrite)
{
downloadVideoMicro = false;
}
if (!downloadVideo && !downloadVideoMicro)
{
return true;
}
var steamId = string.Empty;
if (Steam.IsGameSteamGame(game))
{
logger.Debug("Steam id found for Steam game");
steamId = game.GameId;
}
else if (!settings.SteamDlOnlyProcessPcGames || PlayniteUtilities.IsGamePcGame(game))
{
steamId = extraMetadataHelper.GetSteamIdFromSearch(game, isBackgroundDownload);
}
else
{
logger.Debug("Game is not a PC game and execution is only allowed for PC games");
return false;
}
if (steamId.IsNullOrEmpty())
{
logger.Debug("Steam id not found");
return false;
}
var steamAppDetails = SteamWeb.GetSteamAppDetails(steamId);
if (steamAppDetails is null || steamAppDetails.data.Movies is null || steamAppDetails.data.Movies.Count == 0)
{
return false;
}
if (downloadVideo)
{
var videoUrl = steamAppDetails.data.Movies[0].Mp4.Q480;
if (settings.VideoSteamDownloadHdQuality)
{
videoUrl = steamAppDetails.data.Movies[0].Mp4.Max;
}
var downloadFileResult = HttpRequestFactory.GetHttpFileRequest()
.WithUrl(videoUrl.ToString()).WithDownloadTo(tempDownloadPath)
.DownloadFile(cancelToken);
if (downloadFileResult.IsSuccess)
{
GetVideoInformation(tempDownloadPath);
ProcessVideo(tempDownloadPath, videoPath, false, true);
}
}
if (downloadVideoMicro)
{
var videoUrl = string.Format(steamMicrotrailerUrlTemplate, steamAppDetails.data.Movies[0].Id);
var downloadFileResult = HttpRequestFactory
.GetHttpFileRequest()
.WithUrl(videoUrl.ToString())
.WithDownloadTo(tempDownloadPath)
.DownloadFile(cancelToken);
if (downloadFileResult.IsSuccess)
{
ProcessVideo(tempDownloadPath, videoMicroPath, false, true);
}
}
return true;
}
private bool ProcessVideo(string videoPath, string destinationPath, bool copyOnly, bool deleteSource, string args = null)
{
var ffmpegPath = extraMetadataHelper.ExpandVariables(settings.FfmpegPath);
var videoInfo = GetVideoInformation(videoPath);
var neededAction = GetIsConversionNeeded(videoInfo);
var success = true;
try
{
if (neededAction == VideoActionNeeded.Conversion || Path.GetExtension(videoPath) != ".mp4")
{
if (args.IsNullOrEmpty())
{
args = $"-y -i \"{videoPath}\" -c:v libx264 -c:a mp3 -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -pix_fmt yuv420p \"{destinationPath}\"";
}
var result = ProcessStarter.StartProcessWait(ffmpegPath, args, Path.GetDirectoryName(ffmpegPath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to process video in ffmpeg: {result}, {stdErr}");
success = false;
}
}
else if (neededAction == VideoActionNeeded.Nothing)
{
if (copyOnly)
{
success = FileSystem.CopyFile(videoPath, destinationPath);
}
else
{
success = FileSystem.MoveFile(videoPath, destinationPath);
}
}
else if (neededAction == VideoActionNeeded.Invalid)
{
success = false;
}
}
catch (Exception e)
{
logger.Error(e, $"Error while processing video \"{videoPath}\" with process action \"{neededAction}\"");
success = false;
}
if (deleteSource && FileSystem.FileExists(videoPath))
{
FileSystem.DeleteFile(videoPath);
}
return success;
}
private VideoActionNeeded GetIsConversionNeeded(FfprobeVideoInfoOutput videoInformation)
{
if (videoInformation == null)
{
logger.Debug($"Video information not obtained");
return VideoActionNeeded.Invalid;
}
else if (videoInformation.Streams == null || videoInformation.Streams.Count() < 1)
{
logger.Debug($"Video streams null or 0");
return VideoActionNeeded.Invalid;
}
var stream = videoInformation.Streams[0];
if (stream.Width == 0 || stream.Height == 0)
{
logger.Debug($"Video width and height not obtained");
return VideoActionNeeded.Invalid;
}
else if (string.IsNullOrEmpty(stream.PixFmt))
{
logger.Debug($"Video PixFmt is null");
return VideoActionNeeded.Invalid;
}
else if (stream.PixFmt != "yuv420p")
{
logger.Debug($"Video conversion needed, PixFmt is {stream.PixFmt}");
return VideoActionNeeded.Conversion;
}
return VideoActionNeeded.Nothing;
}
private FfprobeVideoInfoOutput GetVideoInformation(string videoPath)
{
var ffprobePath = extraMetadataHelper.ExpandVariables(settings.FfprobePath);
logger.Debug($"Obtaining video information: {videoPath}");
var args = $"-v error -select_streams v:0 -show_entries stream=width,height,codec_name_name,pix_fmt,duration -of json \"{videoPath}\"";
var result = ProcessStarter.StartProcessWait(ffprobePath, args, Path.GetDirectoryName(ffprobePath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to get video information: {videoPath}, {result}, {stdErr}");
playniteApi.Notifications.Add(new NotificationMessage(
Guid.NewGuid().ToString(),
string.Format(ResourceProvider.GetString("LOCExtra_Metadata_Loader_NotificationErrorFfprobeGetInfoFail"), videoPath, result, stdErr),
NotificationType.Error)
);
return null;
}
return JsonConvert.DeserializeObject<FfprobeVideoInfoOutput>(stdOut);
}
public bool ConvertVideoToMicro(Game game, bool overwrite)
{
var ffmpegPath = extraMetadataHelper.ExpandVariables(game, settings.FfmpegPath);
var videoPath = extraMetadataHelper.GetGameVideoPath(game, true);
var videoMicroPath = extraMetadataHelper.GetGameVideoMicroPath(game, true);
if (!FileSystem.FileExists(videoPath) || (FileSystem.FileExists(videoMicroPath) && !overwrite))
{
return false;
}
var videoInfo = GetVideoInformation(videoPath);
if (videoInfo == null)
{
return false;
}
// It's needed to use invariant culture when parsing because ffprobe output durantion
// uses a dot as decimal separator and some regions use other symbols for this.
var videoDuration = double.Parse(videoInfo.Streams[0].Duration, CultureInfo.InvariantCulture);
var success = true;
if (videoDuration < 14)
{
var actionNeeded = GetIsConversionNeeded(videoInfo);
if (actionNeeded == VideoActionNeeded.Invalid)
{
success = false;
}
else if (actionNeeded == VideoActionNeeded.Conversion)
{
// Scale parameter needs to be used because otherwise ffmpeg
// will fail if a dimension is not divisible by 2.
var args = $"-y -i \"{videoPath}\" -c:v libx264 -c:a mp3 -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -pix_fmt yuv420p -an \"{videoMicroPath}\"";
var result = ProcessStarter.StartProcessWait(ffmpegPath, args, Path.GetDirectoryName(ffmpegPath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to process video in ffmpeg: {videoPath}, {result}, {stdErr}");
playniteApi.Notifications.Add(new NotificationMessage(
Guid.NewGuid().ToString(),
string.Format(ResourceProvider.GetString("LOCExtra_Metadata_Loader_NotificationErrorFfmpegProcessingFail"), videoPath, result, stdErr),
NotificationType.Error)
);
success = false;
}
}
else
{
// Scale parameter needs to be used because otherwise ffmpeg
// will fail if a dimension is not divisible by 2.
var args = $"-y -i \"{videoPath}\" -c:v copy -an \"{videoMicroPath}\"";
var result = ProcessStarter.StartProcessWait(ffmpegPath, args, Path.GetDirectoryName(ffmpegPath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to process video in ffmpeg: {videoPath}, {result}, {stdErr}");
playniteApi.Notifications.Add(new NotificationMessage(
Guid.NewGuid().ToString(),
string.Format(ResourceProvider.GetString("LOCExtra_Metadata_Loader_NotificationErrorFfmpegProcessingFail"), videoPath, result, stdErr),
NotificationType.Error)
);
success = false;
}
}
}
else
{
var rangeStringList = new List<string>();
var clipDuration = 1;
int[] startPercentageVideo = {
15,
25,
35,
45,
55,
65
};
foreach (var percentage in startPercentageVideo)
{
double clipStart = (percentage * videoDuration) / 100;
double clipEnd = clipStart + clipDuration;
rangeStringList.Add(string.Format("between(t,{0:N2},{1:N2})", clipStart.ToString(CultureInfo.InvariantCulture), clipEnd.ToString(CultureInfo.InvariantCulture)));
}
var selectString = $"\"select = '{string.Join("+", rangeStringList)}', setpts = N / FRAME_RATE / TB, scale = trunc(iw / 2) * 2:trunc(ih / 2) * 2\"";
var args = $"-y -i \"{videoPath}\" -vf {selectString} -c:v libx264 -pix_fmt yuv420p -an \"{videoMicroPath}\"";
var result = ProcessStarter.StartProcessWait(ffmpegPath, args, Path.GetDirectoryName(ffmpegPath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to process video in ffmpeg: {videoPath}, {result}, {stdErr}");
playniteApi.Notifications.Add(new NotificationMessage(
Guid.NewGuid().ToString(),
string.Format(ResourceProvider.GetString("LOCExtra_Metadata_Loader_NotificationErrorFfmpegProcessingFail"), videoPath, result, stdErr),
NotificationType.Error)
);
success = false;
}
}
return success;
}
public bool SelectedDialogFileToVideo(Game game)
{
logger.Debug($"SelectedDialogFileToVideo starting for game {game.Name}");
var videoPath = extraMetadataHelper.GetGameVideoPath(game, true);
var selectedVideoPath = playniteApi.Dialogs.SelectFile("Video file|*.mp4;*.avi;*.mkv;*.webm;*.flv;*.wmv;*.mov;*.m4v");
if (!selectedVideoPath.IsNullOrEmpty())
{
return ProcessVideo(selectedVideoPath, videoPath, true, false);
}
else
{
return false;
}
}
public bool DownloadYoutubeVideoById(Game game, string videoId, bool overwrite)
{
var youtubeDlPath = extraMetadataHelper.ExpandVariables(game, settings.YoutubeDlPath);
var ffmpegPath = extraMetadataHelper.ExpandVariables(game, settings.FfmpegPath);
var youtubeCookiesPath = extraMetadataHelper.ExpandVariables(game, settings.YoutubeCookiesPath);
var videoPath = extraMetadataHelper.GetGameVideoPath(game, true);
if (FileSystem.FileExists(videoPath) && !overwrite)
{
return false;
}
var args = string.Format("-v --force-overwrites -o \"{0}\" -f \"mp4\" \"{1}\"", tempDownloadPath, $"https://www.youtube.com/watch?v={videoId}");
if (!youtubeCookiesPath.IsNullOrEmpty() && FileSystem.FileExists(youtubeCookiesPath))
{
args = string.Format("-v --force-overwrites -o \"{0}\" --cookies \"{1}\" -f \"mp4\" \"{2}\"", tempDownloadPath, youtubeCookiesPath, $"https://www.youtube.com/watch?v={videoId}");
}
var result = ProcessStarter.StartProcessWait(youtubeDlPath, args, Path.GetDirectoryName(ffmpegPath), true, out var stdOut, out var stdErr);
if (result != 0)
{
logger.Error($"Failed to download video in youtube-dlp: {videoId}, {result}, {stdErr}");
playniteApi.Notifications.Add(new NotificationMessage(
Guid.NewGuid().ToString(),
string.Format(ResourceProvider.GetString("LOCExtra_Metadata_Loader_NotificationErrorYtdlpDownloadFail"), videoId, result, stdErr),
NotificationType.Error)
);
return false;
}
else
{
return ProcessVideo(tempDownloadPath, videoPath, false, false);
}
}
}
}