BaseProgressiveStreamingService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.MediaInfo;
  12. using ServiceStack.Web;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Api.Playback.Progressive
  19. {
  20. /// <summary>
  21. /// Class BaseProgressiveStreamingService
  22. /// </summary>
  23. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  24. {
  25. protected readonly IImageProcessor ImageProcessor;
  26. protected readonly IHttpClient HttpClient;
  27. protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  28. {
  29. ImageProcessor = imageProcessor;
  30. HttpClient = httpClient;
  31. }
  32. /// <summary>
  33. /// Gets the output file extension.
  34. /// </summary>
  35. /// <param name="state">The state.</param>
  36. /// <returns>System.String.</returns>
  37. protected override string GetOutputFileExtension(StreamState state)
  38. {
  39. var ext = base.GetOutputFileExtension(state);
  40. if (!string.IsNullOrEmpty(ext))
  41. {
  42. return ext;
  43. }
  44. var isVideoRequest = state.VideoRequest != null;
  45. // Try to infer based on the desired video codec
  46. if (isVideoRequest)
  47. {
  48. var videoCodec = state.VideoRequest.VideoCodec;
  49. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  50. {
  51. return ".ts";
  52. }
  53. if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
  54. {
  55. return ".ogv";
  56. }
  57. if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
  58. {
  59. return ".webm";
  60. }
  61. if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
  62. {
  63. return ".asf";
  64. }
  65. }
  66. // Try to infer based on the desired audio codec
  67. if (!isVideoRequest)
  68. {
  69. var audioCodec = state.Request.AudioCodec;
  70. if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
  71. {
  72. return ".aac";
  73. }
  74. if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
  75. {
  76. return ".mp3";
  77. }
  78. if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
  79. {
  80. return ".ogg";
  81. }
  82. if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
  83. {
  84. return ".wma";
  85. }
  86. }
  87. return null;
  88. }
  89. /// <summary>
  90. /// Gets the type of the transcoding job.
  91. /// </summary>
  92. /// <value>The type of the transcoding job.</value>
  93. protected override TranscodingJobType TranscodingJobType
  94. {
  95. get { return TranscodingJobType.Progressive; }
  96. }
  97. /// <summary>
  98. /// Processes the request.
  99. /// </summary>
  100. /// <param name="request">The request.</param>
  101. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  102. /// <returns>Task.</returns>
  103. protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
  104. {
  105. var state = GetState(request, CancellationToken.None).Result;
  106. var responseHeaders = new Dictionary<string, string>();
  107. // Static remote stream
  108. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  109. {
  110. AddDlnaHeaders(state, responseHeaders, true);
  111. using (state)
  112. {
  113. return GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest).Result;
  114. }
  115. }
  116. if (request.Static && state.InputProtocol != MediaProtocol.File)
  117. {
  118. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  119. }
  120. var outputPath = state.OutputFilePath;
  121. var outputPathExists = File.Exists(outputPath);
  122. var isStatic = request.Static ||
  123. (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
  124. AddDlnaHeaders(state, responseHeaders, isStatic);
  125. // Static stream
  126. if (request.Static)
  127. {
  128. var contentType = state.GetMimeType(state.MediaPath);
  129. using (state)
  130. {
  131. return ResultFactory.GetStaticFileResult(Request, state.MediaPath, contentType, FileShare.Read, responseHeaders, isHeadRequest);
  132. }
  133. }
  134. // Not static but transcode cache file exists
  135. if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
  136. {
  137. var contentType = state.GetMimeType(outputPath);
  138. try
  139. {
  140. return ResultFactory.GetStaticFileResult(Request, outputPath, contentType, FileShare.Read, responseHeaders, isHeadRequest);
  141. }
  142. finally
  143. {
  144. state.Dispose();
  145. }
  146. }
  147. // Need to start ffmpeg
  148. try
  149. {
  150. return GetStreamResult(state, responseHeaders, isHeadRequest).Result;
  151. }
  152. catch
  153. {
  154. state.Dispose();
  155. throw;
  156. }
  157. }
  158. /// <summary>
  159. /// Gets the static remote stream result.
  160. /// </summary>
  161. /// <param name="state">The state.</param>
  162. /// <param name="responseHeaders">The response headers.</param>
  163. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  164. /// <returns>Task{System.Object}.</returns>
  165. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest)
  166. {
  167. string useragent = null;
  168. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  169. var options = new HttpRequestOptions
  170. {
  171. Url = state.MediaPath,
  172. UserAgent = useragent,
  173. BufferContent = false
  174. };
  175. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  176. responseHeaders["Accept-Ranges"] = "none";
  177. var length = response.Headers["Content-Length"];
  178. if (!string.IsNullOrEmpty(length))
  179. {
  180. responseHeaders["Content-Length"] = length;
  181. }
  182. if (isHeadRequest)
  183. {
  184. using (response.Content)
  185. {
  186. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  187. }
  188. }
  189. var result = new StaticRemoteStreamWriter(response);
  190. result.Options["Content-Type"] = response.ContentType;
  191. // Add the response headers to the result object
  192. foreach (var header in responseHeaders)
  193. {
  194. result.Options[header.Key] = header.Value;
  195. }
  196. return result;
  197. }
  198. /// <summary>
  199. /// Gets the stream result.
  200. /// </summary>
  201. /// <param name="state">The state.</param>
  202. /// <param name="responseHeaders">The response headers.</param>
  203. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  204. /// <returns>Task{System.Object}.</returns>
  205. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest)
  206. {
  207. // Use the command line args with a dummy playlist path
  208. var outputPath = state.OutputFilePath;
  209. responseHeaders["Accept-Ranges"] = "none";
  210. var contentType = state.GetMimeType(outputPath);
  211. var contentLength = state.EstimateContentLength ? GetEstimatedContentLength(state) : null;
  212. if (contentLength.HasValue)
  213. {
  214. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  215. }
  216. // Headers only
  217. if (isHeadRequest)
  218. {
  219. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  220. if (!contentLength.HasValue)
  221. {
  222. var hasOptions = streamResult as IHasOptions;
  223. if (hasOptions != null)
  224. {
  225. if (hasOptions.Options.ContainsKey("Content-Length"))
  226. {
  227. hasOptions.Options.Remove("Content-Length");
  228. }
  229. }
  230. }
  231. return streamResult;
  232. }
  233. if (!File.Exists(outputPath))
  234. {
  235. await StartFfMpeg(state, outputPath, new CancellationTokenSource()).ConfigureAwait(false);
  236. }
  237. else
  238. {
  239. ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  240. state.Dispose();
  241. }
  242. var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem);
  243. result.Options["Content-Type"] = contentType;
  244. // Add the response headers to the result object
  245. foreach (var item in responseHeaders)
  246. {
  247. result.Options[item.Key] = item.Value;
  248. }
  249. return result;
  250. }
  251. /// <summary>
  252. /// Gets the length of the estimated content.
  253. /// </summary>
  254. /// <param name="state">The state.</param>
  255. /// <returns>System.Nullable{System.Int64}.</returns>
  256. private long? GetEstimatedContentLength(StreamState state)
  257. {
  258. var totalBitrate = state.TotalOutputBitrate ?? 0;
  259. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  260. {
  261. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds);
  262. }
  263. return null;
  264. }
  265. }
  266. }