BaseProgressiveStreamingService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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(
  245. StreamState state,
  246. Dictionary<string, string> responseHeaders,
  247. bool isHeadRequest,
  248. CancellationTokenSource cancellationTokenSource)
  249. {
  250. var options = new HttpRequestOptions
  251. {
  252. Url = state.MediaPath,
  253. BufferContent = false,
  254. CancellationToken = cancellationTokenSource.Token
  255. };
  256. if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent))
  257. {
  258. options.UserAgent = useragent;
  259. }
  260. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  261. responseHeaders[HeaderNames.AcceptRanges] = "none";
  262. // Seeing cases of -1 here
  263. if (response.ContentLength.HasValue && response.ContentLength.Value >= 0)
  264. {
  265. responseHeaders[HeaderNames.ContentLength] = response.ContentLength.Value.ToString(CultureInfo.InvariantCulture);
  266. }
  267. if (isHeadRequest)
  268. {
  269. using (response)
  270. {
  271. return ResultFactory.GetResult(null, Array.Empty<byte>(), response.ContentType, responseHeaders);
  272. }
  273. }
  274. var result = new StaticRemoteStreamWriter(response);
  275. result.Headers[HeaderNames.ContentType] = response.ContentType;
  276. // Add the response headers to the result object
  277. foreach (var header in responseHeaders)
  278. {
  279. result.Headers[header.Key] = header.Value;
  280. }
  281. return result;
  282. }
  283. /// <summary>
  284. /// Gets the stream result.
  285. /// </summary>
  286. /// <param name="state">The state.</param>
  287. /// <param name="responseHeaders">The response headers.</param>
  288. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  289. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  290. /// <returns>Task{System.Object}.</returns>
  291. private async Task<object> GetStreamResult(StreamRequest request, StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  292. {
  293. // Use the command line args with a dummy playlist path
  294. var outputPath = state.OutputFilePath;
  295. responseHeaders[HeaderNames.AcceptRanges] = "none";
  296. var contentType = state.GetMimeType(outputPath);
  297. // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
  298. var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
  299. if (contentLength.HasValue)
  300. {
  301. responseHeaders[HeaderNames.ContentLength] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  302. }
  303. // Headers only
  304. if (isHeadRequest)
  305. {
  306. var streamResult = ResultFactory.GetResult(null, Array.Empty<byte>(), contentType, responseHeaders);
  307. if (streamResult is IHasHeaders hasHeaders)
  308. {
  309. if (contentLength.HasValue)
  310. {
  311. hasHeaders.Headers[HeaderNames.ContentLength] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  312. }
  313. else
  314. {
  315. hasHeaders.Headers.Remove(HeaderNames.ContentLength);
  316. }
  317. }
  318. return streamResult;
  319. }
  320. var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(outputPath);
  321. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  322. try
  323. {
  324. TranscodingJob job;
  325. if (!File.Exists(outputPath))
  326. {
  327. job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  328. }
  329. else
  330. {
  331. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  332. state.Dispose();
  333. }
  334. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  335. {
  336. [HeaderNames.ContentType] = contentType
  337. };
  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, 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. }