BaseMediaHandler.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Logging;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Common.Net.Handlers;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Model.Entities;
  13. namespace MediaBrowser.Api.HttpHandlers
  14. {
  15. public abstract class BaseMediaHandler<T> : BaseHandler
  16. where T : BaseItem, new()
  17. {
  18. /// <summary>
  19. /// Supported values: mp3,flac,ogg,wav,asf,wma,aac
  20. /// </summary>
  21. protected virtual IEnumerable<string> OutputFormats
  22. {
  23. get
  24. {
  25. return QueryString["outputformats"].Split(',');
  26. }
  27. }
  28. /// <summary>
  29. /// These formats can be outputted directly but cannot be encoded to
  30. /// </summary>
  31. protected virtual IEnumerable<string> UnsupportedOutputEncodingFormats
  32. {
  33. get
  34. {
  35. return new string[] { };
  36. }
  37. }
  38. private T _LibraryItem;
  39. /// <summary>
  40. /// Gets the library item that will be played, if any
  41. /// </summary>
  42. protected T 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 T;
  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.Run(() =>
  84. {
  85. return MimeTypes.GetMimeType("." + GetConversionOutputFormat());
  86. });
  87. }
  88. public override bool ShouldCompressResponse(string contentType)
  89. {
  90. return false;
  91. }
  92. public override async Task ProcessRequest(HttpListenerContext ctx)
  93. {
  94. HttpListenerContext = ctx;
  95. if (!RequiresConversion())
  96. {
  97. await new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx);
  98. }
  99. else
  100. {
  101. await base.ProcessRequest(ctx);
  102. }
  103. }
  104. protected abstract string GetCommandLineArguments();
  105. /// <summary>
  106. /// Gets the format we'll be converting to
  107. /// </summary>
  108. protected virtual string GetConversionOutputFormat()
  109. {
  110. return OutputFormats.First(f => !UnsupportedOutputEncodingFormats.Any(s => s.Equals(f, StringComparison.OrdinalIgnoreCase)));
  111. }
  112. protected virtual bool RequiresConversion()
  113. {
  114. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  115. if (OutputFormats.Any(f => currentFormat.EndsWith(f, StringComparison.OrdinalIgnoreCase)))
  116. {
  117. // We can output these files directly, but we can't encode them
  118. if (UnsupportedOutputEncodingFormats.Any(f => currentFormat.EndsWith(f, StringComparison.OrdinalIgnoreCase)))
  119. {
  120. return false;
  121. }
  122. }
  123. else
  124. {
  125. // If it's not in a format the consumer accepts, return true
  126. return true;
  127. }
  128. return false;
  129. }
  130. protected async override Task WriteResponseToOutputStream(Stream stream)
  131. {
  132. ProcessStartInfo startInfo = new ProcessStartInfo();
  133. startInfo.CreateNoWindow = true;
  134. startInfo.UseShellExecute = false;
  135. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  136. startInfo.RedirectStandardOutput = true;
  137. startInfo.RedirectStandardError = true;
  138. startInfo.FileName = Kernel.Instance.ApplicationPaths.FFMpegPath;
  139. startInfo.WorkingDirectory = Kernel.Instance.ApplicationPaths.FFMpegDirectory;
  140. startInfo.Arguments = GetCommandLineArguments();
  141. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  142. Process process = new Process();
  143. process.StartInfo = startInfo;
  144. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  145. FileStream logStream = new FileStream(Path.Combine(Kernel.Instance.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid().ToString() + ".txt"), FileMode.Create);
  146. try
  147. {
  148. process.Start();
  149. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  150. // If we ever decide to disable the ffmpeg log then you must uncomment the below line.
  151. //process.BeginErrorReadLine();
  152. Task debugLogTask = Task.Run(async () => { await process.StandardError.BaseStream.CopyToAsync(logStream); });
  153. await process.StandardOutput.BaseStream.CopyToAsync(stream);
  154. process.WaitForExit();
  155. Logger.LogInfo("FFMpeg exited with code " + process.ExitCode);
  156. await debugLogTask;
  157. }
  158. catch (Exception ex)
  159. {
  160. Logger.LogException(ex);
  161. // Hate having to do this
  162. try
  163. {
  164. process.Kill();
  165. }
  166. catch
  167. {
  168. }
  169. }
  170. finally
  171. {
  172. logStream.Dispose();
  173. process.Dispose();
  174. }
  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. }