2016-10-07 15:08:13 +00:00
|
|
|
|
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;
|
|
|
|
|
|
2016-11-03 23:35:19 +00:00
|
|
|
|
namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
2016-10-07 15:08:13 +00:00
|
|
|
|
{
|
|
|
|
|
public class QueueStream
|
|
|
|
|
{
|
|
|
|
|
private readonly Stream _outputStream;
|
|
|
|
|
private readonly ConcurrentQueue<byte[]> _queue = new ConcurrentQueue<byte[]>();
|
|
|
|
|
private CancellationToken _cancellationToken;
|
|
|
|
|
public TaskCompletionSource<bool> TaskCompletion { get; private set; }
|
|
|
|
|
|
|
|
|
|
public Action<QueueStream> OnFinished { get; set; }
|
|
|
|
|
private readonly ILogger _logger;
|
2017-02-01 20:55:56 +00:00
|
|
|
|
public Guid Id = Guid.NewGuid();
|
2016-10-07 15:08:13 +00:00
|
|
|
|
|
|
|
|
|
public QueueStream(Stream outputStream, ILogger logger)
|
|
|
|
|
{
|
|
|
|
|
_outputStream = outputStream;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
TaskCompletion = new TaskCompletionSource<bool>();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Queue(byte[] bytes)
|
|
|
|
|
{
|
2017-02-01 20:55:56 +00:00
|
|
|
|
_queue.Enqueue(bytes);
|
2016-10-07 15:08:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Start(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
_cancellationToken = cancellationToken;
|
2016-10-07 15:13:57 +00:00
|
|
|
|
Task.Run(() => StartInternal());
|
2016-10-07 15:08:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private byte[] Dequeue()
|
|
|
|
|
{
|
|
|
|
|
byte[] bytes;
|
|
|
|
|
if (_queue.TryDequeue(out bytes))
|
|
|
|
|
{
|
|
|
|
|
return bytes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task StartInternal()
|
|
|
|
|
{
|
|
|
|
|
var cancellationToken = _cancellationToken;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2017-02-01 20:55:56 +00:00
|
|
|
|
while (true)
|
2016-10-07 15:08:13 +00:00
|
|
|
|
{
|
|
|
|
|
var bytes = Dequeue();
|
|
|
|
|
if (bytes != null)
|
|
|
|
|
{
|
|
|
|
|
await _outputStream.WriteAsync(bytes, 0, bytes.Length, 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
|
|
|
|
|
{
|
|
|
|
|
if (OnFinished != null)
|
|
|
|
|
{
|
|
|
|
|
OnFinished(this);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|