BaseProgressiveStreamingService.cs 13 KB

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