BaseProgressiveStreamingService.cs 16 KB

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