BaseProgressiveStreamingService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 cancellationTokenSource = new CancellationTokenSource();
  106. var state = GetState(request, cancellationTokenSource.Token).Result;
  107. var responseHeaders = new Dictionary<string, string>();
  108. // Static remote stream
  109. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  110. {
  111. AddDlnaHeaders(state, responseHeaders, true);
  112. using (state)
  113. {
  114. return GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).Result;
  115. }
  116. }
  117. if (request.Static && state.InputProtocol != MediaProtocol.File)
  118. {
  119. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  120. }
  121. var outputPath = state.OutputFilePath;
  122. var outputPathExists = File.Exists(outputPath);
  123. var isStatic = request.Static ||
  124. (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
  125. AddDlnaHeaders(state, responseHeaders, isStatic);
  126. // Static stream
  127. if (request.Static)
  128. {
  129. var contentType = state.GetMimeType(state.MediaPath);
  130. using (state)
  131. {
  132. var throttleLimit = state.InputBitrate.HasValue ? (state.InputBitrate.Value / 8) : 0;
  133. return ResultFactory.GetStaticFileResult(Request, state.MediaPath, contentType, null, FileShare.Read, responseHeaders, isHeadRequest, request.Throttle, throttleLimit);
  134. }
  135. }
  136. // Not static but transcode cache file exists
  137. if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
  138. {
  139. var contentType = state.GetMimeType(outputPath);
  140. try
  141. {
  142. return ResultFactory.GetStaticFileResult(Request, outputPath, contentType, null, FileShare.Read, responseHeaders, isHeadRequest);
  143. }
  144. finally
  145. {
  146. state.Dispose();
  147. }
  148. }
  149. // Need to start ffmpeg
  150. try
  151. {
  152. return GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).Result;
  153. }
  154. catch
  155. {
  156. state.Dispose();
  157. throw;
  158. }
  159. }
  160. /// <summary>
  161. /// Gets the static remote stream result.
  162. /// </summary>
  163. /// <param name="state">The state.</param>
  164. /// <param name="responseHeaders">The response headers.</param>
  165. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  166. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  167. /// <returns>Task{System.Object}.</returns>
  168. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  169. {
  170. string useragent = null;
  171. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  172. var options = new HttpRequestOptions
  173. {
  174. Url = state.MediaPath,
  175. UserAgent = useragent,
  176. BufferContent = false,
  177. CancellationToken = cancellationTokenSource.Token
  178. };
  179. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  180. responseHeaders["Accept-Ranges"] = "none";
  181. var length = response.Headers["Content-Length"];
  182. if (!string.IsNullOrEmpty(length))
  183. {
  184. responseHeaders["Content-Length"] = length;
  185. }
  186. if (isHeadRequest)
  187. {
  188. using (response.Content)
  189. {
  190. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  191. }
  192. }
  193. var result = new StaticRemoteStreamWriter(response);
  194. result.Options["Content-Type"] = response.ContentType;
  195. // Add the response headers to the result object
  196. foreach (var header in responseHeaders)
  197. {
  198. result.Options[header.Key] = header.Value;
  199. }
  200. return result;
  201. }
  202. /// <summary>
  203. /// Gets the stream result.
  204. /// </summary>
  205. /// <param name="state">The state.</param>
  206. /// <param name="responseHeaders">The response headers.</param>
  207. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  208. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  209. /// <returns>Task{System.Object}.</returns>
  210. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  211. {
  212. // Use the command line args with a dummy playlist path
  213. var outputPath = state.OutputFilePath;
  214. responseHeaders["Accept-Ranges"] = "none";
  215. var contentType = state.GetMimeType(outputPath);
  216. var contentLength = state.EstimateContentLength ? GetEstimatedContentLength(state) : null;
  217. if (contentLength.HasValue)
  218. {
  219. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  220. }
  221. // Headers only
  222. if (isHeadRequest)
  223. {
  224. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  225. if (!contentLength.HasValue)
  226. {
  227. var hasOptions = streamResult as IHasOptions;
  228. if (hasOptions != null)
  229. {
  230. if (hasOptions.Options.ContainsKey("Content-Length"))
  231. {
  232. hasOptions.Options.Remove("Content-Length");
  233. }
  234. }
  235. }
  236. return streamResult;
  237. }
  238. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  239. try
  240. {
  241. if (!File.Exists(outputPath))
  242. {
  243. await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  244. }
  245. else
  246. {
  247. ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  248. state.Dispose();
  249. }
  250. var job = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
  251. var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem, job);
  252. result.Options["Content-Type"] = contentType;
  253. // Add the response headers to the result object
  254. foreach (var item in responseHeaders)
  255. {
  256. result.Options[item.Key] = item.Value;
  257. }
  258. return result;
  259. }
  260. finally
  261. {
  262. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  263. }
  264. }
  265. /// <summary>
  266. /// Gets the length of the estimated content.
  267. /// </summary>
  268. /// <param name="state">The state.</param>
  269. /// <returns>System.Nullable{System.Int64}.</returns>
  270. private long? GetEstimatedContentLength(StreamState state)
  271. {
  272. var totalBitrate = state.TotalOutputBitrate ?? 0;
  273. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  274. {
  275. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds);
  276. }
  277. return null;
  278. }
  279. }
  280. }