diff options
Diffstat (limited to 'MediaBrowser.Api/Playback/Progressive')
4 files changed, 113 insertions, 34 deletions
diff --git a/MediaBrowser.Api/Playback/Progressive/AudioService.cs b/MediaBrowser.Api/Playback/Progressive/AudioService.cs index 6fae65ffcb..ae592c428a 100644 --- a/MediaBrowser.Api/Playback/Progressive/AudioService.cs +++ b/MediaBrowser.Api/Playback/Progressive/AudioService.cs @@ -55,15 +55,7 @@ namespace MediaBrowser.Api.Playback.Progressive return ProcessRequest(request, true); } - /// <summary> - /// Gets the command line arguments. - /// </summary> - /// <param name="outputPath">The output path.</param> - /// <param name="state">The state.</param> - /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param> - /// <returns>System.String.</returns> - /// <exception cref="System.InvalidOperationException">Only aac and mp3 audio codecs are supported.</exception> - protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding) + protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding) { var audioTranscodeParams = new List<string>(); @@ -92,7 +84,7 @@ namespace MediaBrowser.Api.Playback.Progressive return string.Format("{0} -i {1} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1 -y \"{5}\"", inputModifier, - GetInputArgument(state), + GetInputArgument(transcodingJobId, state), threads, vn, string.Join(" ", audioTranscodeParams.ToArray()), diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index f0ad6ce5c4..50929e6f3f 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -142,10 +142,9 @@ namespace MediaBrowser.Api.Playback.Progressive var outputPath = state.OutputFilePath; var outputPathExists = File.Exists(outputPath); - var isStatic = request.Static || - (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive)); + var isTranscodeCached = outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive); - AddDlnaHeaders(state, responseHeaders, isStatic); + AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached); // Static stream if (request.Static) @@ -154,6 +153,10 @@ namespace MediaBrowser.Api.Playback.Progressive using (state) { + var job = string.IsNullOrEmpty(request.TranscodingJobId) ? + null : + ApiEntryPoint.Instance.GetTranscodingJob(request.TranscodingJobId); + var limits = new List<long>(); if (state.InputBitrate.HasValue) { @@ -172,7 +175,13 @@ namespace MediaBrowser.Api.Playback.Progressive } // Take the greater of the above to methods, just to be safe - var throttleLimit = limits.Count > 0 ? limits.Max() : 0; + var throttleLimit = limits.Count > 0 ? limits.First() : 0; + + // Pad to play it safe + var bytesPerSecond = Convert.ToInt64(1.05 * throttleLimit); + + // Don't even start evaluating this until at least two minutes have content have been consumed + var targetGap = throttleLimit * 120; return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions { @@ -182,17 +191,17 @@ namespace MediaBrowser.Api.Playback.Progressive Path = state.MediaPath, Throttle = request.Throttle, - // Pad by 20% to play it safe - ThrottleLimit = Convert.ToInt64(1.2 * throttleLimit), + ThrottleLimit = bytesPerSecond, - // 3.5 minutes - MinThrottlePosition = throttleLimit * 210 + MinThrottlePosition = targetGap, + + ThrottleCallback = (l1, l2) => ThrottleCallack(l1, l2, bytesPerSecond, job) }); } } // Not static but transcode cache file exists - if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive)) + if (isTranscodeCached) { var contentType = state.GetMimeType(outputPath); @@ -225,6 +234,67 @@ namespace MediaBrowser.Api.Playback.Progressive } } + private readonly long _gapLengthInTicks = TimeSpan.FromMinutes(3).Ticks; + + private long ThrottleCallack(long currentBytesPerSecond, long bytesWritten, long originalBytesPerSecond, TranscodingJob job) + { + var bytesDownloaded = job.BytesDownloaded ?? 0; + var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0; + var downloadPositionTicks = job.DownloadPositionTicks ?? 0; + + var path = job.Path; + + if (bytesDownloaded > 0 && transcodingPositionTicks > 0) + { + // Progressive Streaming - byte-based consideration + + try + { + var bytesTranscoded = job.BytesTranscoded ?? new FileInfo(path).Length; + + // Estimate the bytes the transcoder should be ahead + double gapFactor = _gapLengthInTicks; + gapFactor /= transcodingPositionTicks; + var targetGap = bytesTranscoded * gapFactor; + + var gap = bytesTranscoded - bytesDownloaded; + + if (gap < targetGap) + { + //Logger.Debug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + return 0; + } + + //Logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + } + catch + { + //Logger.Error("Error getting output size"); + } + } + else if (downloadPositionTicks > 0 && transcodingPositionTicks > 0) + { + // HLS - time-based consideration + + var targetGap = _gapLengthInTicks; + var gap = transcodingPositionTicks - downloadPositionTicks; + + if (gap < targetGap) + { + //Logger.Debug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); + return 0; + } + + //Logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); + } + else + { + //Logger.Debug("No throttle data for " + path); + } + + return originalBytesPerSecond; + } + /// <summary> /// Gets the static remote stream result. /// </summary> @@ -325,17 +395,18 @@ namespace MediaBrowser.Api.Playback.Progressive await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false); try { + TranscodingJob job; + if (!File.Exists(outputPath)) { - await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false); + job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false); } else { - ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive); + job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive); state.Dispose(); } - var job = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive); var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem, job); result.Options["Content-Type"] = contentType; diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs index a62f3dc9fc..6e77e5eabd 100644 --- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs +++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs @@ -1,7 +1,8 @@ -using System; +using System.Threading; using MediaBrowser.Common.IO; using MediaBrowser.Model.Logging; using ServiceStack.Web; +using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; @@ -73,7 +74,10 @@ namespace MediaBrowser.Api.Playback.Progressive } finally { - ApiEntryPoint.Instance.OnTranscodeEndRequest(Path, TranscodingJobType.Progressive); + if (_job != null) + { + ApiEntryPoint.Instance.OnTranscodeEndRequest(_job); + } } } } @@ -83,6 +87,8 @@ namespace MediaBrowser.Api.Playback.Progressive private readonly IFileSystem _fileSystem; private readonly TranscodingJob _job; + private long _bytesWritten = 0; + public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job) { _fileSystem = fileSystem; @@ -98,7 +104,7 @@ namespace MediaBrowser.Api.Playback.Progressive { while (eofCount < 15) { - await fs.CopyToAsync(outputStream).ConfigureAwait(false); + await CopyToAsyncInternal(fs, outputStream, 81920, CancellationToken.None).ConfigureAwait(false); var fsPosition = fs.Position; @@ -123,5 +129,22 @@ namespace MediaBrowser.Api.Playback.Progressive } } } + + private async Task CopyToAsyncInternal(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken) + { + byte[] array = new byte[bufferSize]; + int count; + while ((count = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0) + { + await destination.WriteAsync(array, 0, count, cancellationToken).ConfigureAwait(false); + + _bytesWritten += count; + + if (_job != null) + { + _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten); + } + } + } } } diff --git a/MediaBrowser.Api/Playback/Progressive/VideoService.cs b/MediaBrowser.Api/Playback/Progressive/VideoService.cs index 6393811649..f82de5a6ac 100644 --- a/MediaBrowser.Api/Playback/Progressive/VideoService.cs +++ b/MediaBrowser.Api/Playback/Progressive/VideoService.cs @@ -84,14 +84,7 @@ namespace MediaBrowser.Api.Playback.Progressive return ProcessRequest(request, true); } - /// <summary> - /// Gets the command line arguments. - /// </summary> - /// <param name="outputPath">The output path.</param> - /// <param name="state">The state.</param> - /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param> - /// <returns>System.String.</returns> - protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding) + protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding) { // Get the output codec name var videoCodec = state.OutputVideoCodec; @@ -110,7 +103,7 @@ namespace MediaBrowser.Api.Playback.Progressive return string.Format("{0} -i {1}{2} {3} {4} -map_metadata -1 -threads {5} {6}{7} -y \"{8}\"", inputModifier, - GetInputArgument(state), + GetInputArgument(transcodingJobId, state), keyFrame, GetMapArgs(state), GetVideoArguments(state, videoCodec), |
