BaseMediaHandler.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Net;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Common.Configuration;
  7. using MediaBrowser.Common.Logging;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Common.Net.Handlers;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Model.Entities;
  12. namespace MediaBrowser.Api.HttpHandlers
  13. {
  14. public abstract class BaseMediaHandler<T> : BaseHandler
  15. where T : BaseItem, new()
  16. {
  17. private T _LibraryItem;
  18. /// <summary>
  19. /// Gets the library item that will be played, if any
  20. /// </summary>
  21. protected T LibraryItem
  22. {
  23. get
  24. {
  25. if (_LibraryItem == null)
  26. {
  27. string id = QueryString["id"];
  28. if (!string.IsNullOrEmpty(id))
  29. {
  30. _LibraryItem = Kernel.Instance.GetItemById(Guid.Parse(id)) as T;
  31. }
  32. }
  33. return _LibraryItem;
  34. }
  35. }
  36. public int? AudioChannels
  37. {
  38. get
  39. {
  40. string val = QueryString["audiochannels"];
  41. if (string.IsNullOrEmpty(val))
  42. {
  43. return null;
  44. }
  45. return int.Parse(val);
  46. }
  47. }
  48. public int? AudioSampleRate
  49. {
  50. get
  51. {
  52. string val = QueryString["audiosamplerate"];
  53. if (string.IsNullOrEmpty(val))
  54. {
  55. return 44100;
  56. }
  57. return int.Parse(val);
  58. }
  59. }
  60. public override string ContentType
  61. {
  62. get
  63. {
  64. return MimeTypes.GetMimeType("." + GetOutputFormat());
  65. }
  66. }
  67. public override bool CompressResponse
  68. {
  69. get
  70. {
  71. return false;
  72. }
  73. }
  74. public override void ProcessRequest(HttpListenerContext ctx)
  75. {
  76. HttpListenerContext = ctx;
  77. if (!RequiresConversion())
  78. {
  79. new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx);
  80. return;
  81. }
  82. base.ProcessRequest(ctx);
  83. }
  84. protected abstract string GetCommandLineArguments();
  85. protected abstract string GetOutputFormat();
  86. protected abstract bool RequiresConversion();
  87. protected async override Task WriteResponseToOutputStream(Stream stream)
  88. {
  89. ProcessStartInfo startInfo = new ProcessStartInfo();
  90. startInfo.CreateNoWindow = true;
  91. startInfo.UseShellExecute = false;
  92. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  93. startInfo.RedirectStandardOutput = true;
  94. startInfo.RedirectStandardError = true;
  95. startInfo.FileName = ApiService.FFMpegPath;
  96. startInfo.WorkingDirectory = ApiService.FFMpegDirectory;
  97. startInfo.Arguments = GetCommandLineArguments();
  98. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  99. Process process = new Process();
  100. process.StartInfo = startInfo;
  101. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  102. FileStream logStream = new FileStream(Path.Combine(ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid().ToString() + ".txt"), FileMode.Create);
  103. try
  104. {
  105. process.Start();
  106. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  107. // If we ever decide to disable the ffmpeg log then you must uncomment the below line.
  108. //process.BeginErrorReadLine();
  109. Task debugLogTask = Task.Run(async () => { await process.StandardError.BaseStream.CopyToAsync(logStream); });
  110. await process.StandardOutput.BaseStream.CopyToAsync(stream);
  111. process.WaitForExit();
  112. Logger.LogInfo("FFMpeg exited with code " + process.ExitCode);
  113. await debugLogTask;
  114. }
  115. catch (Exception ex)
  116. {
  117. Logger.LogException(ex);
  118. // Hate having to do this
  119. try
  120. {
  121. process.Kill();
  122. }
  123. catch
  124. {
  125. }
  126. }
  127. finally
  128. {
  129. logStream.Dispose();
  130. process.Dispose();
  131. }
  132. }
  133. }
  134. }