BaseMediaHandler.cs 7.6 KB

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