aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/Playback/TranscodingThrottler.cs
blob: ff79bb48f4e72a07af40a935123e899f4381d737 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Logging;
using System;
using System.IO;
using System.Threading;

namespace MediaBrowser.Api.Playback
{
    public class TranscodingThrottler : IDisposable
    {
        private readonly TranscodingJob _job;
        private readonly ILogger _logger;
        private Timer _timer;
        private bool _isPaused;
        private readonly IConfigurationManager _config;

        public TranscodingThrottler(TranscodingJob job, ILogger logger, IConfigurationManager config)
        {
            _job = job;
            _logger = logger;
            _config = config;
        }

        private EncodingOptions GetOptions()
        {
            return _config.GetConfiguration<EncodingOptions>("encoding");
        }

        public void Start()
        {
            _timer = new Timer(TimerCallback, null, 5000, 5000);
        }

        private void TimerCallback(object state)
        {
            if (_job.HasExited)
            {
                DisposeTimer();
                return;
            }

            var options = GetOptions();

            if (/*options.EnableThrottling &&*/ IsThrottleAllowed(_job, options.ThrottleThresholdSeconds))
            {
                PauseTranscoding();
            }
            else
            {
                UnpauseTranscoding();
            }
        }

        private void PauseTranscoding()
        {
            if (!_isPaused)
            {
                _logger.Debug("Sending pause command to ffmpeg");

                try
                {
                    _job.Process.StandardInput.Write("c");
                    _isPaused = true;
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error pausing transcoding", ex);
                }
            }
        }

        private void UnpauseTranscoding()
        {
            if (_isPaused)
            {
                _logger.Debug("Sending unpause command to ffmpeg");

                try
                {
                    _job.Process.StandardInput.WriteLine();
                    _isPaused = false;
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error unpausing transcoding", ex);
                }
            }
        }

        private bool IsThrottleAllowed(TranscodingJob job, int thresholdSeconds)
        {
            var bytesDownloaded = job.BytesDownloaded ?? 0;
            var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
            var downloadPositionTicks = job.DownloadPositionTicks ?? 0;

            var path = job.Path;
            var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks;

            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 false;
                }

                //_logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
                return true;
            }

            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 false;
                    }

                    //_logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
                    return true;
                }
                catch
                {
                    //_logger.Error("Error getting output size");
                    return false;
                }
            }

            //_logger.Debug("No throttle data for " + path);
            return false;
        }

        public void Stop()
        {
            DisposeTimer();
            UnpauseTranscoding();
        }

        public void Dispose()
        {
            DisposeTimer();
        }

        private void DisposeTimer()
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
        }
    }
}