| | 1 | | #nullable disable |
| | 2 | | #pragma warning disable CS1591 |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Generic; |
| | 6 | | using System.Diagnostics; |
| | 7 | | using System.Globalization; |
| | 8 | | using System.IO; |
| | 9 | | using System.Linq; |
| | 10 | | using System.Text.Json; |
| | 11 | | using System.Text.RegularExpressions; |
| | 12 | | using System.Threading; |
| | 13 | | using System.Threading.Tasks; |
| | 14 | | using AsyncKeyedLock; |
| | 15 | | using Jellyfin.Data.Enums; |
| | 16 | | using Jellyfin.Extensions; |
| | 17 | | using Jellyfin.Extensions.Json; |
| | 18 | | using Jellyfin.Extensions.Json.Converters; |
| | 19 | | using MediaBrowser.Common; |
| | 20 | | using MediaBrowser.Common.Configuration; |
| | 21 | | using MediaBrowser.Common.Extensions; |
| | 22 | | using MediaBrowser.Controller.Configuration; |
| | 23 | | using MediaBrowser.Controller.Extensions; |
| | 24 | | using MediaBrowser.Controller.MediaEncoding; |
| | 25 | | using MediaBrowser.MediaEncoding.Probing; |
| | 26 | | using MediaBrowser.Model.Configuration; |
| | 27 | | using MediaBrowser.Model.Dlna; |
| | 28 | | using MediaBrowser.Model.Drawing; |
| | 29 | | using MediaBrowser.Model.Dto; |
| | 30 | | using MediaBrowser.Model.Entities; |
| | 31 | | using MediaBrowser.Model.Globalization; |
| | 32 | | using MediaBrowser.Model.IO; |
| | 33 | | using MediaBrowser.Model.MediaInfo; |
| | 34 | | using Microsoft.Extensions.Configuration; |
| | 35 | | using Microsoft.Extensions.Logging; |
| | 36 | |
|
| | 37 | | namespace MediaBrowser.MediaEncoding.Encoder |
| | 38 | | { |
| | 39 | | /// <summary> |
| | 40 | | /// Class MediaEncoder. |
| | 41 | | /// </summary> |
| | 42 | | public partial class MediaEncoder : IMediaEncoder, IDisposable |
| | 43 | | { |
| | 44 | | /// <summary> |
| | 45 | | /// The default SDR image extraction timeout in milliseconds. |
| | 46 | | /// </summary> |
| | 47 | | internal const int DefaultSdrImageExtractionTimeout = 10000; |
| | 48 | |
|
| | 49 | | /// <summary> |
| | 50 | | /// The default HDR image extraction timeout in milliseconds. |
| | 51 | | /// </summary> |
| | 52 | | internal const int DefaultHdrImageExtractionTimeout = 20000; |
| | 53 | |
|
| | 54 | | private readonly ILogger<MediaEncoder> _logger; |
| | 55 | | private readonly IServerConfigurationManager _configurationManager; |
| | 56 | | private readonly IFileSystem _fileSystem; |
| | 57 | | private readonly ILocalizationManager _localization; |
| | 58 | | private readonly IBlurayExaminer _blurayExaminer; |
| | 59 | | private readonly IConfiguration _config; |
| | 60 | | private readonly IServerConfigurationManager _serverConfig; |
| | 61 | | private readonly string _startupOptionFFmpegPath; |
| | 62 | |
|
| | 63 | | private readonly AsyncNonKeyedLocker _thumbnailResourcePool; |
| | 64 | |
|
| 23 | 65 | | private readonly object _runningProcessesLock = new object(); |
| 23 | 66 | | private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>(); |
| | 67 | |
|
| | 68 | | // MediaEncoder is registered as a Singleton |
| | 69 | | private readonly JsonSerializerOptions _jsonSerializerOptions; |
| | 70 | |
|
| 23 | 71 | | private List<string> _encoders = new List<string>(); |
| 23 | 72 | | private List<string> _decoders = new List<string>(); |
| 23 | 73 | | private List<string> _hwaccels = new List<string>(); |
| 23 | 74 | | private List<string> _filters = new List<string>(); |
| 23 | 75 | | private IDictionary<int, bool> _filtersWithOption = new Dictionary<int, bool>(); |
| | 76 | |
|
| | 77 | | private bool _isPkeyPauseSupported = false; |
| | 78 | | private bool _isLowPriorityHwDecodeSupported = false; |
| | 79 | |
|
| | 80 | | private bool _isVaapiDeviceAmd = false; |
| | 81 | | private bool _isVaapiDeviceInteliHD = false; |
| | 82 | | private bool _isVaapiDeviceInteli965 = false; |
| | 83 | | private bool _isVaapiDeviceSupportVulkanDrmModifier = false; |
| | 84 | | private bool _isVaapiDeviceSupportVulkanDrmInterop = false; |
| | 85 | |
|
| 0 | 86 | | private static string[] _vulkanImageDrmFmtModifierExts = |
| 0 | 87 | | { |
| 0 | 88 | | "VK_EXT_image_drm_format_modifier", |
| 0 | 89 | | }; |
| | 90 | |
|
| 0 | 91 | | private static string[] _vulkanExternalMemoryDmaBufExts = |
| 0 | 92 | | { |
| 0 | 93 | | "VK_KHR_external_memory_fd", |
| 0 | 94 | | "VK_EXT_external_memory_dma_buf", |
| 0 | 95 | | "VK_KHR_external_semaphore_fd", |
| 0 | 96 | | "VK_EXT_external_memory_host" |
| 0 | 97 | | }; |
| | 98 | |
|
| | 99 | | private Version _ffmpegVersion = null; |
| 23 | 100 | | private string _ffmpegPath = string.Empty; |
| | 101 | | private string _ffprobePath; |
| | 102 | | private int _threads; |
| | 103 | |
|
| | 104 | | public MediaEncoder( |
| | 105 | | ILogger<MediaEncoder> logger, |
| | 106 | | IServerConfigurationManager configurationManager, |
| | 107 | | IFileSystem fileSystem, |
| | 108 | | IBlurayExaminer blurayExaminer, |
| | 109 | | ILocalizationManager localization, |
| | 110 | | IConfiguration config, |
| | 111 | | IServerConfigurationManager serverConfig) |
| | 112 | | { |
| 23 | 113 | | _logger = logger; |
| 23 | 114 | | _configurationManager = configurationManager; |
| 23 | 115 | | _fileSystem = fileSystem; |
| 23 | 116 | | _blurayExaminer = blurayExaminer; |
| 23 | 117 | | _localization = localization; |
| 23 | 118 | | _config = config; |
| 23 | 119 | | _serverConfig = serverConfig; |
| 23 | 120 | | _startupOptionFFmpegPath = config.GetValue<string>(Controller.Extensions.ConfigurationExtensions.FfmpegPathK |
| | 121 | |
|
| 23 | 122 | | _jsonSerializerOptions = new JsonSerializerOptions(JsonDefaults.Options); |
| 23 | 123 | | _jsonSerializerOptions.Converters.Add(new JsonBoolStringConverter()); |
| | 124 | |
|
| 23 | 125 | | var semaphoreCount = 2 * Environment.ProcessorCount; |
| 23 | 126 | | _thumbnailResourcePool = new(semaphoreCount); |
| 23 | 127 | | } |
| | 128 | |
|
| | 129 | | /// <inheritdoc /> |
| 0 | 130 | | public string EncoderPath => _ffmpegPath; |
| | 131 | |
|
| | 132 | | /// <inheritdoc /> |
| 0 | 133 | | public string ProbePath => _ffprobePath; |
| | 134 | |
|
| | 135 | | /// <inheritdoc /> |
| 0 | 136 | | public Version EncoderVersion => _ffmpegVersion; |
| | 137 | |
|
| | 138 | | /// <inheritdoc /> |
| 0 | 139 | | public bool IsPkeyPauseSupported => _isPkeyPauseSupported; |
| | 140 | |
|
| | 141 | | /// <inheritdoc /> |
| 0 | 142 | | public bool IsVaapiDeviceAmd => _isVaapiDeviceAmd; |
| | 143 | |
|
| | 144 | | /// <inheritdoc /> |
| 0 | 145 | | public bool IsVaapiDeviceInteliHD => _isVaapiDeviceInteliHD; |
| | 146 | |
|
| | 147 | | /// <inheritdoc /> |
| 0 | 148 | | public bool IsVaapiDeviceInteli965 => _isVaapiDeviceInteli965; |
| | 149 | |
|
| | 150 | | /// <inheritdoc /> |
| 0 | 151 | | public bool IsVaapiDeviceSupportVulkanDrmModifier => _isVaapiDeviceSupportVulkanDrmModifier; |
| | 152 | |
|
| | 153 | | /// <inheritdoc /> |
| 0 | 154 | | public bool IsVaapiDeviceSupportVulkanDrmInterop => _isVaapiDeviceSupportVulkanDrmInterop; |
| | 155 | |
|
| | 156 | | [GeneratedRegex(@"[^\/\\]+?(\.[^\/\\\n.]+)?$")] |
| | 157 | | private static partial Regex FfprobePathRegex(); |
| | 158 | |
|
| | 159 | | /// <summary> |
| | 160 | | /// Run at startup to validate ffmpeg. |
| | 161 | | /// Sets global variables FFmpegPath. |
| | 162 | | /// Precedence is: CLI/Env var > Config > $PATH. |
| | 163 | | /// </summary> |
| | 164 | | /// <returns>bool indicates whether a valid ffmpeg is found.</returns> |
| | 165 | | public bool SetFFmpegPath() |
| | 166 | | { |
| 22 | 167 | | var skipValidation = _config.GetFFmpegSkipValidation(); |
| 22 | 168 | | if (skipValidation) |
| | 169 | | { |
| 22 | 170 | | _logger.LogWarning("FFmpeg: Skipping FFmpeg Validation due to FFmpeg:novalidation set to true"); |
| 22 | 171 | | return true; |
| | 172 | | } |
| | 173 | |
|
| | 174 | | // 1) Check if the --ffmpeg CLI switch has been given |
| 0 | 175 | | var ffmpegPath = _startupOptionFFmpegPath; |
| 0 | 176 | | string ffmpegPathSetMethodText = "command line or environment variable"; |
| 0 | 177 | | if (string.IsNullOrEmpty(ffmpegPath)) |
| | 178 | | { |
| | 179 | | // 2) Custom path stored in config/encoding xml file under tag <EncoderAppPath> should be used as a fall |
| 0 | 180 | | ffmpegPath = _configurationManager.GetEncodingOptions().EncoderAppPath; |
| 0 | 181 | | ffmpegPathSetMethodText = "encoding.xml config file"; |
| 0 | 182 | | if (string.IsNullOrEmpty(ffmpegPath)) |
| | 183 | | { |
| | 184 | | // 3) Check "ffmpeg" |
| 0 | 185 | | ffmpegPath = "ffmpeg"; |
| 0 | 186 | | ffmpegPathSetMethodText = "system $PATH"; |
| | 187 | | } |
| | 188 | | } |
| | 189 | |
|
| 0 | 190 | | if (!ValidatePath(ffmpegPath)) |
| | 191 | | { |
| 0 | 192 | | _ffmpegPath = null; |
| 0 | 193 | | _logger.LogError("FFmpeg: Path set by {FfmpegPathSetMethodText} is invalid", ffmpegPathSetMethodText); |
| 0 | 194 | | return false; |
| | 195 | | } |
| | 196 | |
|
| | 197 | | // Write the FFmpeg path to the config/encoding.xml file as <EncoderAppPathDisplay> so it appears in UI |
| 0 | 198 | | var options = _configurationManager.GetEncodingOptions(); |
| 0 | 199 | | options.EncoderAppPathDisplay = _ffmpegPath ?? string.Empty; |
| 0 | 200 | | _configurationManager.SaveConfiguration("encoding", options); |
| | 201 | |
|
| | 202 | | // Only if mpeg path is set, try and set path to probe |
| 0 | 203 | | if (_ffmpegPath is not null) |
| | 204 | | { |
| | 205 | | // Determine a probe path from the mpeg path |
| 0 | 206 | | _ffprobePath = FfprobePathRegex().Replace(_ffmpegPath, "ffprobe$1"); |
| | 207 | |
|
| | 208 | | // Interrogate to understand what coders are supported |
| 0 | 209 | | var validator = new EncoderValidator(_logger, _ffmpegPath); |
| | 210 | |
|
| 0 | 211 | | SetAvailableDecoders(validator.GetDecoders()); |
| 0 | 212 | | SetAvailableEncoders(validator.GetEncoders()); |
| 0 | 213 | | SetAvailableFilters(validator.GetFilters()); |
| 0 | 214 | | SetAvailableFiltersWithOption(validator.GetFiltersWithOption()); |
| 0 | 215 | | SetAvailableHwaccels(validator.GetHwaccels()); |
| 0 | 216 | | SetMediaEncoderVersion(validator); |
| | 217 | |
|
| 0 | 218 | | _threads = EncodingHelper.GetNumberOfThreads(null, options, null); |
| | 219 | |
|
| 0 | 220 | | _isPkeyPauseSupported = validator.CheckSupportedRuntimeKey("p pause transcoding", _ffmpegVersion); |
| 0 | 221 | | _isLowPriorityHwDecodeSupported = validator.CheckSupportedHwaccelFlag("low_priority"); |
| | 222 | |
|
| | 223 | | // Check the Vaapi device vendor |
| 0 | 224 | | if (OperatingSystem.IsLinux() |
| 0 | 225 | | && SupportsHwaccel("vaapi") |
| 0 | 226 | | && !string.IsNullOrEmpty(options.VaapiDevice) |
| 0 | 227 | | && options.HardwareAccelerationType == HardwareAccelerationType.vaapi) |
| | 228 | | { |
| 0 | 229 | | _isVaapiDeviceAmd = validator.CheckVaapiDeviceByDriverName("Mesa Gallium driver", options.VaapiDevic |
| 0 | 230 | | _isVaapiDeviceInteliHD = validator.CheckVaapiDeviceByDriverName("Intel iHD driver", options.VaapiDev |
| 0 | 231 | | _isVaapiDeviceInteli965 = validator.CheckVaapiDeviceByDriverName("Intel i965 driver", options.VaapiD |
| 0 | 232 | | _isVaapiDeviceSupportVulkanDrmModifier = validator.CheckVulkanDrmDeviceByExtensionName(options.Vaapi |
| 0 | 233 | | _isVaapiDeviceSupportVulkanDrmInterop = validator.CheckVulkanDrmDeviceByExtensionName(options.VaapiD |
| | 234 | |
|
| 0 | 235 | | if (_isVaapiDeviceAmd) |
| | 236 | | { |
| 0 | 237 | | _logger.LogInformation("VAAPI device {RenderNodePath} is AMD GPU", options.VaapiDevice); |
| | 238 | | } |
| 0 | 239 | | else if (_isVaapiDeviceInteliHD) |
| | 240 | | { |
| 0 | 241 | | _logger.LogInformation("VAAPI device {RenderNodePath} is Intel GPU (iHD)", options.VaapiDevice); |
| | 242 | | } |
| 0 | 243 | | else if (_isVaapiDeviceInteli965) |
| | 244 | | { |
| 0 | 245 | | _logger.LogInformation("VAAPI device {RenderNodePath} is Intel GPU (i965)", options.VaapiDevice) |
| | 246 | | } |
| | 247 | |
|
| 0 | 248 | | if (_isVaapiDeviceSupportVulkanDrmModifier) |
| | 249 | | { |
| 0 | 250 | | _logger.LogInformation("VAAPI device {RenderNodePath} supports Vulkan DRM modifier", options.Vaa |
| | 251 | | } |
| | 252 | |
|
| 0 | 253 | | if (_isVaapiDeviceSupportVulkanDrmInterop) |
| | 254 | | { |
| 0 | 255 | | _logger.LogInformation("VAAPI device {RenderNodePath} supports Vulkan DRM interop", options.Vaap |
| | 256 | | } |
| | 257 | | } |
| | 258 | | } |
| | 259 | |
|
| 0 | 260 | | _logger.LogInformation("FFmpeg: {FfmpegPath}", _ffmpegPath ?? string.Empty); |
| 0 | 261 | | return !string.IsNullOrWhiteSpace(ffmpegPath); |
| | 262 | | } |
| | 263 | |
|
| | 264 | | /// <summary> |
| | 265 | | /// Validates the supplied FQPN to ensure it is a ffmpeg utility. |
| | 266 | | /// If checks pass, global variable FFmpegPath is updated. |
| | 267 | | /// </summary> |
| | 268 | | /// <param name="path">FQPN to test.</param> |
| | 269 | | /// <returns><c>true</c> if the version validation succeeded; otherwise, <c>false</c>.</returns> |
| | 270 | | private bool ValidatePath(string path) |
| | 271 | | { |
| 0 | 272 | | if (string.IsNullOrEmpty(path)) |
| | 273 | | { |
| 0 | 274 | | return false; |
| | 275 | | } |
| | 276 | |
|
| 0 | 277 | | bool rc = new EncoderValidator(_logger, path).ValidateVersion(); |
| 0 | 278 | | if (!rc) |
| | 279 | | { |
| 0 | 280 | | _logger.LogError("FFmpeg: Failed version check: {Path}", path); |
| 0 | 281 | | return false; |
| | 282 | | } |
| | 283 | |
|
| 0 | 284 | | _ffmpegPath = path; |
| 0 | 285 | | return true; |
| | 286 | | } |
| | 287 | |
|
| | 288 | | private string GetEncoderPathFromDirectory(string path, string filename, bool recursive = false) |
| | 289 | | { |
| | 290 | | try |
| | 291 | | { |
| 0 | 292 | | var files = _fileSystem.GetFilePaths(path, recursive); |
| | 293 | |
|
| 0 | 294 | | return files.FirstOrDefault(i => Path.GetFileNameWithoutExtension(i.AsSpan()).Equals(filename, StringCom |
| 0 | 295 | | && !Path.GetExtension(i.AsSpan()).Equals(".c", StringComparison.Ordi |
| | 296 | | } |
| 0 | 297 | | catch (Exception) |
| | 298 | | { |
| | 299 | | // Trap all exceptions, like DirNotExists, and return null |
| 0 | 300 | | return null; |
| | 301 | | } |
| 0 | 302 | | } |
| | 303 | |
|
| | 304 | | public void SetAvailableEncoders(IEnumerable<string> list) |
| | 305 | | { |
| 0 | 306 | | _encoders = list.ToList(); |
| 0 | 307 | | } |
| | 308 | |
|
| | 309 | | public void SetAvailableDecoders(IEnumerable<string> list) |
| | 310 | | { |
| 0 | 311 | | _decoders = list.ToList(); |
| 0 | 312 | | } |
| | 313 | |
|
| | 314 | | public void SetAvailableHwaccels(IEnumerable<string> list) |
| | 315 | | { |
| 0 | 316 | | _hwaccels = list.ToList(); |
| 0 | 317 | | } |
| | 318 | |
|
| | 319 | | public void SetAvailableFilters(IEnumerable<string> list) |
| | 320 | | { |
| 0 | 321 | | _filters = list.ToList(); |
| 0 | 322 | | } |
| | 323 | |
|
| | 324 | | public void SetAvailableFiltersWithOption(IDictionary<int, bool> dict) |
| | 325 | | { |
| 0 | 326 | | _filtersWithOption = dict; |
| 0 | 327 | | } |
| | 328 | |
|
| | 329 | | public void SetMediaEncoderVersion(EncoderValidator validator) |
| | 330 | | { |
| 0 | 331 | | _ffmpegVersion = validator.GetFFmpegVersion(); |
| 0 | 332 | | } |
| | 333 | |
|
| | 334 | | /// <inheritdoc /> |
| | 335 | | public bool SupportsEncoder(string encoder) |
| | 336 | | { |
| 0 | 337 | | return _encoders.Contains(encoder, StringComparer.OrdinalIgnoreCase); |
| | 338 | | } |
| | 339 | |
|
| | 340 | | /// <inheritdoc /> |
| | 341 | | public bool SupportsDecoder(string decoder) |
| | 342 | | { |
| 0 | 343 | | return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase); |
| | 344 | | } |
| | 345 | |
|
| | 346 | | /// <inheritdoc /> |
| | 347 | | public bool SupportsHwaccel(string hwaccel) |
| | 348 | | { |
| 0 | 349 | | return _hwaccels.Contains(hwaccel, StringComparer.OrdinalIgnoreCase); |
| | 350 | | } |
| | 351 | |
|
| | 352 | | /// <inheritdoc /> |
| | 353 | | public bool SupportsFilter(string filter) |
| | 354 | | { |
| 0 | 355 | | return _filters.Contains(filter, StringComparer.OrdinalIgnoreCase); |
| | 356 | | } |
| | 357 | |
|
| | 358 | | /// <inheritdoc /> |
| | 359 | | public bool SupportsFilterWithOption(FilterOptionType option) |
| | 360 | | { |
| 0 | 361 | | if (_filtersWithOption.TryGetValue((int)option, out var val)) |
| | 362 | | { |
| 0 | 363 | | return val; |
| | 364 | | } |
| | 365 | |
|
| 0 | 366 | | return false; |
| | 367 | | } |
| | 368 | |
|
| | 369 | | public bool CanEncodeToAudioCodec(string codec) |
| | 370 | | { |
| 0 | 371 | | if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase)) |
| | 372 | | { |
| 0 | 373 | | codec = "libopus"; |
| | 374 | | } |
| 0 | 375 | | else if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase)) |
| | 376 | | { |
| 0 | 377 | | codec = "libmp3lame"; |
| | 378 | | } |
| | 379 | |
|
| 0 | 380 | | return SupportsEncoder(codec); |
| | 381 | | } |
| | 382 | |
|
| | 383 | | public bool CanEncodeToSubtitleCodec(string codec) |
| | 384 | | { |
| | 385 | | // TODO |
| 0 | 386 | | return true; |
| | 387 | | } |
| | 388 | |
|
| | 389 | | /// <inheritdoc /> |
| | 390 | | public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken) |
| | 391 | | { |
| 0 | 392 | | var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters; |
| 0 | 393 | | var extraArgs = GetExtraArguments(request); |
| | 394 | |
|
| 0 | 395 | | return GetMediaInfoInternal( |
| 0 | 396 | | GetInputArgument(request.MediaSource.Path, request.MediaSource), |
| 0 | 397 | | request.MediaSource.Path, |
| 0 | 398 | | request.MediaSource.Protocol, |
| 0 | 399 | | extractChapters, |
| 0 | 400 | | extraArgs, |
| 0 | 401 | | request.MediaType == DlnaProfileType.Audio, |
| 0 | 402 | | request.MediaSource.VideoType, |
| 0 | 403 | | cancellationToken); |
| | 404 | | } |
| | 405 | |
|
| | 406 | | internal string GetExtraArguments(MediaInfoRequest request) |
| | 407 | | { |
| 1 | 408 | | var ffmpegAnalyzeDuration = _config.GetFFmpegAnalyzeDuration() ?? string.Empty; |
| 1 | 409 | | var ffmpegProbeSize = _config.GetFFmpegProbeSize() ?? string.Empty; |
| 1 | 410 | | var analyzeDuration = string.Empty; |
| 1 | 411 | | var extraArgs = string.Empty; |
| | 412 | |
|
| 1 | 413 | | if (request.MediaSource.AnalyzeDurationMs > 0) |
| | 414 | | { |
| 0 | 415 | | analyzeDuration = "-analyzeduration " + (request.MediaSource.AnalyzeDurationMs * 1000); |
| | 416 | | } |
| 1 | 417 | | else if (!string.IsNullOrEmpty(ffmpegAnalyzeDuration)) |
| | 418 | | { |
| 0 | 419 | | analyzeDuration = "-analyzeduration " + ffmpegAnalyzeDuration; |
| | 420 | | } |
| | 421 | |
|
| 1 | 422 | | if (!string.IsNullOrEmpty(analyzeDuration)) |
| | 423 | | { |
| 0 | 424 | | extraArgs = analyzeDuration; |
| | 425 | | } |
| | 426 | |
|
| 1 | 427 | | if (!string.IsNullOrEmpty(ffmpegProbeSize)) |
| | 428 | | { |
| 0 | 429 | | extraArgs += " -probesize " + ffmpegProbeSize; |
| | 430 | | } |
| | 431 | |
|
| 1 | 432 | | if (request.MediaSource.RequiredHttpHeaders.TryGetValue("User-Agent", out var userAgent)) |
| | 433 | | { |
| 1 | 434 | | extraArgs += $" -user_agent \"{userAgent}\""; |
| | 435 | | } |
| | 436 | |
|
| 1 | 437 | | if (request.MediaSource.Protocol == MediaProtocol.Rtsp) |
| | 438 | | { |
| 0 | 439 | | extraArgs += " -rtsp_transport tcp+udp -rtsp_flags prefer_tcp"; |
| | 440 | | } |
| | 441 | |
|
| 1 | 442 | | return extraArgs; |
| | 443 | | } |
| | 444 | |
|
| | 445 | | /// <inheritdoc /> |
| | 446 | | public string GetInputArgument(IReadOnlyList<string> inputFiles, MediaSourceInfo mediaSource) |
| | 447 | | { |
| 0 | 448 | | return EncodingUtils.GetInputArgument("file", inputFiles, mediaSource.Protocol); |
| | 449 | | } |
| | 450 | |
|
| | 451 | | /// <inheritdoc /> |
| | 452 | | public string GetInputArgument(string inputFile, MediaSourceInfo mediaSource) |
| | 453 | | { |
| 0 | 454 | | var prefix = "file"; |
| 0 | 455 | | if (mediaSource.IsoType == IsoType.BluRay) |
| | 456 | | { |
| 0 | 457 | | prefix = "bluray"; |
| | 458 | | } |
| | 459 | |
|
| 0 | 460 | | return EncodingUtils.GetInputArgument(prefix, new[] { inputFile }, mediaSource.Protocol); |
| | 461 | | } |
| | 462 | |
|
| | 463 | | /// <inheritdoc /> |
| | 464 | | public string GetExternalSubtitleInputArgument(string inputFile) |
| | 465 | | { |
| | 466 | | const string Prefix = "file"; |
| | 467 | |
|
| 0 | 468 | | return EncodingUtils.GetInputArgument(Prefix, new[] { inputFile }, MediaProtocol.File); |
| | 469 | | } |
| | 470 | |
|
| | 471 | | /// <summary> |
| | 472 | | /// Gets the media info internal. |
| | 473 | | /// </summary> |
| | 474 | | /// <returns>Task{MediaInfoResult}.</returns> |
| | 475 | | private async Task<MediaInfo> GetMediaInfoInternal( |
| | 476 | | string inputPath, |
| | 477 | | string primaryPath, |
| | 478 | | MediaProtocol protocol, |
| | 479 | | bool extractChapters, |
| | 480 | | string probeSizeArgument, |
| | 481 | | bool isAudio, |
| | 482 | | VideoType? videoType, |
| | 483 | | CancellationToken cancellationToken) |
| | 484 | | { |
| | 485 | | var args = extractChapters |
| | 486 | | ? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format" |
| | 487 | | : "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format"; |
| | 488 | | args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, _threads).Trim(); |
| | 489 | |
|
| | 490 | | var process = new Process |
| | 491 | | { |
| | 492 | | StartInfo = new ProcessStartInfo |
| | 493 | | { |
| | 494 | | CreateNoWindow = true, |
| | 495 | | UseShellExecute = false, |
| | 496 | |
|
| | 497 | | // Must consume both or ffmpeg may hang due to deadlocks. |
| | 498 | | RedirectStandardOutput = true, |
| | 499 | |
|
| | 500 | | FileName = _ffprobePath, |
| | 501 | | Arguments = args, |
| | 502 | |
|
| | 503 | | WindowStyle = ProcessWindowStyle.Hidden, |
| | 504 | | ErrorDialog = false, |
| | 505 | | }, |
| | 506 | | EnableRaisingEvents = true |
| | 507 | | }; |
| | 508 | |
|
| | 509 | | _logger.LogInformation("Starting {ProcessFileName} with args {ProcessArgs}", _ffprobePath, args); |
| | 510 | |
|
| | 511 | | var memoryStream = new MemoryStream(); |
| | 512 | | await using (memoryStream.ConfigureAwait(false)) |
| | 513 | | using (var processWrapper = new ProcessWrapper(process, this)) |
| | 514 | | { |
| | 515 | | StartProcess(processWrapper); |
| | 516 | | using var reader = process.StandardOutput; |
| | 517 | | await reader.BaseStream.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false); |
| | 518 | | memoryStream.Seek(0, SeekOrigin.Begin); |
| | 519 | | InternalMediaInfoResult result; |
| | 520 | | try |
| | 521 | | { |
| | 522 | | result = await JsonSerializer.DeserializeAsync<InternalMediaInfoResult>( |
| | 523 | | memoryStream, |
| | 524 | | _jsonSerializerOptions, |
| | 525 | | cancellationToken).ConfigureAwait(false); |
| | 526 | | } |
| | 527 | | catch |
| | 528 | | { |
| | 529 | | StopProcess(processWrapper, 100); |
| | 530 | |
|
| | 531 | | throw; |
| | 532 | | } |
| | 533 | |
|
| | 534 | | if (result is null || (result.Streams is null && result.Format is null)) |
| | 535 | | { |
| | 536 | | throw new FfmpegException("ffprobe failed - streams and format are both null."); |
| | 537 | | } |
| | 538 | |
|
| | 539 | | if (result.Streams is not null) |
| | 540 | | { |
| | 541 | | // Normalize aspect ratio if invalid |
| | 542 | | foreach (var stream in result.Streams) |
| | 543 | | { |
| | 544 | | if (string.Equals(stream.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase)) |
| | 545 | | { |
| | 546 | | stream.DisplayAspectRatio = string.Empty; |
| | 547 | | } |
| | 548 | |
|
| | 549 | | if (string.Equals(stream.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase)) |
| | 550 | | { |
| | 551 | | stream.SampleAspectRatio = string.Empty; |
| | 552 | | } |
| | 553 | | } |
| | 554 | | } |
| | 555 | |
|
| | 556 | | return new ProbeResultNormalizer(_logger, _localization).GetMediaInfo(result, videoType, isAudio, primar |
| | 557 | | } |
| | 558 | | } |
| | 559 | |
|
| | 560 | | /// <inheritdoc /> |
| | 561 | | public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken) |
| | 562 | | { |
| 0 | 563 | | var mediaSource = new MediaSourceInfo |
| 0 | 564 | | { |
| 0 | 565 | | Protocol = MediaProtocol.File |
| 0 | 566 | | }; |
| | 567 | |
|
| 0 | 568 | | return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, ImageFormat.Jpg, canc |
| | 569 | | } |
| | 570 | |
|
| | 571 | | /// <inheritdoc /> |
| | 572 | | public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStre |
| | 573 | | { |
| 0 | 574 | | return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, Image |
| | 575 | | } |
| | 576 | |
|
| | 577 | | /// <inheritdoc /> |
| | 578 | | public Task<string> ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStre |
| | 579 | | { |
| 0 | 580 | | return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, tar |
| | 581 | | } |
| | 582 | |
|
| | 583 | | private async Task<string> ExtractImage( |
| | 584 | | string inputFile, |
| | 585 | | string container, |
| | 586 | | MediaStream videoStream, |
| | 587 | | int? imageStreamIndex, |
| | 588 | | MediaSourceInfo mediaSource, |
| | 589 | | bool isAudio, |
| | 590 | | Video3DFormat? threedFormat, |
| | 591 | | TimeSpan? offset, |
| | 592 | | ImageFormat? targetFormat, |
| | 593 | | CancellationToken cancellationToken) |
| | 594 | | { |
| | 595 | | var inputArgument = GetInputPathArgument(inputFile, mediaSource); |
| | 596 | |
|
| | 597 | | if (!isAudio) |
| | 598 | | { |
| | 599 | | try |
| | 600 | | { |
| | 601 | | return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFor |
| | 602 | | } |
| | 603 | | catch (ArgumentException) |
| | 604 | | { |
| | 605 | | throw; |
| | 606 | | } |
| | 607 | | catch (Exception ex) |
| | 608 | | { |
| | 609 | | _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments} |
| | 610 | | } |
| | 611 | | } |
| | 612 | |
|
| | 613 | | return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, off |
| | 614 | | } |
| | 615 | |
|
| | 616 | | private string GetImageResolutionParameter() |
| | 617 | | { |
| 0 | 618 | | var imageResolutionParameter = _serverConfig.Configuration.ChapterImageResolution switch |
| 0 | 619 | | { |
| 0 | 620 | | ImageResolution.P144 => "256x144", |
| 0 | 621 | | ImageResolution.P240 => "426x240", |
| 0 | 622 | | ImageResolution.P360 => "640x360", |
| 0 | 623 | | ImageResolution.P480 => "854x480", |
| 0 | 624 | | ImageResolution.P720 => "1280x720", |
| 0 | 625 | | ImageResolution.P1080 => "1920x1080", |
| 0 | 626 | | ImageResolution.P1440 => "2560x1440", |
| 0 | 627 | | ImageResolution.P2160 => "3840x2160", |
| 0 | 628 | | _ => string.Empty |
| 0 | 629 | | }; |
| | 630 | |
|
| 0 | 631 | | if (!string.IsNullOrEmpty(imageResolutionParameter)) |
| | 632 | | { |
| 0 | 633 | | imageResolutionParameter = " -s " + imageResolutionParameter; |
| | 634 | | } |
| | 635 | |
|
| 0 | 636 | | return imageResolutionParameter; |
| | 637 | | } |
| | 638 | |
|
| | 639 | | private async Task<string> ExtractImageInternal( |
| | 640 | | string inputPath, |
| | 641 | | string container, |
| | 642 | | MediaStream videoStream, |
| | 643 | | int? imageStreamIndex, |
| | 644 | | Video3DFormat? threedFormat, |
| | 645 | | TimeSpan? offset, |
| | 646 | | bool useIFrame, |
| | 647 | | ImageFormat? targetFormat, |
| | 648 | | bool isAudio, |
| | 649 | | CancellationToken cancellationToken) |
| | 650 | | { |
| | 651 | | ArgumentException.ThrowIfNullOrEmpty(inputPath); |
| | 652 | |
|
| | 653 | | var outputExtension = targetFormat?.GetExtension() ?? ".jpg"; |
| | 654 | |
|
| | 655 | | var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ou |
| | 656 | | Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath)); |
| | 657 | |
|
| | 658 | | // deint -> scale -> thumbnail -> tonemap. |
| | 659 | | // put the SW tonemap right after the thumbnail to do it only once to reduce cpu usage. |
| | 660 | | var filters = new List<string>(); |
| | 661 | |
|
| | 662 | | // deinterlace using bwdif algorithm for video stream. |
| | 663 | | if (videoStream is not null && videoStream.IsInterlaced) |
| | 664 | | { |
| | 665 | | filters.Add("bwdif=0:-1:0"); |
| | 666 | | } |
| | 667 | |
|
| | 668 | | // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the cor |
| | 669 | | // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex |
| | 670 | | var scaler = threedFormat switch |
| | 671 | | { |
| | 672 | | // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may |
| | 673 | | Video3DFormat.HalfSideBySide => @"crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\,ih*dar):min |
| | 674 | | // fsbs crop width in half,set the display aspect,crop out any black bars we may have made |
| | 675 | | Video3DFormat.FullSideBySide => @"crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw |
| | 676 | | // htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may |
| | 677 | | Video3DFormat.HalfTopAndBottom => @"crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\,ih*dar): |
| | 678 | | // ftab crop height in half, set the display aspect,crop out any black bars we may have made |
| | 679 | | Video3DFormat.FullTopAndBottom => @"crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\,ih*dar):min(ih\,iw/dar):( |
| | 680 | | _ => "scale=round(iw*sar/2)*2:round(ih/2)*2" |
| | 681 | | }; |
| | 682 | |
|
| | 683 | | filters.Add(scaler); |
| | 684 | |
|
| | 685 | | // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick |
| | 686 | | // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will l |
| | 687 | | var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); |
| | 688 | | if (enableThumbnail) |
| | 689 | | { |
| | 690 | | var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase); |
| | 691 | | filters.Add("thumbnail=n=" + (useLargerBatchSize ? "50" : "24")); |
| | 692 | | } |
| | 693 | |
|
| | 694 | | // Use SW tonemap on HDR video stream only when the zscale or tonemapx filter is available. |
| | 695 | | // Only enable Dolby Vision tonemap when tonemapx is available |
| | 696 | | var enableHdrExtraction = false; |
| | 697 | |
|
| | 698 | | if (videoStream?.VideoRange == VideoRange.HDR) |
| | 699 | | { |
| | 700 | | if (SupportsFilter("tonemapx")) |
| | 701 | | { |
| | 702 | | enableHdrExtraction = true; |
| | 703 | | filters.Add("tonemapx=tonemap=bt2390:desat=0:peak=100:t=bt709:m=bt709:p=bt709:format=yuv420p"); |
| | 704 | | } |
| | 705 | | else if (SupportsFilter("zscale") && videoStream.VideoRangeType != VideoRangeType.DOVI) |
| | 706 | | { |
| | 707 | | enableHdrExtraction = true; |
| | 708 | | filters.Add("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:p |
| | 709 | | } |
| | 710 | | } |
| | 711 | |
|
| | 712 | | var vf = string.Join(',', filters); |
| | 713 | | var mapArg = imageStreamIndex.HasValue ? (" -map 0:" + imageStreamIndex.Value.ToString(CultureInfo.Invariant |
| | 714 | | var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 -vf {2}{5 |
| | 715 | |
|
| | 716 | | if (offset.HasValue) |
| | 717 | | { |
| | 718 | | args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args; |
| | 719 | | } |
| | 720 | |
|
| | 721 | | if (!string.IsNullOrWhiteSpace(container)) |
| | 722 | | { |
| | 723 | | var inputFormat = EncodingHelper.GetInputFormat(container); |
| | 724 | | if (!string.IsNullOrWhiteSpace(inputFormat)) |
| | 725 | | { |
| | 726 | | args = "-f " + inputFormat + " " + args; |
| | 727 | | } |
| | 728 | | } |
| | 729 | |
|
| | 730 | | var process = new Process |
| | 731 | | { |
| | 732 | | StartInfo = new ProcessStartInfo |
| | 733 | | { |
| | 734 | | CreateNoWindow = true, |
| | 735 | | UseShellExecute = false, |
| | 736 | | FileName = _ffmpegPath, |
| | 737 | | Arguments = args, |
| | 738 | | WindowStyle = ProcessWindowStyle.Hidden, |
| | 739 | | ErrorDialog = false, |
| | 740 | | }, |
| | 741 | | EnableRaisingEvents = true |
| | 742 | | }; |
| | 743 | |
|
| | 744 | | _logger.LogDebug("{ProcessFileName} {ProcessArguments}", process.StartInfo.FileName, process.StartInfo.Argum |
| | 745 | |
|
| | 746 | | using (var processWrapper = new ProcessWrapper(process, this)) |
| | 747 | | { |
| | 748 | | using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false)) |
| | 749 | | { |
| | 750 | | StartProcess(processWrapper); |
| | 751 | |
|
| | 752 | | var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs; |
| | 753 | | if (timeoutMs <= 0) |
| | 754 | | { |
| | 755 | | timeoutMs = enableHdrExtraction ? DefaultHdrImageExtractionTimeout : DefaultSdrImageExtractionTi |
| | 756 | | } |
| | 757 | |
|
| | 758 | | try |
| | 759 | | { |
| | 760 | | await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false); |
| | 761 | | } |
| | 762 | | catch (OperationCanceledException ex) |
| | 763 | | { |
| | 764 | | process.Kill(true); |
| | 765 | | throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction t |
| | 766 | | } |
| | 767 | | } |
| | 768 | |
|
| | 769 | | var file = _fileSystem.GetFileInfo(tempExtractPath); |
| | 770 | |
|
| | 771 | | if (processWrapper.ExitCode > 0 || !file.Exists || file.Length == 0) |
| | 772 | | { |
| | 773 | | throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction faile |
| | 774 | | } |
| | 775 | |
|
| | 776 | | return tempExtractPath; |
| | 777 | | } |
| | 778 | | } |
| | 779 | |
|
| | 780 | | /// <inheritdoc /> |
| | 781 | | public Task<string> ExtractVideoImagesOnIntervalAccelerated( |
| | 782 | | string inputFile, |
| | 783 | | string container, |
| | 784 | | MediaSourceInfo mediaSource, |
| | 785 | | MediaStream imageStream, |
| | 786 | | int maxWidth, |
| | 787 | | TimeSpan interval, |
| | 788 | | bool allowHwAccel, |
| | 789 | | bool enableHwEncoding, |
| | 790 | | int? threads, |
| | 791 | | int? qualityScale, |
| | 792 | | ProcessPriorityClass? priority, |
| | 793 | | bool enableKeyFrameOnlyExtraction, |
| | 794 | | EncodingHelper encodingHelper, |
| | 795 | | CancellationToken cancellationToken) |
| | 796 | | { |
| 0 | 797 | | var options = allowHwAccel ? _configurationManager.GetEncodingOptions() : new EncodingOptions(); |
| 0 | 798 | | threads ??= _threads; |
| | 799 | |
|
| 0 | 800 | | if (allowHwAccel && enableKeyFrameOnlyExtraction) |
| | 801 | | { |
| 0 | 802 | | var hardwareAccelerationType = options.HardwareAccelerationType; |
| 0 | 803 | | var supportsKeyFrameOnly = (hardwareAccelerationType == HardwareAccelerationType.nvenc && options.Enable |
| 0 | 804 | | || (hardwareAccelerationType == HardwareAccelerationType.amf && OperatingSyst |
| 0 | 805 | | || (hardwareAccelerationType == HardwareAccelerationType.qsv && options.Prefe |
| 0 | 806 | | || hardwareAccelerationType == HardwareAccelerationType.vaapi |
| 0 | 807 | | || hardwareAccelerationType == HardwareAccelerationType.videotoolbox; |
| 0 | 808 | | if (!supportsKeyFrameOnly) |
| | 809 | | { |
| | 810 | | // Disable hardware acceleration when the hardware decoder does not support keyframe only mode. |
| 0 | 811 | | allowHwAccel = false; |
| 0 | 812 | | options = new EncodingOptions(); |
| | 813 | | } |
| | 814 | | } |
| | 815 | |
|
| | 816 | | // A new EncodingOptions instance must be used as to not disable HW acceleration for all of Jellyfin. |
| | 817 | | // Additionally, we must set a few fields without defaults to prevent null pointer exceptions. |
| 0 | 818 | | if (!allowHwAccel) |
| | 819 | | { |
| 0 | 820 | | options.EnableHardwareEncoding = false; |
| 0 | 821 | | options.HardwareAccelerationType = HardwareAccelerationType.none; |
| 0 | 822 | | options.EnableTonemapping = false; |
| | 823 | | } |
| | 824 | |
|
| 0 | 825 | | if (imageStream.Width is not null && imageStream.Height is not null && !string.IsNullOrEmpty(imageStream.Asp |
| | 826 | | { |
| | 827 | | // For hardware trickplay encoders, we need to re-calculate the size because they used fixed scale dimen |
| 0 | 828 | | var darParts = imageStream.AspectRatio.Split(':'); |
| 0 | 829 | | var (wa, ha) = (double.Parse(darParts[0], CultureInfo.InvariantCulture), double.Parse(darParts[1], Cultu |
| | 830 | | // When dimension / DAR does not equal to 1:1, then the frames are most likely stored stretched. |
| | 831 | | // Note: this might be incorrect for 3D videos as the SAR stored might be per eye instead of per video, |
| 0 | 832 | | var shouldResetHeight = Math.Abs((imageStream.Width.Value * ha) - (imageStream.Height.Value * wa)) > .05 |
| 0 | 833 | | if (shouldResetHeight) |
| | 834 | | { |
| | 835 | | // SAR = DAR * Height / Width |
| | 836 | | // RealHeight = Height / SAR = Height / (DAR * Height / Width) = Width / DAR |
| 0 | 837 | | imageStream.Height = Convert.ToInt32(imageStream.Width.Value * ha / wa); |
| | 838 | | } |
| | 839 | | } |
| | 840 | |
|
| 0 | 841 | | var baseRequest = new BaseEncodingJobOptions { MaxWidth = maxWidth, MaxFramerate = (float)(1.0 / interval.To |
| 0 | 842 | | var jobState = new EncodingJobInfo(TranscodingJobType.Progressive) |
| 0 | 843 | | { |
| 0 | 844 | | IsVideoRequest = true, // must be true for InputVideoHwaccelArgs to return non-empty value |
| 0 | 845 | | MediaSource = mediaSource, |
| 0 | 846 | | VideoStream = imageStream, |
| 0 | 847 | | BaseRequest = baseRequest, // GetVideoProcessingFilterParam errors if null |
| 0 | 848 | | MediaPath = inputFile, |
| 0 | 849 | | OutputVideoCodec = "mjpeg" |
| 0 | 850 | | }; |
| 0 | 851 | | var vidEncoder = enableHwEncoding ? encodingHelper.GetVideoEncoder(jobState, options) : jobState.OutputVideo |
| | 852 | |
|
| | 853 | | // Get input and filter arguments |
| 0 | 854 | | var inputArg = encodingHelper.GetInputArgument(jobState, options, container).Trim(); |
| 0 | 855 | | if (string.IsNullOrWhiteSpace(inputArg)) |
| | 856 | | { |
| 0 | 857 | | throw new InvalidOperationException("EncodingHelper returned empty input arguments."); |
| | 858 | | } |
| | 859 | |
|
| 0 | 860 | | if (!allowHwAccel) |
| | 861 | | { |
| 0 | 862 | | inputArg = "-threads " + threads + " " + inputArg; // HW accel args set a different input thread count, |
| | 863 | | } |
| | 864 | |
|
| 0 | 865 | | if (options.HardwareAccelerationType == HardwareAccelerationType.videotoolbox && _isLowPriorityHwDecodeSuppo |
| | 866 | | { |
| | 867 | | // VideoToolbox supports low priority decoding, which is useful for trickplay |
| 0 | 868 | | inputArg = "-hwaccel_flags +low_priority " + inputArg; |
| | 869 | | } |
| | 870 | |
|
| 0 | 871 | | if (enableKeyFrameOnlyExtraction) |
| | 872 | | { |
| 0 | 873 | | inputArg = "-skip_frame nokey " + inputArg; |
| | 874 | | } |
| | 875 | |
|
| 0 | 876 | | var filterParam = encodingHelper.GetVideoProcessingFilterParam(jobState, options, vidEncoder).Trim(); |
| 0 | 877 | | if (string.IsNullOrWhiteSpace(filterParam)) |
| | 878 | | { |
| 0 | 879 | | throw new InvalidOperationException("EncodingHelper returned empty or invalid filter parameters."); |
| | 880 | | } |
| | 881 | |
|
| 0 | 882 | | return ExtractVideoImagesOnIntervalInternal(inputArg, filterParam, vidEncoder, threads, qualityScale, priori |
| | 883 | | } |
| | 884 | |
|
| | 885 | | private async Task<string> ExtractVideoImagesOnIntervalInternal( |
| | 886 | | string inputArg, |
| | 887 | | string filterParam, |
| | 888 | | string vidEncoder, |
| | 889 | | int? outputThreads, |
| | 890 | | int? qualityScale, |
| | 891 | | ProcessPriorityClass? priority, |
| | 892 | | CancellationToken cancellationToken) |
| | 893 | | { |
| | 894 | | if (string.IsNullOrWhiteSpace(inputArg)) |
| | 895 | | { |
| | 896 | | throw new InvalidOperationException("Empty or invalid input argument."); |
| | 897 | | } |
| | 898 | |
|
| | 899 | | // ffmpeg qscale is a value from 1-31, with 1 being best quality and 31 being worst |
| | 900 | | // jpeg quality is a value from 0-100, with 0 being worst quality and 100 being best |
| | 901 | | var encoderQuality = Math.Clamp(qualityScale ?? 4, 1, 31); |
| | 902 | | var encoderQualityOption = "-qscale:v "; |
| | 903 | |
|
| | 904 | | if (vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase) |
| | 905 | | || vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase)) |
| | 906 | | { |
| | 907 | | // vaapi and qsv's mjpeg encoder use jpeg quality as input, instead of ffmpeg defined qscale |
| | 908 | | encoderQuality = 100 - ((encoderQuality - 1) * (100 / 30)); |
| | 909 | | encoderQualityOption = "-global_quality:v "; |
| | 910 | | } |
| | 911 | |
|
| | 912 | | if (vidEncoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase)) |
| | 913 | | { |
| | 914 | | // videotoolbox's mjpeg encoder uses jpeg quality scaled to QP2LAMBDA (118) instead of ffmpeg defined qs |
| | 915 | | encoderQuality = 118 - ((encoderQuality - 1) * (118 / 30)); |
| | 916 | | } |
| | 917 | |
|
| | 918 | | if (vidEncoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase)) |
| | 919 | | { |
| | 920 | | // rkmpp's mjpeg encoder uses jpeg quality as input (max is 99, not 100), instead of ffmpeg defined qsca |
| | 921 | | encoderQuality = 99 - ((encoderQuality - 1) * (99 / 30)); |
| | 922 | | encoderQualityOption = "-qp_init:v "; |
| | 923 | | } |
| | 924 | |
|
| | 925 | | // Output arguments |
| | 926 | | var targetDirectory = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid().ToSt |
| | 927 | | Directory.CreateDirectory(targetDirectory); |
| | 928 | | var outputPath = Path.Combine(targetDirectory, "%08d.jpg"); |
| | 929 | |
|
| | 930 | | // Final command arguments |
| | 931 | | var args = string.Format( |
| | 932 | | CultureInfo.InvariantCulture, |
| | 933 | | "-loglevel error {0} -an -sn {1} -threads {2} -c:v {3} {4}{5}-f {6} \"{7}\"", |
| | 934 | | inputArg, |
| | 935 | | filterParam, |
| | 936 | | outputThreads.GetValueOrDefault(_threads), |
| | 937 | | vidEncoder, |
| | 938 | | encoderQualityOption + encoderQuality + " ", |
| | 939 | | vidEncoder.Contains("videotoolbox", StringComparison.InvariantCultureIgnoreCase) ? "-allow_sw 1 " : stri |
| | 940 | | "image2", |
| | 941 | | outputPath); |
| | 942 | |
|
| | 943 | | // Start ffmpeg process |
| | 944 | | var process = new Process |
| | 945 | | { |
| | 946 | | StartInfo = new ProcessStartInfo |
| | 947 | | { |
| | 948 | | CreateNoWindow = true, |
| | 949 | | UseShellExecute = false, |
| | 950 | | FileName = _ffmpegPath, |
| | 951 | | Arguments = args, |
| | 952 | | WindowStyle = ProcessWindowStyle.Hidden, |
| | 953 | | ErrorDialog = false, |
| | 954 | | }, |
| | 955 | | EnableRaisingEvents = true |
| | 956 | | }; |
| | 957 | |
|
| | 958 | | var processDescription = string.Format(CultureInfo.InvariantCulture, "{0} {1}", process.StartInfo.FileName, |
| | 959 | | _logger.LogInformation("Trickplay generation: {ProcessDescription}", processDescription); |
| | 960 | |
|
| | 961 | | using (var processWrapper = new ProcessWrapper(process, this)) |
| | 962 | | { |
| | 963 | | bool ranToCompletion = false; |
| | 964 | |
|
| | 965 | | using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false)) |
| | 966 | | { |
| | 967 | | StartProcess(processWrapper); |
| | 968 | |
|
| | 969 | | // Set process priority |
| | 970 | | if (priority.HasValue) |
| | 971 | | { |
| | 972 | | try |
| | 973 | | { |
| | 974 | | processWrapper.Process.PriorityClass = priority.Value; |
| | 975 | | } |
| | 976 | | catch (Exception ex) |
| | 977 | | { |
| | 978 | | _logger.LogDebug(ex, "Unable to set process priority to {Priority} for {Description}", prior |
| | 979 | | } |
| | 980 | | } |
| | 981 | |
|
| | 982 | | // Need to give ffmpeg enough time to make all the thumbnails, which could be a while, |
| | 983 | | // but we still need to detect if the process hangs. |
| | 984 | | // Making the assumption that as long as new jpegs are showing up, everything is good. |
| | 985 | |
|
| | 986 | | bool isResponsive = true; |
| | 987 | | int lastCount = 0; |
| | 988 | | var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs; |
| | 989 | | timeoutMs = timeoutMs <= 0 ? DefaultHdrImageExtractionTimeout : timeoutMs; |
| | 990 | |
|
| | 991 | | while (isResponsive && !cancellationToken.IsCancellationRequested) |
| | 992 | | { |
| | 993 | | try |
| | 994 | | { |
| | 995 | | await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false); |
| | 996 | |
|
| | 997 | | ranToCompletion = true; |
| | 998 | | break; |
| | 999 | | } |
| | 1000 | | catch (OperationCanceledException) |
| | 1001 | | { |
| | 1002 | | // We don't actually expect the process to be finished in one timeout span, just that one im |
| | 1003 | | } |
| | 1004 | |
|
| | 1005 | | var jpegCount = _fileSystem.GetFilePaths(targetDirectory).Count(); |
| | 1006 | |
|
| | 1007 | | isResponsive = jpegCount > lastCount; |
| | 1008 | | lastCount = jpegCount; |
| | 1009 | | } |
| | 1010 | |
|
| | 1011 | | if (!ranToCompletion) |
| | 1012 | | { |
| | 1013 | | if (!isResponsive) |
| | 1014 | | { |
| | 1015 | | _logger.LogInformation("Trickplay process unresponsive."); |
| | 1016 | | } |
| | 1017 | |
|
| | 1018 | | _logger.LogInformation("Stopping trickplay extraction."); |
| | 1019 | | StopProcess(processWrapper, 1000); |
| | 1020 | | } |
| | 1021 | | } |
| | 1022 | |
|
| | 1023 | | var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1; |
| | 1024 | |
|
| | 1025 | | if (exitCode == -1) |
| | 1026 | | { |
| | 1027 | | _logger.LogError("ffmpeg image extraction failed for {ProcessDescription}", processDescription); |
| | 1028 | |
|
| | 1029 | | throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction faile |
| | 1030 | | } |
| | 1031 | |
|
| | 1032 | | return targetDirectory; |
| | 1033 | | } |
| | 1034 | | } |
| | 1035 | |
|
| | 1036 | | public string GetTimeParameter(long ticks) |
| | 1037 | | { |
| 0 | 1038 | | var time = TimeSpan.FromTicks(ticks); |
| | 1039 | |
|
| 0 | 1040 | | return GetTimeParameter(time); |
| | 1041 | | } |
| | 1042 | |
|
| | 1043 | | public string GetTimeParameter(TimeSpan time) |
| | 1044 | | { |
| 0 | 1045 | | return time.ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture); |
| | 1046 | | } |
| | 1047 | |
|
| | 1048 | | private void StartProcess(ProcessWrapper process) |
| | 1049 | | { |
| 0 | 1050 | | process.Process.Start(); |
| | 1051 | |
|
| 0 | 1052 | | lock (_runningProcessesLock) |
| | 1053 | | { |
| 0 | 1054 | | _runningProcesses.Add(process); |
| 0 | 1055 | | } |
| 0 | 1056 | | } |
| | 1057 | |
|
| | 1058 | | private void StopProcess(ProcessWrapper process, int waitTimeMs) |
| | 1059 | | { |
| | 1060 | | try |
| | 1061 | | { |
| 0 | 1062 | | if (process.Process.WaitForExit(waitTimeMs)) |
| | 1063 | | { |
| 0 | 1064 | | return; |
| | 1065 | | } |
| | 1066 | |
|
| 0 | 1067 | | _logger.LogInformation("Killing ffmpeg process"); |
| | 1068 | |
|
| 0 | 1069 | | process.Process.Kill(); |
| 0 | 1070 | | } |
| 0 | 1071 | | catch (InvalidOperationException) |
| | 1072 | | { |
| | 1073 | | // The process has already exited or |
| | 1074 | | // there is no process associated with this Process object. |
| 0 | 1075 | | } |
| 0 | 1076 | | catch (Exception ex) |
| | 1077 | | { |
| 0 | 1078 | | _logger.LogError(ex, "Error killing process"); |
| 0 | 1079 | | } |
| 0 | 1080 | | } |
| | 1081 | |
|
| | 1082 | | private void StopProcesses() |
| | 1083 | | { |
| | 1084 | | List<ProcessWrapper> proceses; |
| 22 | 1085 | | lock (_runningProcessesLock) |
| | 1086 | | { |
| 22 | 1087 | | proceses = _runningProcesses.ToList(); |
| 22 | 1088 | | _runningProcesses.Clear(); |
| 22 | 1089 | | } |
| | 1090 | |
|
| 44 | 1091 | | foreach (var process in proceses) |
| | 1092 | | { |
| 0 | 1093 | | if (!process.HasExited) |
| | 1094 | | { |
| 0 | 1095 | | StopProcess(process, 500); |
| | 1096 | | } |
| | 1097 | | } |
| 22 | 1098 | | } |
| | 1099 | |
|
| | 1100 | | public string EscapeSubtitleFilterPath(string path) |
| | 1101 | | { |
| | 1102 | | // https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping |
| | 1103 | | // We need to double escape |
| | 1104 | |
|
| 0 | 1105 | | return path.Replace('\\', '/').Replace(":", "\\:", StringComparison.Ordinal).Replace("'", @"'\\\''", StringC |
| | 1106 | | } |
| | 1107 | |
|
| | 1108 | | /// <inheritdoc /> |
| | 1109 | | public void Dispose() |
| | 1110 | | { |
| 22 | 1111 | | Dispose(true); |
| 22 | 1112 | | GC.SuppressFinalize(this); |
| 22 | 1113 | | } |
| | 1114 | |
|
| | 1115 | | /// <summary> |
| | 1116 | | /// Releases unmanaged and - optionally - managed resources. |
| | 1117 | | /// </summary> |
| | 1118 | | /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o |
| | 1119 | | protected virtual void Dispose(bool dispose) |
| | 1120 | | { |
| 22 | 1121 | | if (dispose) |
| | 1122 | | { |
| 22 | 1123 | | StopProcesses(); |
| 22 | 1124 | | _thumbnailResourcePool.Dispose(); |
| | 1125 | | } |
| 22 | 1126 | | } |
| | 1127 | |
|
| | 1128 | | /// <inheritdoc /> |
| | 1129 | | public Task ConvertImage(string inputPath, string outputPath) |
| | 1130 | | { |
| 0 | 1131 | | throw new NotImplementedException(); |
| | 1132 | | } |
| | 1133 | |
|
| | 1134 | | /// <inheritdoc /> |
| | 1135 | | public IReadOnlyList<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber) |
| | 1136 | | { |
| | 1137 | | // Eliminate menus and intros by omitting VIDEO_TS.VOB and all subsequent title .vob files ending with _0.VO |
| 0 | 1138 | | var allVobs = _fileSystem.GetFiles(path, true) |
| 0 | 1139 | | .Where(file => string.Equals(file.Extension, ".VOB", StringComparison.OrdinalIgnoreCase)) |
| 0 | 1140 | | .Where(file => !string.Equals(file.Name, "VIDEO_TS.VOB", StringComparison.OrdinalIgnoreCase)) |
| 0 | 1141 | | .Where(file => !file.Name.EndsWith("_0.VOB", StringComparison.OrdinalIgnoreCase)) |
| 0 | 1142 | | .OrderBy(i => i.FullName) |
| 0 | 1143 | | .ToList(); |
| | 1144 | |
|
| 0 | 1145 | | if (titleNumber.HasValue) |
| | 1146 | | { |
| 0 | 1147 | | var prefix = string.Format(CultureInfo.InvariantCulture, "VTS_{0:D2}_", titleNumber.Value); |
| 0 | 1148 | | var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); |
| | 1149 | |
|
| 0 | 1150 | | if (vobs.Count > 0) |
| | 1151 | | { |
| 0 | 1152 | | return vobs.Select(i => i.FullName).ToList(); |
| | 1153 | | } |
| | 1154 | |
|
| 0 | 1155 | | _logger.LogWarning("Could not determine .vob files for title {Title} of {Path}.", titleNumber, path); |
| | 1156 | | } |
| | 1157 | |
|
| | 1158 | | // Check for multiple big titles (> 900 MB) |
| 0 | 1159 | | var titles = allVobs |
| 0 | 1160 | | .Where(vob => vob.Length >= 900 * 1024 * 1024) |
| 0 | 1161 | | .Select(vob => _fileSystem.GetFileNameWithoutExtension(vob).AsSpan().RightPart('_').ToString()) |
| 0 | 1162 | | .Distinct() |
| 0 | 1163 | | .ToList(); |
| | 1164 | |
|
| | 1165 | | // Fall back to first title if no big title is found |
| 0 | 1166 | | if (titles.Count == 0) |
| | 1167 | | { |
| 0 | 1168 | | titles.Add(_fileSystem.GetFileNameWithoutExtension(allVobs[0]).AsSpan().RightPart('_').ToString()); |
| | 1169 | | } |
| | 1170 | |
|
| | 1171 | | // Aggregate all .vob files of the titles |
| 0 | 1172 | | return allVobs |
| 0 | 1173 | | .Where(vob => titles.Contains(_fileSystem.GetFileNameWithoutExtension(vob).AsSpan().RightPart('_').ToStr |
| 0 | 1174 | | .Select(i => i.FullName) |
| 0 | 1175 | | .Order() |
| 0 | 1176 | | .ToList(); |
| | 1177 | | } |
| | 1178 | |
|
| | 1179 | | /// <inheritdoc /> |
| | 1180 | | public IReadOnlyList<string> GetPrimaryPlaylistM2tsFiles(string path) |
| 0 | 1181 | | => _blurayExaminer.GetDiscInfo(path).Files; |
| | 1182 | |
|
| | 1183 | | /// <inheritdoc /> |
| | 1184 | | public string GetInputPathArgument(EncodingJobInfo state) |
| 0 | 1185 | | => GetInputPathArgument(state.MediaPath, state.MediaSource); |
| | 1186 | |
|
| | 1187 | | /// <inheritdoc /> |
| | 1188 | | public string GetInputPathArgument(string path, MediaSourceInfo mediaSource) |
| | 1189 | | { |
| 0 | 1190 | | return mediaSource.VideoType switch |
| 0 | 1191 | | { |
| 0 | 1192 | | VideoType.Dvd => GetInputArgument(GetPrimaryPlaylistVobFiles(path, null), mediaSource), |
| 0 | 1193 | | VideoType.BluRay => GetInputArgument(GetPrimaryPlaylistM2tsFiles(path), mediaSource), |
| 0 | 1194 | | _ => GetInputArgument(path, mediaSource) |
| 0 | 1195 | | }; |
| | 1196 | | } |
| | 1197 | |
|
| | 1198 | | /// <inheritdoc /> |
| | 1199 | | public void GenerateConcatConfig(MediaSourceInfo source, string concatFilePath) |
| | 1200 | | { |
| | 1201 | | // Get all playable files |
| | 1202 | | IReadOnlyList<string> files; |
| 0 | 1203 | | var videoType = source.VideoType; |
| 0 | 1204 | | if (videoType == VideoType.Dvd) |
| | 1205 | | { |
| 0 | 1206 | | files = GetPrimaryPlaylistVobFiles(source.Path, null); |
| | 1207 | | } |
| 0 | 1208 | | else if (videoType == VideoType.BluRay) |
| | 1209 | | { |
| 0 | 1210 | | files = GetPrimaryPlaylistM2tsFiles(source.Path); |
| | 1211 | | } |
| | 1212 | | else |
| | 1213 | | { |
| 0 | 1214 | | return; |
| | 1215 | | } |
| | 1216 | |
|
| | 1217 | | // Generate concat configuration entries for each file and write to file |
| 0 | 1218 | | Directory.CreateDirectory(Path.GetDirectoryName(concatFilePath)); |
| 0 | 1219 | | using var sw = new FormattingStreamWriter(concatFilePath, CultureInfo.InvariantCulture); |
| 0 | 1220 | | foreach (var path in files) |
| | 1221 | | { |
| 0 | 1222 | | var mediaInfoResult = GetMediaInfo( |
| 0 | 1223 | | new MediaInfoRequest |
| 0 | 1224 | | { |
| 0 | 1225 | | MediaType = DlnaProfileType.Video, |
| 0 | 1226 | | MediaSource = new MediaSourceInfo |
| 0 | 1227 | | { |
| 0 | 1228 | | Path = path, |
| 0 | 1229 | | Protocol = MediaProtocol.File, |
| 0 | 1230 | | VideoType = videoType |
| 0 | 1231 | | } |
| 0 | 1232 | | }, |
| 0 | 1233 | | CancellationToken.None).GetAwaiter().GetResult(); |
| | 1234 | |
|
| 0 | 1235 | | var duration = TimeSpan.FromTicks(mediaInfoResult.RunTimeTicks.Value).TotalSeconds; |
| | 1236 | |
|
| | 1237 | | // Add file path stanza to concat configuration |
| 0 | 1238 | | sw.WriteLine("file '{0}'", path.Replace("'", @"'\''", StringComparison.Ordinal)); |
| | 1239 | |
|
| | 1240 | | // Add duration stanza to concat configuration |
| 0 | 1241 | | sw.WriteLine("duration {0}", duration); |
| | 1242 | | } |
| 0 | 1243 | | } |
| | 1244 | |
|
| | 1245 | | public bool CanExtractSubtitles(string codec) |
| | 1246 | | { |
| | 1247 | | // TODO is there ever a case when a subtitle can't be extracted?? |
| 0 | 1248 | | return true; |
| | 1249 | | } |
| | 1250 | |
|
| | 1251 | | private sealed class ProcessWrapper : IDisposable |
| | 1252 | | { |
| | 1253 | | private readonly MediaEncoder _mediaEncoder; |
| | 1254 | |
|
| | 1255 | | private bool _disposed = false; |
| | 1256 | |
|
| | 1257 | | public ProcessWrapper(Process process, MediaEncoder mediaEncoder) |
| | 1258 | | { |
| | 1259 | | Process = process; |
| 0 | 1260 | | _mediaEncoder = mediaEncoder; |
| 0 | 1261 | | Process.Exited += OnProcessExited; |
| 0 | 1262 | | } |
| | 1263 | |
|
| | 1264 | | public Process Process { get; } |
| | 1265 | |
|
| | 1266 | | public bool HasExited { get; private set; } |
| | 1267 | |
|
| | 1268 | | public int? ExitCode { get; private set; } |
| | 1269 | |
|
| | 1270 | | private void OnProcessExited(object sender, EventArgs e) |
| | 1271 | | { |
| 0 | 1272 | | var process = (Process)sender; |
| | 1273 | |
|
| 0 | 1274 | | HasExited = true; |
| | 1275 | |
|
| | 1276 | | try |
| | 1277 | | { |
| 0 | 1278 | | ExitCode = process.ExitCode; |
| 0 | 1279 | | } |
| 0 | 1280 | | catch |
| | 1281 | | { |
| 0 | 1282 | | } |
| | 1283 | |
|
| 0 | 1284 | | DisposeProcess(process); |
| 0 | 1285 | | } |
| | 1286 | |
|
| | 1287 | | private void DisposeProcess(Process process) |
| | 1288 | | { |
| 0 | 1289 | | lock (_mediaEncoder._runningProcessesLock) |
| | 1290 | | { |
| 0 | 1291 | | _mediaEncoder._runningProcesses.Remove(this); |
| 0 | 1292 | | } |
| | 1293 | |
|
| 0 | 1294 | | process.Dispose(); |
| 0 | 1295 | | } |
| | 1296 | |
|
| | 1297 | | public void Dispose() |
| | 1298 | | { |
| 0 | 1299 | | if (!_disposed) |
| | 1300 | | { |
| 0 | 1301 | | if (Process is not null) |
| | 1302 | | { |
| 0 | 1303 | | Process.Exited -= OnProcessExited; |
| 0 | 1304 | | DisposeProcess(Process); |
| | 1305 | | } |
| | 1306 | | } |
| | 1307 | |
|
| 0 | 1308 | | _disposed = true; |
| 0 | 1309 | | } |
| | 1310 | | } |
| | 1311 | | } |
| | 1312 | | } |