BaseProgressiveStreamingService.cs 13 KB

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