BaseProgressiveStreamingService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 System;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using MediaBrowser.Model.Services;
  19. using MediaBrowser.Model.System;
  20. using Microsoft.Extensions.Logging;
  21. using MediaBrowser.Api.LiveTv;
  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 IEnvironmentInfo EnvironmentInfo;
  31. public 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, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, IEnvironmentInfo environmentInfo) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext)
  32. {
  33. ImageProcessor = imageProcessor;
  34. EnvironmentInfo = environmentInfo;
  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 async Task<object> ProcessRequest(StreamRequest request, bool isHeadRequest)
  108. {
  109. var cancellationTokenSource = new CancellationTokenSource();
  110. var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
  111. var responseHeaders = new Dictionary<string, string>();
  112. if (request.Static && state.DirectStreamProvider != null)
  113. {
  114. AddDlnaHeaders(state, responseHeaders, true);
  115. using (state)
  116. {
  117. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  118. // TODO: Don't hardcode this
  119. outputHeaders["Content-Type"] = MediaBrowser.Model.Net.MimeTypes.GetMimeType("file.ts");
  120. return new ProgressiveFileCopier(state.DirectStreamProvider, outputHeaders, null, Logger, EnvironmentInfo, CancellationToken.None)
  121. {
  122. AllowEndOfFile = false
  123. };
  124. }
  125. }
  126. // Static remote stream
  127. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  128. {
  129. AddDlnaHeaders(state, responseHeaders, true);
  130. using (state)
  131. {
  132. return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  133. }
  134. }
  135. if (request.Static && state.InputProtocol != MediaProtocol.File)
  136. {
  137. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  138. }
  139. var outputPath = state.OutputFilePath;
  140. var outputPathExists = FileSystem.FileExists(outputPath);
  141. var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
  142. var isTranscodeCached = outputPathExists && transcodingJob != null;
  143. AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
  144. // Static stream
  145. if (request.Static)
  146. {
  147. var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
  148. using (state)
  149. {
  150. if (state.MediaSource.IsInfiniteStream)
  151. {
  152. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  153. outputHeaders["Content-Type"] = contentType;
  154. return new ProgressiveFileCopier(FileSystem, state.MediaPath, outputHeaders, null, Logger, EnvironmentInfo, CancellationToken.None)
  155. {
  156. AllowEndOfFile = false
  157. };
  158. }
  159. TimeSpan? cacheDuration = null;
  160. if (!string.IsNullOrEmpty(request.Tag))
  161. {
  162. cacheDuration = TimeSpan.FromDays(365);
  163. }
  164. return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  165. {
  166. ResponseHeaders = responseHeaders,
  167. ContentType = contentType,
  168. IsHeadRequest = isHeadRequest,
  169. Path = state.MediaPath,
  170. CacheDuration = cacheDuration
  171. }).ConfigureAwait(false);
  172. }
  173. }
  174. //// Not static but transcode cache file exists
  175. //if (isTranscodeCached && state.VideoRequest == null)
  176. //{
  177. // var contentType = state.GetMimeType(outputPath);
  178. // try
  179. // {
  180. // if (transcodingJob != null)
  181. // {
  182. // ApiEntryPoint.Instance.OnTranscodeBeginRequest(transcodingJob);
  183. // }
  184. // return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  185. // {
  186. // ResponseHeaders = responseHeaders,
  187. // ContentType = contentType,
  188. // IsHeadRequest = isHeadRequest,
  189. // Path = outputPath,
  190. // FileShare = FileShareMode.ReadWrite,
  191. // OnComplete = () =>
  192. // {
  193. // if (transcodingJob != null)
  194. // {
  195. // ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  196. // }
  197. // }
  198. // }).ConfigureAwait(false);
  199. // }
  200. // finally
  201. // {
  202. // state.Dispose();
  203. // }
  204. //}
  205. // Need to start ffmpeg
  206. try
  207. {
  208. return await GetStreamResult(request, state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  209. }
  210. catch
  211. {
  212. state.Dispose();
  213. throw;
  214. }
  215. }
  216. /// <summary>
  217. /// Gets the static remote stream result.
  218. /// </summary>
  219. /// <param name="state">The state.</param>
  220. /// <param name="responseHeaders">The response headers.</param>
  221. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  222. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  223. /// <returns>Task{System.Object}.</returns>
  224. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  225. {
  226. string useragent = null;
  227. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  228. var trySupportSeek = false;
  229. var options = new HttpRequestOptions
  230. {
  231. Url = state.MediaPath,
  232. UserAgent = useragent,
  233. BufferContent = false,
  234. CancellationToken = cancellationTokenSource.Token
  235. };
  236. if (trySupportSeek)
  237. {
  238. if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
  239. {
  240. options.RequestHeaders["Range"] = Request.QueryString["Range"];
  241. }
  242. }
  243. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  244. if (trySupportSeek)
  245. {
  246. foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
  247. {
  248. var val = response.Headers[name];
  249. if (!string.IsNullOrWhiteSpace(val))
  250. {
  251. responseHeaders[name] = val;
  252. }
  253. }
  254. }
  255. else
  256. {
  257. responseHeaders["Accept-Ranges"] = "none";
  258. }
  259. // Seeing cases of -1 here
  260. if (response.ContentLength.HasValue && response.ContentLength.Value >= 0)
  261. {
  262. responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
  263. }
  264. if (isHeadRequest)
  265. {
  266. using (response)
  267. {
  268. return ResultFactory.GetResult(null, new byte[] { }, response.ContentType, responseHeaders);
  269. }
  270. }
  271. var result = new StaticRemoteStreamWriter(response);
  272. result.Headers["Content-Type"] = response.ContentType;
  273. // Add the response headers to the result object
  274. foreach (var header in responseHeaders)
  275. {
  276. result.Headers[header.Key] = header.Value;
  277. }
  278. return result;
  279. }
  280. /// <summary>
  281. /// Gets the stream result.
  282. /// </summary>
  283. /// <param name="state">The state.</param>
  284. /// <param name="responseHeaders">The response headers.</param>
  285. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  286. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  287. /// <returns>Task{System.Object}.</returns>
  288. private async Task<object> GetStreamResult(StreamRequest request, StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  289. {
  290. // Use the command line args with a dummy playlist path
  291. var outputPath = state.OutputFilePath;
  292. responseHeaders["Accept-Ranges"] = "none";
  293. var contentType = state.GetMimeType(outputPath);
  294. // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
  295. // What we really want to do is hunt that down and remove that
  296. var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
  297. if (contentLength.HasValue)
  298. {
  299. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  300. }
  301. // Headers only
  302. if (isHeadRequest)
  303. {
  304. var streamResult = ResultFactory.GetResult(null, new byte[] { }, contentType, responseHeaders);
  305. var hasHeaders = streamResult as IHasHeaders;
  306. if (hasHeaders != null)
  307. {
  308. if (contentLength.HasValue)
  309. {
  310. hasHeaders.Headers["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  311. }
  312. else
  313. {
  314. if (hasHeaders.Headers.ContainsKey("Content-Length"))
  315. {
  316. hasHeaders.Headers.Remove("Content-Length");
  317. }
  318. }
  319. }
  320. return streamResult;
  321. }
  322. var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(outputPath);
  323. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  324. try
  325. {
  326. TranscodingJob job;
  327. if (!FileSystem.FileExists(outputPath))
  328. {
  329. job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  330. }
  331. else
  332. {
  333. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  334. state.Dispose();
  335. }
  336. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  337. outputHeaders["Content-Type"] = contentType;
  338. // Add the response headers to the result object
  339. foreach (var item in responseHeaders)
  340. {
  341. outputHeaders[item.Key] = item.Value;
  342. }
  343. return new ProgressiveFileCopier(FileSystem, outputPath, outputHeaders, job, Logger, EnvironmentInfo, CancellationToken.None);
  344. }
  345. finally
  346. {
  347. transcodingLock.Release();
  348. }
  349. }
  350. /// <summary>
  351. /// Gets the length of the estimated content.
  352. /// </summary>
  353. /// <param name="state">The state.</param>
  354. /// <returns>System.Nullable{System.Int64}.</returns>
  355. private long? GetEstimatedContentLength(StreamState state)
  356. {
  357. var totalBitrate = state.TotalOutputBitrate ?? 0;
  358. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  359. {
  360. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds / 8);
  361. }
  362. return null;
  363. }
  364. }
  365. }