BaseProgressiveStreamingService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 ServiceStack.Web;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using CommonIO;
  20. using ServiceStack;
  21. namespace MediaBrowser.Api.Playback.Progressive
  22. {
  23. /// <summary>
  24. /// Class BaseProgressiveStreamingService
  25. /// </summary>
  26. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  27. {
  28. protected readonly IImageProcessor ImageProcessor;
  29. protected 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, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
  30. {
  31. ImageProcessor = imageProcessor;
  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
  95. {
  96. get { return TranscodingJobType.Progressive; }
  97. }
  98. /// <summary>
  99. /// Processes the request.
  100. /// </summary>
  101. /// <param name="request">The request.</param>
  102. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  103. /// <returns>Task.</returns>
  104. protected async Task<object> ProcessRequest(StreamRequest request, bool isHeadRequest)
  105. {
  106. var cancellationTokenSource = new CancellationTokenSource();
  107. var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
  108. var responseHeaders = new Dictionary<string, string>();
  109. if (request.Static && state.DirectStreamProvider != null)
  110. {
  111. AddDlnaHeaders(state, responseHeaders, true);
  112. using (state)
  113. {
  114. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  115. // TODO: Don't hardcode this
  116. outputHeaders["Content-Type"] = MediaBrowser.Model.Net.MimeTypes.GetMimeType("file.ts");
  117. var streamSource = new ProgressiveFileCopier(state.DirectStreamProvider, outputHeaders, null, Logger, CancellationToken.None)
  118. {
  119. AllowEndOfFile = false
  120. };
  121. return ResultFactory.GetAsyncStreamWriter(streamSource);
  122. }
  123. }
  124. // Static remote stream
  125. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  126. {
  127. AddDlnaHeaders(state, responseHeaders, true);
  128. using (state)
  129. {
  130. return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  131. }
  132. }
  133. if (request.Static && state.InputProtocol != MediaProtocol.File)
  134. {
  135. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  136. }
  137. var outputPath = state.OutputFilePath;
  138. var outputPathExists = FileSystem.FileExists(outputPath);
  139. var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
  140. var isTranscodeCached = outputPathExists && transcodingJob != null;
  141. AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
  142. // Static stream
  143. if (request.Static)
  144. {
  145. var contentType = state.GetMimeType(state.MediaPath);
  146. using (state)
  147. {
  148. if (state.MediaSource.IsInfiniteStream)
  149. {
  150. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  151. outputHeaders["Content-Type"] = contentType;
  152. var streamSource = new ProgressiveFileCopier(FileSystem, state.MediaPath, outputHeaders, null, Logger, CancellationToken.None)
  153. {
  154. AllowEndOfFile = false
  155. };
  156. return ResultFactory.GetAsyncStreamWriter(streamSource);
  157. }
  158. TimeSpan? cacheDuration = null;
  159. if (!string.IsNullOrEmpty(request.Tag))
  160. {
  161. cacheDuration = TimeSpan.FromDays(365);
  162. }
  163. return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  164. {
  165. ResponseHeaders = responseHeaders,
  166. ContentType = contentType,
  167. IsHeadRequest = isHeadRequest,
  168. Path = state.MediaPath,
  169. CacheDuration = cacheDuration
  170. }).ConfigureAwait(false);
  171. }
  172. }
  173. //// Not static but transcode cache file exists
  174. //if (isTranscodeCached && state.VideoRequest == null)
  175. //{
  176. // var contentType = state.GetMimeType(outputPath);
  177. // try
  178. // {
  179. // if (transcodingJob != null)
  180. // {
  181. // ApiEntryPoint.Instance.OnTranscodeBeginRequest(transcodingJob);
  182. // }
  183. // return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  184. // {
  185. // ResponseHeaders = responseHeaders,
  186. // ContentType = contentType,
  187. // IsHeadRequest = isHeadRequest,
  188. // Path = outputPath,
  189. // FileShare = FileShare.ReadWrite,
  190. // OnComplete = () =>
  191. // {
  192. // if (transcodingJob != null)
  193. // {
  194. // ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  195. // }
  196. // }
  197. // }).ConfigureAwait(false);
  198. // }
  199. // finally
  200. // {
  201. // state.Dispose();
  202. // }
  203. //}
  204. // Need to start ffmpeg
  205. try
  206. {
  207. return await GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  208. }
  209. catch
  210. {
  211. state.Dispose();
  212. throw;
  213. }
  214. }
  215. /// <summary>
  216. /// Gets the static remote stream result.
  217. /// </summary>
  218. /// <param name="state">The state.</param>
  219. /// <param name="responseHeaders">The response headers.</param>
  220. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  221. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  222. /// <returns>Task{System.Object}.</returns>
  223. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  224. {
  225. string useragent = null;
  226. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  227. var trySupportSeek = false;
  228. var options = new HttpRequestOptions
  229. {
  230. Url = state.MediaPath,
  231. UserAgent = useragent,
  232. BufferContent = false,
  233. CancellationToken = cancellationTokenSource.Token
  234. };
  235. if (trySupportSeek)
  236. {
  237. if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
  238. {
  239. options.RequestHeaders["Range"] = Request.QueryString["Range"];
  240. }
  241. }
  242. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  243. if (trySupportSeek)
  244. {
  245. foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
  246. {
  247. var val = response.Headers[name];
  248. if (!string.IsNullOrWhiteSpace(val))
  249. {
  250. responseHeaders[name] = val;
  251. }
  252. }
  253. }
  254. else
  255. {
  256. responseHeaders["Accept-Ranges"] = "none";
  257. }
  258. if (response.ContentLength.HasValue)
  259. {
  260. responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
  261. }
  262. if (isHeadRequest)
  263. {
  264. using (response)
  265. {
  266. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  267. }
  268. }
  269. var result = new StaticRemoteStreamWriter(response);
  270. result.Options["Content-Type"] = response.ContentType;
  271. // Add the response headers to the result object
  272. foreach (var header in responseHeaders)
  273. {
  274. result.Options[header.Key] = header.Value;
  275. }
  276. return result;
  277. }
  278. /// <summary>
  279. /// Gets the stream result.
  280. /// </summary>
  281. /// <param name="state">The state.</param>
  282. /// <param name="responseHeaders">The response headers.</param>
  283. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  284. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  285. /// <returns>Task{System.Object}.</returns>
  286. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  287. {
  288. // Use the command line args with a dummy playlist path
  289. var outputPath = state.OutputFilePath;
  290. responseHeaders["Accept-Ranges"] = "none";
  291. var contentType = state.GetMimeType(outputPath);
  292. // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
  293. // What we really want to do is hunt that down and remove that
  294. var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
  295. if (contentLength.HasValue)
  296. {
  297. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  298. }
  299. // Headers only
  300. if (isHeadRequest)
  301. {
  302. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  303. var hasOptions = streamResult as IHasOptions;
  304. if (hasOptions != null)
  305. {
  306. if (contentLength.HasValue)
  307. {
  308. hasOptions.Options["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  309. }
  310. else
  311. {
  312. if (hasOptions.Options.ContainsKey("Content-Length"))
  313. {
  314. hasOptions.Options.Remove("Content-Length");
  315. }
  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 (!FileSystem.FileExists(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. outputHeaders["Content-Type"] = contentType;
  336. // Add the response headers to the result object
  337. foreach (var item in responseHeaders)
  338. {
  339. outputHeaders[item.Key] = item.Value;
  340. }
  341. var streamSource = new ProgressiveFileCopier(FileSystem, outputPath, outputHeaders, job, Logger, CancellationToken.None);
  342. return ResultFactory.GetAsyncStreamWriter(streamSource);
  343. }
  344. finally
  345. {
  346. transcodingLock.Release();
  347. }
  348. }
  349. /// <summary>
  350. /// Gets the length of the estimated content.
  351. /// </summary>
  352. /// <param name="state">The state.</param>
  353. /// <returns>System.Nullable{System.Int64}.</returns>
  354. private long? GetEstimatedContentLength(StreamState state)
  355. {
  356. var totalBitrate = state.TotalOutputBitrate ?? 0;
  357. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  358. {
  359. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds / 8);
  360. }
  361. return null;
  362. }
  363. }
  364. }