BaseProgressiveStreamingService.cs 17 KB

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