BaseMediaHandler.cs 7.6 KB

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