BaseProgressiveStreamingService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. // Static remote stream
  110. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  111. {
  112. AddDlnaHeaders(state, responseHeaders, true);
  113. using (state)
  114. {
  115. if (state.MediaPath.IndexOf("/livestreamfiles/", StringComparison.OrdinalIgnoreCase) != -1)
  116. {
  117. var parts = state.MediaPath.Split('/');
  118. var filename = parts[parts.Length - 2] + Path.GetExtension(parts[parts.Length - 1]);
  119. var filePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, filename);
  120. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  121. outputHeaders["Content-Type"] = MimeTypes.GetMimeType(filePath);
  122. var streamSource = new ProgressiveFileCopier(FileSystem, filePath, outputHeaders, null, Logger, CancellationToken.None)
  123. {
  124. AllowEndOfFile = false
  125. };
  126. return ResultFactory.GetAsyncStreamWriter(streamSource);
  127. }
  128. return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource)
  129. .ConfigureAwait(false);
  130. }
  131. }
  132. if (request.Static && state.InputProtocol != MediaProtocol.File)
  133. {
  134. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  135. }
  136. var outputPath = state.OutputFilePath;
  137. var outputPathExists = FileSystem.FileExists(outputPath);
  138. var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
  139. var isTranscodeCached = outputPathExists && transcodingJob != null;
  140. AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
  141. // Static stream
  142. if (request.Static)
  143. {
  144. var contentType = state.GetMimeType(state.MediaPath);
  145. using (state)
  146. {
  147. TimeSpan? cacheDuration = null;
  148. if (!string.IsNullOrEmpty(request.Tag))
  149. {
  150. cacheDuration = TimeSpan.FromDays(365);
  151. }
  152. return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  153. {
  154. ResponseHeaders = responseHeaders,
  155. ContentType = contentType,
  156. IsHeadRequest = isHeadRequest,
  157. Path = state.MediaPath,
  158. CacheDuration = cacheDuration
  159. }).ConfigureAwait(false);
  160. }
  161. }
  162. //// Not static but transcode cache file exists
  163. //if (isTranscodeCached && state.VideoRequest == null)
  164. //{
  165. // var contentType = state.GetMimeType(outputPath);
  166. // try
  167. // {
  168. // if (transcodingJob != null)
  169. // {
  170. // ApiEntryPoint.Instance.OnTranscodeBeginRequest(transcodingJob);
  171. // }
  172. // return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  173. // {
  174. // ResponseHeaders = responseHeaders,
  175. // ContentType = contentType,
  176. // IsHeadRequest = isHeadRequest,
  177. // Path = outputPath,
  178. // FileShare = FileShare.ReadWrite,
  179. // OnComplete = () =>
  180. // {
  181. // if (transcodingJob != null)
  182. // {
  183. // ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  184. // }
  185. // }
  186. // }).ConfigureAwait(false);
  187. // }
  188. // finally
  189. // {
  190. // state.Dispose();
  191. // }
  192. //}
  193. // Need to start ffmpeg
  194. try
  195. {
  196. return await GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).ConfigureAwait(false);
  197. }
  198. catch
  199. {
  200. state.Dispose();
  201. throw;
  202. }
  203. }
  204. /// <summary>
  205. /// Gets the static remote stream result.
  206. /// </summary>
  207. /// <param name="state">The state.</param>
  208. /// <param name="responseHeaders">The response headers.</param>
  209. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  210. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  211. /// <returns>Task{System.Object}.</returns>
  212. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  213. {
  214. string useragent = null;
  215. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  216. var trySupportSeek = false;
  217. var options = new HttpRequestOptions
  218. {
  219. Url = state.MediaPath,
  220. UserAgent = useragent,
  221. BufferContent = false,
  222. CancellationToken = cancellationTokenSource.Token
  223. };
  224. if (trySupportSeek)
  225. {
  226. if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
  227. {
  228. options.RequestHeaders["Range"] = Request.QueryString["Range"];
  229. }
  230. }
  231. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  232. if (trySupportSeek)
  233. {
  234. foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
  235. {
  236. var val = response.Headers[name];
  237. if (!string.IsNullOrWhiteSpace(val))
  238. {
  239. responseHeaders[name] = val;
  240. }
  241. }
  242. }
  243. else
  244. {
  245. responseHeaders["Accept-Ranges"] = "none";
  246. }
  247. if (response.ContentLength.HasValue)
  248. {
  249. responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
  250. }
  251. if (isHeadRequest)
  252. {
  253. using (response)
  254. {
  255. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  256. }
  257. }
  258. var result = new StaticRemoteStreamWriter(response);
  259. result.Options["Content-Type"] = response.ContentType;
  260. // Add the response headers to the result object
  261. foreach (var header in responseHeaders)
  262. {
  263. result.Options[header.Key] = header.Value;
  264. }
  265. return result;
  266. }
  267. /// <summary>
  268. /// Gets the stream result.
  269. /// </summary>
  270. /// <param name="state">The state.</param>
  271. /// <param name="responseHeaders">The response headers.</param>
  272. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  273. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  274. /// <returns>Task{System.Object}.</returns>
  275. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  276. {
  277. // Use the command line args with a dummy playlist path
  278. var outputPath = state.OutputFilePath;
  279. responseHeaders["Accept-Ranges"] = "none";
  280. var contentType = state.GetMimeType(outputPath);
  281. // TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
  282. // What we really want to do is hunt that down and remove that
  283. var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
  284. if (contentLength.HasValue)
  285. {
  286. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  287. }
  288. // Headers only
  289. if (isHeadRequest)
  290. {
  291. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  292. var hasOptions = streamResult as IHasOptions;
  293. if (hasOptions != null)
  294. {
  295. if (contentLength.HasValue)
  296. {
  297. hasOptions.Options["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
  298. }
  299. else
  300. {
  301. if (hasOptions.Options.ContainsKey("Content-Length"))
  302. {
  303. hasOptions.Options.Remove("Content-Length");
  304. }
  305. }
  306. }
  307. return streamResult;
  308. }
  309. var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(outputPath);
  310. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  311. try
  312. {
  313. TranscodingJob job;
  314. if (!FileSystem.FileExists(outputPath))
  315. {
  316. job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  317. }
  318. else
  319. {
  320. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  321. state.Dispose();
  322. }
  323. var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  324. outputHeaders["Content-Type"] = contentType;
  325. // Add the response headers to the result object
  326. foreach (var item in responseHeaders)
  327. {
  328. outputHeaders[item.Key] = item.Value;
  329. }
  330. var streamSource = new ProgressiveFileCopier(FileSystem, outputPath, outputHeaders, job, Logger, CancellationToken.None);
  331. return ResultFactory.GetAsyncStreamWriter(streamSource);
  332. }
  333. finally
  334. {
  335. transcodingLock.Release();
  336. }
  337. }
  338. /// <summary>
  339. /// Gets the length of the estimated content.
  340. /// </summary>
  341. /// <param name="state">The state.</param>
  342. /// <returns>System.Nullable{System.Int64}.</returns>
  343. private long? GetEstimatedContentLength(StreamState state)
  344. {
  345. var totalBitrate = state.TotalOutputBitrate ?? 0;
  346. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  347. {
  348. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds / 8);
  349. }
  350. return null;
  351. }
  352. }
  353. }