BaseProgressiveStreamingService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.MediaInfo;
  11. using MediaBrowser.Model.Serialization;
  12. using ServiceStack.Web;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using CommonIO;
  20. namespace MediaBrowser.Api.Playback.Progressive
  21. {
  22. /// <summary>
  23. /// Class BaseProgressiveStreamingService
  24. /// </summary>
  25. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  26. {
  27. protected readonly IImageProcessor ImageProcessor;
  28. protected readonly IHttpClient HttpClient;
  29. protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
  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 async Task<object> ProcessRequest(StreamRequest request, bool isHeadRequest)
  106. {
  107. var cancellationTokenSource = new CancellationTokenSource();
  108. var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
  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 await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource)
  117. .ConfigureAwait(false);
  118. }
  119. }
  120. if (request.Static && state.InputProtocol != MediaProtocol.File)
  121. {
  122. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  123. }
  124. var outputPath = state.OutputFilePath;
  125. var outputPathExists = FileSystem.FileExists(outputPath);
  126. var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
  127. var isTranscodeCached = outputPathExists && transcodingJob != null;
  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. TimeSpan? cacheDuration = null;
  136. if (!string.IsNullOrEmpty(request.Tag))
  137. {
  138. cacheDuration = TimeSpan.FromDays(365);
  139. }
  140. return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  141. {
  142. ResponseHeaders = responseHeaders,
  143. ContentType = contentType,
  144. IsHeadRequest = isHeadRequest,
  145. Path = state.MediaPath,
  146. CacheDuration = cacheDuration
  147. }).ConfigureAwait(false);
  148. }
  149. }
  150. //// Not static but transcode cache file exists
  151. //if (isTranscodeCached && state.VideoRequest == null)
  152. //{
  153. // var contentType = state.GetMimeType(outputPath);
  154. // try
  155. // {
  156. // if (transcodingJob != null)
  157. // {
  158. // ApiEntryPoint.Instance.OnTranscodeBeginRequest(transcodingJob);
  159. // }
  160. // return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  161. // {
  162. // ResponseHeaders = responseHeaders,
  163. // ContentType = contentType,
  164. // IsHeadRequest = isHeadRequest,
  165. // Path = outputPath,
  166. // FileShare = FileShare.ReadWrite,
  167. // OnComplete = () =>
  168. // {
  169. // if (transcodingJob != null)
  170. // {
  171. // ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  172. // }
  173. // }
  174. // }).ConfigureAwait(false);
  175. // }
  176. // finally
  177. // {
  178. // state.Dispose();
  179. // }
  180. //}
  181. // Need to start ffmpeg
  182. try
  183. {
  184. return await GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  185. }
  186. catch
  187. {
  188. state.Dispose();
  189. throw;
  190. }
  191. }
  192. /// <summary>
  193. /// Gets the static remote stream result.
  194. /// </summary>
  195. /// <param name="state">The state.</param>
  196. /// <param name="responseHeaders">The response headers.</param>
  197. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  198. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  199. /// <returns>Task{System.Object}.</returns>
  200. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  201. {
  202. string useragent = null;
  203. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  204. var trySupportSeek = false;
  205. var options = new HttpRequestOptions
  206. {
  207. Url = state.MediaPath,
  208. UserAgent = useragent,
  209. BufferContent = false,
  210. CancellationToken = cancellationTokenSource.Token
  211. };
  212. if (trySupportSeek)
  213. {
  214. if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
  215. {
  216. options.RequestHeaders["Range"] = Request.QueryString["Range"];
  217. }
  218. }
  219. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  220. if (trySupportSeek)
  221. {
  222. foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
  223. {
  224. var val = response.Headers[name];
  225. if (!string.IsNullOrWhiteSpace(val))
  226. {
  227. responseHeaders[name] = val;
  228. }
  229. }
  230. }
  231. else
  232. {
  233. responseHeaders["Accept-Ranges"] = "none";
  234. }
  235. if (response.ContentLength.HasValue)
  236. {
  237. responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
  238. }
  239. if (isHeadRequest)
  240. {
  241. using (response)
  242. {
  243. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  244. }
  245. }
  246. var result = new StaticRemoteStreamWriter(response);
  247. result.Options["Content-Type"] = response.ContentType;
  248. // Add the response headers to the result object
  249. foreach (var header in responseHeaders)
  250. {
  251. result.Options[header.Key] = header.Value;
  252. }
  253. return result;
  254. }
  255. /// <summary>
  256. /// Gets the stream result.
  257. /// </summary>
  258. /// <param name="state">The state.</param>
  259. /// <param name="responseHeaders">The response headers.</param>
  260. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  261. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  262. /// <returns>Task{System.Object}.</returns>
  263. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  264. {
  265. // Use the command line args with a dummy playlist path
  266. var outputPath = state.OutputFilePath;
  267. responseHeaders["Accept-Ranges"] = "none";
  268. var contentType = state.GetMimeType(outputPath);
  269. // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
  270. // What we really want to do is hunt that down and remove that
  271. var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
  272. if (contentLength.HasValue)
  273. {
  274. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  275. }
  276. // Headers only
  277. if (isHeadRequest)
  278. {
  279. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  280. var hasOptions = streamResult as IHasOptions;
  281. if (hasOptions != null)
  282. {
  283. if (contentLength.HasValue)
  284. {
  285. hasOptions.Options["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  286. }
  287. else
  288. {
  289. if (hasOptions.Options.ContainsKey("Content-Length"))
  290. {
  291. hasOptions.Options.Remove("Content-Length");
  292. }
  293. }
  294. }
  295. return streamResult;
  296. }
  297. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  298. try
  299. {
  300. TranscodingJob job;
  301. if (!FileSystem.FileExists(outputPath))
  302. {
  303. job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  304. }
  305. else
  306. {
  307. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  308. state.Dispose();
  309. }
  310. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  311. outputHeaders["Content-Type"] = contentType;
  312. // Add the response headers to the result object
  313. foreach (var item in responseHeaders)
  314. {
  315. outputHeaders[item.Key] = item.Value;
  316. }
  317. var streamSource = new ProgressiveFileCopier(FileSystem, outputPath, outputHeaders, job, Logger, CancellationToken.None);
  318. return ResultFactory.GetAsyncStreamWriter(streamSource);
  319. }
  320. finally
  321. {
  322. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  323. }
  324. }
  325. /// <summary>
  326. /// Gets the length of the estimated content.
  327. /// </summary>
  328. /// <param name="state">The state.</param>
  329. /// <returns>System.Nullable{System.Int64}.</returns>
  330. private long? GetEstimatedContentLength(StreamState state)
  331. {
  332. var totalBitrate = state.TotalOutputBitrate ?? 0;
  333. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  334. {
  335. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds / 8);
  336. }
  337. return null;
  338. }
  339. }
  340. }