FfProbeKeyframeExtractor.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. namespace Jellyfin.MediaEncoding.Keyframes.FfProbe;
  7. /// <summary>
  8. /// FfProbe based keyframe extractor.
  9. /// </summary>
  10. public static class FfProbeKeyframeExtractor
  11. {
  12. /// <summary>
  13. /// Extracts the keyframes using the ffprobe executable at the specified path.
  14. /// </summary>
  15. /// <param name="ffProbePath">The path to the ffprobe executable.</param>
  16. /// <param name="filePath">The file path.</param>
  17. /// <returns>An instance of <see cref="KeyframeData"/>.</returns>
  18. public static KeyframeData GetKeyframeData(string ffProbePath, string filePath)
  19. {
  20. using var process = new Process
  21. {
  22. StartInfo = new ProcessStartInfo
  23. {
  24. FileName = ffProbePath,
  25. Arguments = string.Format(
  26. CultureInfo.InvariantCulture,
  27. "-fflags +genpts -v error -skip_frame nokey -show_entries format=duration -show_entries stream=duration -show_entries packet=pts_time,flags -select_streams v -of csv \"{0}\"",
  28. filePath),
  29. CreateNoWindow = true,
  30. UseShellExecute = false,
  31. RedirectStandardOutput = true,
  32. WindowStyle = ProcessWindowStyle.Hidden,
  33. ErrorDialog = false,
  34. },
  35. EnableRaisingEvents = true
  36. };
  37. try
  38. {
  39. process.Start();
  40. try
  41. {
  42. process.PriorityClass = ProcessPriorityClass.BelowNormal;
  43. }
  44. catch
  45. {
  46. // We do not care if process priority setting fails
  47. // Ideally log a warning but this does not have a logger available
  48. }
  49. return ParseStream(process.StandardOutput);
  50. }
  51. catch (Exception)
  52. {
  53. try
  54. {
  55. if (!process.HasExited)
  56. {
  57. process.Kill();
  58. }
  59. }
  60. catch
  61. {
  62. // We do not care if this fails
  63. }
  64. throw;
  65. }
  66. }
  67. internal static KeyframeData ParseStream(StreamReader reader)
  68. {
  69. var keyframes = new List<long>();
  70. double streamDuration = 0;
  71. double formatDuration = 0;
  72. using (reader)
  73. {
  74. while (!reader.EndOfStream)
  75. {
  76. var line = reader.ReadLine().AsSpan();
  77. if (line.IsEmpty)
  78. {
  79. continue;
  80. }
  81. var firstComma = line.IndexOf(',');
  82. var lineType = line[..firstComma];
  83. var rest = line[(firstComma + 1)..];
  84. if (lineType.Equals("packet", StringComparison.OrdinalIgnoreCase))
  85. {
  86. // Split time and flags from the packet line. Example line: packet,7169.079000,K_
  87. var secondComma = rest.IndexOf(',');
  88. var ptsTime = rest[..secondComma];
  89. var flags = rest[(secondComma + 1)..];
  90. if (flags.StartsWith("K_"))
  91. {
  92. if (double.TryParse(ptsTime, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var keyframe))
  93. {
  94. // Have to manually convert to ticks to avoid rounding errors as TimeSpan is only precise down to 1 ms when converting double.
  95. keyframes.Add(Convert.ToInt64(keyframe * TimeSpan.TicksPerSecond));
  96. }
  97. }
  98. }
  99. else if (lineType.Equals("stream", StringComparison.OrdinalIgnoreCase))
  100. {
  101. if (double.TryParse(rest, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var streamDurationResult))
  102. {
  103. streamDuration = streamDurationResult;
  104. }
  105. }
  106. else if (lineType.Equals("format", StringComparison.OrdinalIgnoreCase))
  107. {
  108. if (double.TryParse(rest, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var formatDurationResult))
  109. {
  110. formatDuration = formatDurationResult;
  111. }
  112. }
  113. }
  114. // Prefer the stream duration as it should be more accurate
  115. var duration = streamDuration > 0 ? streamDuration : formatDuration;
  116. return new KeyframeData(TimeSpan.FromSeconds(duration).Ticks, keyframes);
  117. }
  118. }
  119. }