TranscodingJob.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Threading;
  5. using MediaBrowser.Common.Logging;
  6. namespace MediaBrowser.Api.Transcoding
  7. {
  8. /// <summary>
  9. /// Represents an active transcoding job
  10. /// </summary>
  11. public class TranscodingJob
  12. {
  13. public string InputFile { get; set; }
  14. public string OutputFile { get; set; }
  15. public string TranscoderPath { get; set; }
  16. public string Arguments { get; set; }
  17. public TranscoderJobStatus Status { get; private set; }
  18. /// <summary>
  19. /// Starts the job
  20. /// </summary>
  21. public void Start()
  22. {
  23. ApiService.AddTranscodingJob(this);
  24. ProcessStartInfo startInfo = new ProcessStartInfo();
  25. startInfo.CreateNoWindow = true;
  26. startInfo.UseShellExecute = false;
  27. startInfo.FileName = TranscoderPath;
  28. startInfo.WorkingDirectory = Path.GetDirectoryName(TranscoderPath);
  29. startInfo.Arguments = Arguments;
  30. Logger.LogInfo("TranscodingJob.Start: " + TranscoderPath + " " + Arguments);
  31. Process process = new Process();
  32. process.StartInfo = startInfo;
  33. process.EnableRaisingEvents = true;
  34. process.Start();
  35. process.Exited += process_Exited;
  36. }
  37. void process_Exited(object sender, EventArgs e)
  38. {
  39. ApiService.RemoveTranscodingJob(this);
  40. Process process = sender as Process;
  41. // If it terminated with an error
  42. if (process.ExitCode != 0)
  43. {
  44. Status = TranscoderJobStatus.Error;
  45. // Delete this since it won't be valid
  46. if (File.Exists(OutputFile))
  47. {
  48. File.Delete(OutputFile);
  49. }
  50. }
  51. else
  52. {
  53. Status = TranscoderJobStatus.Completed;
  54. }
  55. process.Dispose();
  56. }
  57. /// <summary>
  58. /// Provides a helper to wait for the job to exit
  59. /// </summary>
  60. public void WaitForExit()
  61. {
  62. while (true)
  63. {
  64. TranscoderJobStatus status = Status;
  65. if (status == TranscoderJobStatus.Completed || status == TranscoderJobStatus.Error)
  66. {
  67. break;
  68. }
  69. Thread.Sleep(500);
  70. }
  71. }
  72. }
  73. public enum TranscoderJobStatus
  74. {
  75. Queued,
  76. Started,
  77. Completed,
  78. Error
  79. }
  80. }