BaseProgressiveStreamingService.cs 16 KB

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