FFmpegLog.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. namespace Vinno.IUS.Common.Media.FFmpeg
  5. {
  6. public class FFmpegLog: IFFmpegLog
  7. {
  8. private readonly StringBuilder _complete = new StringBuilder();
  9. private TimeSpan? _duration;
  10. private int _lastReportedProgress;
  11. private readonly Regex _durationRegex = new Regex(@"Duration: (\d{2}:\d{2}:\d{2}.\d{2})");
  12. private readonly Regex _timeRegex = new Regex(@"time=(\d{2}:\d{2}:\d{2}.\d{2})");
  13. public event Action<int> ProgressChanged;
  14. public string Frame { get; private set; } = string.Empty;
  15. public string Content { get; private set; } = string.Empty;
  16. public void WriteArgs(string args)
  17. {
  18. _complete.AppendLine("ARGS:");
  19. _complete.AppendLine("-------------");
  20. _complete.AppendLine(args);
  21. _complete.AppendLine();
  22. _complete.AppendLine("OUTPUT:");
  23. _complete.AppendLine("-------------");
  24. }
  25. public void Write(string text)
  26. {
  27. if (text == null)
  28. return;
  29. _complete.AppendLine(text);
  30. if (_duration == null)
  31. {
  32. var match = _durationRegex.Match(text);
  33. if (match.Success)
  34. {
  35. _duration = TimeSpan.Parse(match.Groups[1].Value);
  36. }
  37. }
  38. if (text.StartsWith("frame=") || text.StartsWith("size="))
  39. {
  40. Frame = text;
  41. if (_duration != null)
  42. {
  43. var match = _timeRegex.Match(text);
  44. if (match.Success)
  45. {
  46. var time = TimeSpan.Parse(match.Groups[1].Value);
  47. var progress = (int)(time.TotalMilliseconds * 100 / _duration.Value.TotalMilliseconds);
  48. if (progress > _lastReportedProgress)
  49. {
  50. _lastReportedProgress = progress;
  51. ProgressChanged?.Invoke(progress);
  52. }
  53. }
  54. }
  55. }
  56. else Content += text + Environment.NewLine;
  57. }
  58. public string GetCompleteLog() => _complete.ToString();
  59. }
  60. }