BaseMediaHandler.cs 7.6 KB

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