BaseMediaHandler.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. public override Task<string> GetContentType()
  82. {
  83. return Task.FromResult(MimeTypes.GetMimeType("." + GetConversionOutputFormat()));
  84. }
  85. public override bool ShouldCompressResponse(string contentType)
  86. {
  87. return false;
  88. }
  89. public override Task ProcessRequest(HttpListenerContext ctx)
  90. {
  91. HttpListenerContext = ctx;
  92. if (!RequiresConversion())
  93. {
  94. return new StaticFileHandler { Path = LibraryItem.Path }.ProcessRequest(ctx);
  95. }
  96. return base.ProcessRequest(ctx);
  97. }
  98. protected abstract string GetCommandLineArguments();
  99. /// <summary>
  100. /// Gets the format we'll be converting to
  101. /// </summary>
  102. protected virtual TOutputType GetConversionOutputFormat()
  103. {
  104. return OutputFormats.First(f => !UnsupportedOutputEncodingFormats.Any(s => s.ToString().Equals(f.ToString(), StringComparison.OrdinalIgnoreCase)));
  105. }
  106. protected virtual bool RequiresConversion()
  107. {
  108. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  109. if (OutputFormats.Any(f => currentFormat.EndsWith(f.ToString(), StringComparison.OrdinalIgnoreCase)))
  110. {
  111. // We can output these files directly, but we can't encode them
  112. if (UnsupportedOutputEncodingFormats.Any(f => currentFormat.EndsWith(f.ToString(), StringComparison.OrdinalIgnoreCase)))
  113. {
  114. return false;
  115. }
  116. }
  117. else
  118. {
  119. // If it's not in a format the consumer accepts, return true
  120. return true;
  121. }
  122. return false;
  123. }
  124. private FileStream LogFileStream { get; set; }
  125. protected async override Task WriteResponseToOutputStream(Stream stream)
  126. {
  127. var startInfo = new ProcessStartInfo{};
  128. startInfo.CreateNoWindow = true;
  129. startInfo.UseShellExecute = false;
  130. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  131. startInfo.RedirectStandardOutput = true;
  132. startInfo.RedirectStandardError = true;
  133. startInfo.FileName = Kernel.Instance.ApplicationPaths.FFMpegPath;
  134. startInfo.WorkingDirectory = Kernel.Instance.ApplicationPaths.FFMpegDirectory;
  135. startInfo.Arguments = GetCommandLineArguments();
  136. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  137. var process = new Process{};
  138. process.StartInfo = startInfo;
  139. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  140. LogFileStream = new FileStream(Path.Combine(Kernel.Instance.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid().ToString() + ".txt"), FileMode.Create);
  141. process.EnableRaisingEvents = true;
  142. process.Exited += ProcessExited;
  143. try
  144. {
  145. process.Start();
  146. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  147. // Kick off two tasks
  148. Task mediaTask = process.StandardOutput.BaseStream.CopyToAsync(stream);
  149. Task debugLogTask = process.StandardError.BaseStream.CopyToAsync(LogFileStream);
  150. await mediaTask.ConfigureAwait(false);
  151. //await debugLogTask.ConfigureAwait(false);
  152. }
  153. catch (Exception ex)
  154. {
  155. Logger.LogException(ex);
  156. // Hate having to do this
  157. try
  158. {
  159. process.Kill();
  160. }
  161. catch
  162. {
  163. }
  164. }
  165. }
  166. void ProcessExited(object sender, EventArgs e)
  167. {
  168. if (LogFileStream != null)
  169. {
  170. LogFileStream.Dispose();
  171. }
  172. var process = sender as Process;
  173. Logger.LogInfo("FFMpeg exited with code " + process.ExitCode);
  174. process.Dispose();
  175. }
  176. /// <summary>
  177. /// Gets the number of audio channels to specify on the command line
  178. /// </summary>
  179. protected int? GetNumAudioChannelsParam(int libraryItemChannels)
  180. {
  181. // If the user requested a max number of channels
  182. if (AudioChannels.HasValue)
  183. {
  184. // Only specify the param if we're going to downmix
  185. if (AudioChannels.Value < libraryItemChannels)
  186. {
  187. return AudioChannels.Value;
  188. }
  189. }
  190. return null;
  191. }
  192. /// <summary>
  193. /// Gets the number of audio channels to specify on the command line
  194. /// </summary>
  195. protected int? GetSampleRateParam(int libraryItemSampleRate)
  196. {
  197. // If the user requested a max value
  198. if (AudioSampleRate.HasValue)
  199. {
  200. // Only specify the param if we're going to downmix
  201. if (AudioSampleRate.Value < libraryItemSampleRate)
  202. {
  203. return AudioSampleRate.Value;
  204. }
  205. }
  206. return null;
  207. }
  208. }
  209. }