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