BaseProgressiveStreamingService.cs 15 KB

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