BaseProgressiveStreamingService.cs 16 KB

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