AudioHandler.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 class AudioHandler : BaseMediaHandler<Audio>
  16. {
  17. public IEnumerable<string> AudioFormats
  18. {
  19. get
  20. {
  21. string val = QueryString["audioformats"];
  22. if (string.IsNullOrEmpty(val))
  23. {
  24. return new string[] { "mp3" };
  25. }
  26. return val.Split(',');
  27. }
  28. }
  29. public IEnumerable<int> AudioBitRates
  30. {
  31. get
  32. {
  33. string val = QueryString["audioformats"];
  34. if (string.IsNullOrEmpty(val))
  35. {
  36. return new int[] { };
  37. }
  38. return val.Split(',').Select(v => int.Parse(v));
  39. }
  40. }
  41. private int? GetMaxAcceptedBitRate(string audioFormat)
  42. {
  43. int index = AudioFormats.ToList().IndexOf(audioFormat);
  44. if (!AudioBitRates.Any())
  45. {
  46. return null;
  47. }
  48. return AudioBitRates.ElementAt(index);
  49. }
  50. /// <summary>
  51. /// Determines whether or not the original file requires transcoding
  52. /// </summary>
  53. protected override bool RequiresConversion()
  54. {
  55. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  56. // If it's not in a format the consumer accepts, return true
  57. if (!AudioFormats.Any(f => currentFormat.EndsWith(f, StringComparison.OrdinalIgnoreCase)))
  58. {
  59. return true;
  60. }
  61. int? bitrate = GetMaxAcceptedBitRate(currentFormat);
  62. // If the bitrate is greater than our desired bitrate, we need to transcode
  63. if (bitrate.HasValue && bitrate.Value < LibraryItem.BitRate)
  64. {
  65. return true;
  66. }
  67. // If the number of channels is greater than our desired channels, we need to transcode
  68. if (AudioChannels.HasValue && AudioChannels.Value < LibraryItem.Channels)
  69. {
  70. return true;
  71. }
  72. // If the sample rate is greater than our desired sample rate, we need to transcode
  73. if (AudioSampleRate.HasValue && AudioSampleRate.Value < LibraryItem.SampleRate)
  74. {
  75. return true;
  76. }
  77. // Yay
  78. return false;
  79. }
  80. /// <summary>
  81. /// Gets the format we'll be converting to
  82. /// </summary>
  83. protected override string GetOutputFormat()
  84. {
  85. return AudioFormats.First();
  86. }
  87. /// <summary>
  88. /// Creates arguments to pass to ffmpeg
  89. /// </summary>
  90. protected override string GetCommandLineArguments()
  91. {
  92. List<string> audioTranscodeParams = new List<string>();
  93. string outputFormat = GetOutputFormat();
  94. int? bitrate = GetMaxAcceptedBitRate(outputFormat);
  95. if (bitrate.HasValue)
  96. {
  97. audioTranscodeParams.Add("-ab " + bitrate.Value);
  98. }
  99. if (AudioChannels.HasValue)
  100. {
  101. audioTranscodeParams.Add("-ac " + AudioChannels.Value);
  102. }
  103. if (AudioSampleRate.HasValue)
  104. {
  105. audioTranscodeParams.Add("-ar " + AudioSampleRate.Value);
  106. }
  107. audioTranscodeParams.Add("-f " + outputFormat);
  108. return "-i \"" + LibraryItem.Path + "\" -vn " + string.Join(" ", audioTranscodeParams.ToArray()) + " -";
  109. }
  110. }
  111. public abstract class BaseMediaHandler<T> : BaseHandler
  112. where T : BaseItem, new()
  113. {
  114. private T _LibraryItem;
  115. /// <summary>
  116. /// Gets the library item that will be played, if any
  117. /// </summary>
  118. protected T LibraryItem
  119. {
  120. get
  121. {
  122. if (_LibraryItem == null)
  123. {
  124. string id = QueryString["id"];
  125. if (!string.IsNullOrEmpty(id))
  126. {
  127. _LibraryItem = Kernel.Instance.GetItemById(Guid.Parse(id)) as T;
  128. }
  129. }
  130. return _LibraryItem;
  131. }
  132. }
  133. public int? AudioChannels
  134. {
  135. get
  136. {
  137. string val = QueryString["audiochannels"];
  138. if (string.IsNullOrEmpty(val))
  139. {
  140. return null;
  141. }
  142. return int.Parse(val);
  143. }
  144. }
  145. public int? AudioSampleRate
  146. {
  147. get
  148. {
  149. string val = QueryString["audiosamplerate"];
  150. if (string.IsNullOrEmpty(val))
  151. {
  152. return 44100;
  153. }
  154. return int.Parse(val);
  155. }
  156. }
  157. public override string ContentType
  158. {
  159. get
  160. {
  161. return MimeTypes.GetMimeType("." + GetOutputFormat());
  162. }
  163. }
  164. public override bool CompressResponse
  165. {
  166. get
  167. {
  168. return false;
  169. }
  170. }
  171. public override void ProcessRequest(HttpListenerContext ctx)
  172. {
  173. HttpListenerContext = ctx;
  174. if (!RequiresConversion())
  175. {
  176. new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx);
  177. return;
  178. }
  179. base.ProcessRequest(ctx);
  180. }
  181. protected abstract string GetCommandLineArguments();
  182. protected abstract string GetOutputFormat();
  183. protected abstract bool RequiresConversion();
  184. protected async override Task WriteResponseToOutputStream(Stream stream)
  185. {
  186. ProcessStartInfo startInfo = new ProcessStartInfo();
  187. startInfo.CreateNoWindow = true;
  188. startInfo.UseShellExecute = false;
  189. startInfo.RedirectStandardOutput = true;
  190. startInfo.RedirectStandardError = true;
  191. startInfo.FileName = ApiService.FFMpegPath;
  192. startInfo.WorkingDirectory = ApiService.FFMpegDirectory;
  193. startInfo.Arguments = GetCommandLineArguments();
  194. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  195. Process process = new Process();
  196. process.StartInfo = startInfo;
  197. try
  198. {
  199. process.Start();
  200. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  201. process.BeginErrorReadLine();
  202. await process.StandardOutput.BaseStream.CopyToAsync(stream);
  203. process.WaitForExit();
  204. }
  205. catch (Exception ex)
  206. {
  207. Logger.LogException(ex);
  208. }
  209. finally
  210. {
  211. process.Dispose();
  212. }
  213. }
  214. }
  215. }