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