BaseProgressiveStreamingService.cs 16 KB

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