aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/LiveTv/TunerHosts/QueueStream.cs
blob: 543d2e373ecbda32c8e6fdabaa60951a22e52a29 (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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Logging;

namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
    public class QueueStream
    {
        private readonly Stream _outputStream;
        private readonly ConcurrentQueue<Tuple<byte[], int, int>> _queue = new ConcurrentQueue<Tuple<byte[], int, int>>();
        private CancellationToken _cancellationToken;
        public TaskCompletionSource<bool> TaskCompletion { get; private set; }

        public Action<QueueStream> OnFinished { get; set; }
        private readonly ILogger _logger;
        public Guid Id = Guid.NewGuid();

        public QueueStream(Stream outputStream, ILogger logger)
        {
            _outputStream = outputStream;
            _logger = logger;
            TaskCompletion = new TaskCompletionSource<bool>();
        }

        public void Queue(byte[] bytes, int offset, int count)
        {
            _queue.Enqueue(new Tuple<byte[], int, int>(bytes, offset, count));
        }

        public void Start(CancellationToken cancellationToken)
        {
            _cancellationToken = cancellationToken;
            Task.Run(() => StartInternal());
        }

        private Tuple<byte[], int, int> Dequeue()
        {
            Tuple<byte[], int, int> result;
            if (_queue.TryDequeue(out result))
            {
                return result;
            }

            return null;
        }

        private void OnClosed()
        {
            GC.Collect();
            if (OnFinished != null)
            {
                OnFinished(this);
            }
        }

        public async Task WriteAsync(byte[] bytes, int offset, int count)
        {
            //return _outputStream.WriteAsync(bytes, offset, count, cancellationToken);
            var cancellationToken = _cancellationToken;

            try
            {
                await _outputStream.WriteAsync(bytes, offset, count, cancellationToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                _logger.Debug("QueueStream cancelled");
                TaskCompletion.TrySetCanceled();
                OnClosed();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error in QueueStream", ex);
                TaskCompletion.TrySetException(ex);
                OnClosed();
            }
        }

        private async Task StartInternal()
        {
            var cancellationToken = _cancellationToken;

            try
            {
                while (true)
                {
                    var result = Dequeue();
                    if (result != null)
                    {
                        await _outputStream.WriteAsync(result.Item1, result.Item2, result.Item3, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await Task.Delay(50, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                _logger.Debug("QueueStream cancelled");
                TaskCompletion.TrySetCanceled();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error in QueueStream", ex);
                TaskCompletion.TrySetException(ex);
            }
            finally
            {
                OnClosed();
            }
        }
    }
}