BaseProgressiveStreamingService.cs 16 KB

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