BaseProgressiveStreamingService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Devices;
  6. using MediaBrowser.Controller.Dlna;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Net;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.MediaInfo;
  14. using ServiceStack.Web;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  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 readonly IHttpClient HttpClient;
  30. protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder, deviceManager)
  31. {
  32. ImageProcessor = imageProcessor;
  33. HttpClient = httpClient;
  34. }
  35. /// <summary>
  36. /// Gets the output file extension.
  37. /// </summary>
  38. /// <param name="state">The state.</param>
  39. /// <returns>System.String.</returns>
  40. protected override string GetOutputFileExtension(StreamState state)
  41. {
  42. var ext = base.GetOutputFileExtension(state);
  43. if (!string.IsNullOrEmpty(ext))
  44. {
  45. return ext;
  46. }
  47. var isVideoRequest = state.VideoRequest != null;
  48. // Try to infer based on the desired video codec
  49. if (isVideoRequest)
  50. {
  51. var videoCodec = state.VideoRequest.VideoCodec;
  52. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  53. {
  54. return ".ts";
  55. }
  56. if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
  57. {
  58. return ".ogv";
  59. }
  60. if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
  61. {
  62. return ".webm";
  63. }
  64. if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
  65. {
  66. return ".asf";
  67. }
  68. }
  69. // Try to infer based on the desired audio codec
  70. if (!isVideoRequest)
  71. {
  72. var audioCodec = state.Request.AudioCodec;
  73. if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
  74. {
  75. return ".aac";
  76. }
  77. if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
  78. {
  79. return ".mp3";
  80. }
  81. if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
  82. {
  83. return ".ogg";
  84. }
  85. if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
  86. {
  87. return ".wma";
  88. }
  89. }
  90. return null;
  91. }
  92. /// <summary>
  93. /// Gets the type of the transcoding job.
  94. /// </summary>
  95. /// <value>The type of the transcoding job.</value>
  96. protected override TranscodingJobType TranscodingJobType
  97. {
  98. get { return TranscodingJobType.Progressive; }
  99. }
  100. /// <summary>
  101. /// Processes the request.
  102. /// </summary>
  103. /// <param name="request">The request.</param>
  104. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  105. /// <returns>Task.</returns>
  106. protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
  107. {
  108. var cancellationTokenSource = new CancellationTokenSource();
  109. var state = GetState(request, cancellationTokenSource.Token).Result;
  110. var responseHeaders = new Dictionary<string, string>();
  111. // Static remote stream
  112. if (request.Static && state.InputProtocol == MediaProtocol.Http)
  113. {
  114. AddDlnaHeaders(state, responseHeaders, true);
  115. using (state)
  116. {
  117. return GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).Result;
  118. }
  119. }
  120. if (request.Static && state.InputProtocol != MediaProtocol.File)
  121. {
  122. throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
  123. }
  124. var outputPath = state.OutputFilePath;
  125. var outputPathExists = File.Exists(outputPath);
  126. var isTranscodeCached = outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive);
  127. AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
  128. // Static stream
  129. if (request.Static)
  130. {
  131. var contentType = state.GetMimeType(state.MediaPath);
  132. using (state)
  133. {
  134. var job = string.IsNullOrEmpty(request.TranscodingJobId) ?
  135. null :
  136. ApiEntryPoint.Instance.GetTranscodingJob(request.TranscodingJobId);
  137. var limits = new List<long>();
  138. if (state.InputBitrate.HasValue)
  139. {
  140. // Bytes per second
  141. limits.Add((state.InputBitrate.Value / 8));
  142. }
  143. if (state.InputFileSize.HasValue && state.RunTimeTicks.HasValue)
  144. {
  145. var totalSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds;
  146. if (totalSeconds > 1)
  147. {
  148. var timeBasedLimit = state.InputFileSize.Value / totalSeconds;
  149. limits.Add(Convert.ToInt64(timeBasedLimit));
  150. }
  151. }
  152. // Take the greater of the above to methods, just to be safe
  153. var throttleLimit = limits.Count > 0 ? limits.First() : 0;
  154. // Pad to play it safe
  155. var bytesPerSecond = Convert.ToInt64(1.05 * throttleLimit);
  156. // Don't even start evaluating this until at least two minutes have content have been consumed
  157. var targetGap = throttleLimit * 120;
  158. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  159. {
  160. ResponseHeaders = responseHeaders,
  161. ContentType = contentType,
  162. IsHeadRequest = isHeadRequest,
  163. Path = state.MediaPath,
  164. Throttle = request.Throttle,
  165. ThrottleLimit = bytesPerSecond,
  166. MinThrottlePosition = targetGap,
  167. ThrottleCallback = (l1, l2) => ThrottleCallack(l1, l2, bytesPerSecond, job)
  168. });
  169. }
  170. }
  171. // Not static but transcode cache file exists
  172. if (isTranscodeCached)
  173. {
  174. var contentType = state.GetMimeType(outputPath);
  175. try
  176. {
  177. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  178. {
  179. ResponseHeaders = responseHeaders,
  180. ContentType = contentType,
  181. IsHeadRequest = isHeadRequest,
  182. Path = outputPath
  183. });
  184. }
  185. finally
  186. {
  187. state.Dispose();
  188. }
  189. }
  190. // Need to start ffmpeg
  191. try
  192. {
  193. return GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource).Result;
  194. }
  195. catch
  196. {
  197. state.Dispose();
  198. throw;
  199. }
  200. }
  201. private readonly long _gapLengthInTicks = TimeSpan.FromMinutes(3).Ticks;
  202. private long ThrottleCallack(long currentBytesPerSecond, long bytesWritten, long originalBytesPerSecond, TranscodingJob job)
  203. {
  204. var bytesDownloaded = job.BytesDownloaded ?? 0;
  205. var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
  206. var downloadPositionTicks = job.DownloadPositionTicks ?? 0;
  207. var path = job.Path;
  208. if (bytesDownloaded > 0 && transcodingPositionTicks > 0)
  209. {
  210. // Progressive Streaming - byte-based consideration
  211. try
  212. {
  213. var bytesTranscoded = job.BytesTranscoded ?? new FileInfo(path).Length;
  214. // Estimate the bytes the transcoder should be ahead
  215. double gapFactor = _gapLengthInTicks;
  216. gapFactor /= transcodingPositionTicks;
  217. var targetGap = bytesTranscoded * gapFactor;
  218. var gap = bytesTranscoded - bytesDownloaded;
  219. if (gap < targetGap)
  220. {
  221. //Logger.Debug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  222. return 0;
  223. }
  224. //Logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  225. }
  226. catch
  227. {
  228. //Logger.Error("Error getting output size");
  229. }
  230. }
  231. else if (downloadPositionTicks > 0 && transcodingPositionTicks > 0)
  232. {
  233. // HLS - time-based consideration
  234. var targetGap = _gapLengthInTicks;
  235. var gap = transcodingPositionTicks - downloadPositionTicks;
  236. if (gap < targetGap)
  237. {
  238. //Logger.Debug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
  239. return 0;
  240. }
  241. //Logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
  242. }
  243. else
  244. {
  245. //Logger.Debug("No throttle data for " + path);
  246. }
  247. return originalBytesPerSecond;
  248. }
  249. /// <summary>
  250. /// Gets the static remote stream result.
  251. /// </summary>
  252. /// <param name="state">The state.</param>
  253. /// <param name="responseHeaders">The response headers.</param>
  254. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  255. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  256. /// <returns>Task{System.Object}.</returns>
  257. private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  258. {
  259. string useragent = null;
  260. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  261. var trySupportSeek = false;
  262. var options = new HttpRequestOptions
  263. {
  264. Url = state.MediaPath,
  265. UserAgent = useragent,
  266. BufferContent = false,
  267. CancellationToken = cancellationTokenSource.Token
  268. };
  269. if (trySupportSeek)
  270. {
  271. if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
  272. {
  273. options.RequestHeaders["Range"] = Request.QueryString["Range"];
  274. }
  275. }
  276. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  277. if (trySupportSeek)
  278. {
  279. foreach (var name in new[] {"Content-Range", "Accept-Ranges"})
  280. {
  281. var val = response.Headers[name];
  282. if (!string.IsNullOrWhiteSpace(val))
  283. {
  284. responseHeaders[name] = val;
  285. }
  286. }
  287. }
  288. else
  289. {
  290. responseHeaders["Accept-Ranges"] = "none";
  291. }
  292. if (response.ContentLength.HasValue)
  293. {
  294. responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
  295. }
  296. if (isHeadRequest)
  297. {
  298. using (response)
  299. {
  300. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  301. }
  302. }
  303. var result = new StaticRemoteStreamWriter(response);
  304. result.Options["Content-Type"] = response.ContentType;
  305. // Add the response headers to the result object
  306. foreach (var header in responseHeaders)
  307. {
  308. result.Options[header.Key] = header.Value;
  309. }
  310. return result;
  311. }
  312. /// <summary>
  313. /// Gets the stream result.
  314. /// </summary>
  315. /// <param name="state">The state.</param>
  316. /// <param name="responseHeaders">The response headers.</param>
  317. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  318. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  319. /// <returns>Task{System.Object}.</returns>
  320. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
  321. {
  322. // Use the command line args with a dummy playlist path
  323. var outputPath = state.OutputFilePath;
  324. responseHeaders["Accept-Ranges"] = "none";
  325. var contentType = state.GetMimeType(outputPath);
  326. var contentLength = state.EstimateContentLength ? GetEstimatedContentLength(state) : null;
  327. if (contentLength.HasValue)
  328. {
  329. responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
  330. }
  331. // Headers only
  332. if (isHeadRequest)
  333. {
  334. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  335. if (!contentLength.HasValue)
  336. {
  337. var hasOptions = streamResult as IHasOptions;
  338. if (hasOptions != null)
  339. {
  340. if (hasOptions.Options.ContainsKey("Content-Length"))
  341. {
  342. hasOptions.Options.Remove("Content-Length");
  343. }
  344. }
  345. }
  346. return streamResult;
  347. }
  348. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  349. try
  350. {
  351. TranscodingJob job;
  352. if (!File.Exists(outputPath))
  353. {
  354. job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
  355. }
  356. else
  357. {
  358. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  359. state.Dispose();
  360. }
  361. var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem, job);
  362. result.Options["Content-Type"] = contentType;
  363. // Add the response headers to the result object
  364. foreach (var item in responseHeaders)
  365. {
  366. result.Options[item.Key] = item.Value;
  367. }
  368. return result;
  369. }
  370. finally
  371. {
  372. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  373. }
  374. }
  375. /// <summary>
  376. /// Gets the length of the estimated content.
  377. /// </summary>
  378. /// <param name="state">The state.</param>
  379. /// <returns>System.Nullable{System.Int64}.</returns>
  380. private long? GetEstimatedContentLength(StreamState state)
  381. {
  382. var totalBitrate = state.TotalOutputBitrate ?? 0;
  383. if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
  384. {
  385. return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds);
  386. }
  387. return null;
  388. }
  389. }
  390. }