BaseMediaHandler.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using MediaBrowser.Common.Logging;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.Net.Handlers;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api.HttpHandlers
  14. {
  15. public abstract class BaseMediaHandler<TBaseItemType, TOutputType> : BaseHandler
  16. where TBaseItemType : BaseItem, new()
  17. {
  18. /// <summary>
  19. /// Supported values: mp3,flac,ogg,wav,asf,wma,aac
  20. /// </summary>
  21. protected virtual IEnumerable<TOutputType> OutputFormats
  22. {
  23. get
  24. {
  25. return QueryString["outputformats"].Split(',').Select(o => (TOutputType)Enum.Parse(typeof(TOutputType), o, true));
  26. }
  27. }
  28. /// <summary>
  29. /// These formats can be outputted directly but cannot be encoded to
  30. /// </summary>
  31. protected virtual IEnumerable<TOutputType> UnsupportedOutputEncodingFormats
  32. {
  33. get
  34. {
  35. return new TOutputType[] { };
  36. }
  37. }
  38. private TBaseItemType _libraryItem;
  39. /// <summary>
  40. /// Gets the library item that will be played, if any
  41. /// </summary>
  42. protected TBaseItemType LibraryItem
  43. {
  44. get
  45. {
  46. if (_libraryItem == null)
  47. {
  48. string id = QueryString["id"];
  49. if (!string.IsNullOrEmpty(id))
  50. {
  51. _libraryItem = Kernel.Instance.GetItemById(Guid.Parse(id)) as TBaseItemType;
  52. }
  53. }
  54. return _libraryItem;
  55. }
  56. }
  57. public int? AudioChannels
  58. {
  59. get
  60. {
  61. string val = QueryString["audiochannels"];
  62. if (string.IsNullOrEmpty(val))
  63. {
  64. return null;
  65. }
  66. return int.Parse(val);
  67. }
  68. }
  69. public int? AudioSampleRate
  70. {
  71. get
  72. {
  73. string val = QueryString["audiosamplerate"];
  74. if (string.IsNullOrEmpty(val))
  75. {
  76. return 44100;
  77. }
  78. return int.Parse(val);
  79. }
  80. }
  81. protected override Task<ResponseInfo> GetResponseInfo()
  82. {
  83. ResponseInfo info = new ResponseInfo
  84. {
  85. ContentType = MimeTypes.GetMimeType("." + GetConversionOutputFormat()),
  86. CompressResponse = false
  87. };
  88. return Task.FromResult<ResponseInfo>(info);
  89. }
  90. public override Task ProcessRequest(HttpListenerContext ctx)
  91. {
  92. HttpListenerContext = ctx;
  93. if (!RequiresConversion())
  94. {
  95. return new StaticFileHandler { Path = LibraryItem.Path }.ProcessRequest(ctx);
  96. }
  97. return base.ProcessRequest(ctx);
  98. }
  99. protected abstract string GetCommandLineArguments();
  100. /// <summary>
  101. /// Gets the format we'll be converting to
  102. /// </summary>
  103. protected virtual TOutputType GetConversionOutputFormat()
  104. {
  105. return OutputFormats.First(f => !UnsupportedOutputEncodingFormats.Any(s => s.ToString().Equals(f.ToString(), StringComparison.OrdinalIgnoreCase)));
  106. }
  107. protected virtual bool RequiresConversion()
  108. {
  109. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  110. if (OutputFormats.Any(f => currentFormat.EndsWith(f.ToString(), StringComparison.OrdinalIgnoreCase)))
  111. {
  112. // We can output these files directly, but we can't encode them
  113. if (UnsupportedOutputEncodingFormats.Any(f => currentFormat.EndsWith(f.ToString(), StringComparison.OrdinalIgnoreCase)))
  114. {
  115. return false;
  116. }
  117. }
  118. else
  119. {
  120. // If it's not in a format the consumer accepts, return true
  121. return true;
  122. }
  123. return false;
  124. }
  125. private FileStream LogFileStream { get; set; }
  126. protected async override Task WriteResponseToOutputStream(Stream stream)
  127. {
  128. var startInfo = new ProcessStartInfo{};
  129. startInfo.CreateNoWindow = true;
  130. startInfo.UseShellExecute = false;
  131. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  132. startInfo.RedirectStandardOutput = true;
  133. startInfo.RedirectStandardError = true;
  134. startInfo.FileName = Kernel.Instance.ApplicationPaths.FFMpegPath;
  135. startInfo.WorkingDirectory = Kernel.Instance.ApplicationPaths.FFMpegDirectory;
  136. startInfo.Arguments = GetCommandLineArguments();
  137. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  138. var process = new Process{};
  139. process.StartInfo = startInfo;
  140. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  141. LogFileStream = new FileStream(Path.Combine(Kernel.Instance.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid().ToString() + ".txt"), FileMode.Create);
  142. process.EnableRaisingEvents = true;
  143. process.Exited += ProcessExited;
  144. try
  145. {
  146. process.Start();
  147. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  148. // Kick off two tasks
  149. Task mediaTask = process.StandardOutput.BaseStream.CopyToAsync(stream);
  150. Task debugLogTask = process.StandardError.BaseStream.CopyToAsync(LogFileStream);
  151. await mediaTask.ConfigureAwait(false);
  152. //await debugLogTask.ConfigureAwait(false);
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.LogException(ex);
  157. // Hate having to do this
  158. try
  159. {
  160. process.Kill();
  161. }
  162. catch
  163. {
  164. }
  165. }
  166. }
  167. void ProcessExited(object sender, EventArgs e)
  168. {
  169. if (LogFileStream != null)
  170. {
  171. LogFileStream.Dispose();
  172. }
  173. var process = sender as Process;
  174. Logger.LogInfo("FFMpeg exited with code " + process.ExitCode);
  175. process.Dispose();
  176. }
  177. /// <summary>
  178. /// Gets the number of audio channels to specify on the command line
  179. /// </summary>
  180. protected int? GetNumAudioChannelsParam(int libraryItemChannels)
  181. {
  182. // If the user requested a max number of channels
  183. if (AudioChannels.HasValue)
  184. {
  185. // Only specify the param if we're going to downmix
  186. if (AudioChannels.Value < libraryItemChannels)
  187. {
  188. return AudioChannels.Value;
  189. }
  190. }
  191. return null;
  192. }
  193. /// <summary>
  194. /// Gets the number of audio channels to specify on the command line
  195. /// </summary>
  196. protected int? GetSampleRateParam(int libraryItemSampleRate)
  197. {
  198. // If the user requested a max value
  199. if (AudioSampleRate.HasValue)
  200. {
  201. // Only specify the param if we're going to downmix
  202. if (AudioSampleRate.Value < libraryItemSampleRate)
  203. {
  204. return AudioSampleRate.Value;
  205. }
  206. }
  207. return null;
  208. }
  209. }
  210. }