AudioHandler.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. private string GetAudioArguments()
  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. protected async override Task WriteResponseToOutputStream(Stream stream)
  111. {
  112. ProcessStartInfo startInfo = new ProcessStartInfo();
  113. startInfo.CreateNoWindow = true;
  114. startInfo.UseShellExecute = false;
  115. startInfo.RedirectStandardOutput = true;
  116. startInfo.FileName = ApiService.FFMpegPath;
  117. startInfo.WorkingDirectory = ApiService.FFMpegDirectory;
  118. startInfo.Arguments = GetAudioArguments();
  119. Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
  120. Process process = new Process();
  121. process.StartInfo = startInfo;
  122. try
  123. {
  124. process.Start();
  125. await process.StandardOutput.BaseStream.CopyToAsync(stream);
  126. }
  127. catch (Exception ex)
  128. {
  129. Logger.LogException(ex);
  130. }
  131. finally
  132. {
  133. process.Dispose();
  134. }
  135. }
  136. }
  137. public abstract class BaseMediaHandler<T> : BaseHandler
  138. where T : BaseItem, new()
  139. {
  140. private T _LibraryItem;
  141. /// <summary>
  142. /// Gets the library item that will be played, if any
  143. /// </summary>
  144. protected T LibraryItem
  145. {
  146. get
  147. {
  148. if (_LibraryItem == null)
  149. {
  150. string id = QueryString["id"];
  151. if (!string.IsNullOrEmpty(id))
  152. {
  153. _LibraryItem = Kernel.Instance.GetItemById(Guid.Parse(id)) as T;
  154. }
  155. }
  156. return _LibraryItem;
  157. }
  158. }
  159. public int? AudioChannels
  160. {
  161. get
  162. {
  163. string val = QueryString["audiochannels"];
  164. if (string.IsNullOrEmpty(val))
  165. {
  166. return null;
  167. }
  168. return int.Parse(val);
  169. }
  170. }
  171. public int? AudioSampleRate
  172. {
  173. get
  174. {
  175. string val = QueryString["audiosamplerate"];
  176. if (string.IsNullOrEmpty(val))
  177. {
  178. return 44100;
  179. }
  180. return int.Parse(val);
  181. }
  182. }
  183. public override string ContentType
  184. {
  185. get
  186. {
  187. return MimeTypes.GetMimeType("." + GetOutputFormat());
  188. }
  189. }
  190. public override bool CompressResponse
  191. {
  192. get
  193. {
  194. return false;
  195. }
  196. }
  197. public override void ProcessRequest(HttpListenerContext ctx)
  198. {
  199. HttpListenerContext = ctx;
  200. if (!RequiresConversion())
  201. {
  202. new StaticFileHandler() { Path = LibraryItem.Path }.ProcessRequest(ctx);
  203. return;
  204. }
  205. base.ProcessRequest(ctx);
  206. }
  207. protected abstract string GetOutputFormat();
  208. protected abstract bool RequiresConversion();
  209. }
  210. }