jellyfin/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs

289 lines
12 KiB
C#
Raw Normal View History

2017-03-02 21:32:20 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2017-05-25 04:25:51 +00:00
using Emby.Server.Implementations.IO;
2017-03-02 21:32:20 +00:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
2017-05-22 04:54:02 +00:00
using MediaBrowser.Model.System;
2017-06-01 04:51:43 +00:00
using System.Globalization;
using MediaBrowser.Controller.IO;
2017-03-02 21:32:20 +00:00
namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
2017-03-03 05:53:21 +00:00
public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
2017-03-02 21:32:20 +00:00
{
private readonly ILogger _logger;
private readonly IServerApplicationHost _appHost;
private readonly ISocketFactory _socketFactory;
private readonly CancellationTokenSource _liveStreamCancellationTokenSource = new CancellationTokenSource();
private readonly TaskCompletionSource<bool> _liveStreamTaskCompletionSource = new TaskCompletionSource<bool>();
2017-03-06 02:32:56 +00:00
private readonly IHdHomerunChannelCommands _channelCommands;
2017-03-02 21:32:20 +00:00
private readonly int _numTuners;
2017-03-03 04:36:20 +00:00
private readonly INetworkManager _networkManager;
2017-03-02 21:32:20 +00:00
2017-05-22 04:54:02 +00:00
private readonly string _tempFilePath;
public HdHomerunUdpStream(MediaSourceInfo mediaSource, string originalStreamId, IHdHomerunChannelCommands channelCommands, int numTuners, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost, ISocketFactory socketFactory, INetworkManager networkManager, IEnvironmentInfo environment)
: base(mediaSource, environment, fileSystem)
2017-03-02 21:32:20 +00:00
{
_logger = logger;
_appHost = appHost;
_socketFactory = socketFactory;
2017-03-03 04:36:20 +00:00
_networkManager = networkManager;
2017-03-02 21:32:20 +00:00
OriginalStreamId = originalStreamId;
2017-03-06 02:32:56 +00:00
_channelCommands = channelCommands;
2017-03-02 21:32:20 +00:00
_numTuners = numTuners;
2017-05-22 04:54:02 +00:00
_tempFilePath = Path.Combine(appPaths.TranscodingTempPath, UniqueId + ".ts");
2017-03-02 21:32:20 +00:00
}
protected override async Task OpenInternal(CancellationToken openCancellationToken)
{
_liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
var mediaSource = OriginalMediaSource;
2017-03-03 04:36:20 +00:00
var uri = new Uri(mediaSource.Path);
var localPort = _networkManager.GetRandomUnusedUdpPort();
2017-03-02 21:32:20 +00:00
2017-03-03 05:53:21 +00:00
_logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host);
2017-03-02 21:32:20 +00:00
var taskCompletionSource = new TaskCompletionSource<bool>();
2017-03-03 04:36:20 +00:00
StartStreaming(uri.Host, localPort, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
2017-03-02 21:32:20 +00:00
//OpenedMediaSource.Protocol = MediaProtocol.File;
//OpenedMediaSource.Path = tempFile;
//OpenedMediaSource.ReadAtNativeFramerate = true;
OpenedMediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
OpenedMediaSource.Protocol = MediaProtocol.Http;
2017-05-19 16:39:40 +00:00
//OpenedMediaSource.SupportsDirectPlay = false;
//OpenedMediaSource.SupportsDirectStream = true;
//OpenedMediaSource.SupportsTranscoding = true;
2017-03-02 21:32:20 +00:00
await taskCompletionSource.Task.ConfigureAwait(false);
//await Task.Delay(5000).ConfigureAwait(false);
}
public override Task Close()
{
2017-03-03 05:53:21 +00:00
_logger.Info("Closing HDHR UDP live stream");
2017-03-02 21:32:20 +00:00
_liveStreamCancellationTokenSource.Cancel();
return _liveStreamTaskCompletionSource.Task;
}
2017-05-22 04:54:02 +00:00
private Task StartStreaming(string remoteIp, int localPort, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
2017-03-02 21:32:20 +00:00
{
2017-05-22 04:54:02 +00:00
return Task.Run(async () =>
2017-03-03 05:53:21 +00:00
{
var isFirstAttempt = true;
using (var udpClient = _socketFactory.CreateUdpSocket(localPort))
{
using (var hdHomerunManager = new HdHomerunManager(_socketFactory))
{
2017-03-03 20:16:43 +00:00
var remoteAddress = _networkManager.ParseIpAddress(remoteIp);
2017-03-03 05:53:21 +00:00
IpAddressInfo localAddress = null;
2017-03-03 20:16:43 +00:00
using (var tcpSocket = _socketFactory.CreateSocket(remoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, false))
2017-03-03 05:53:21 +00:00
{
try
{
tcpSocket.Connect(new IpEndPointInfo(remoteAddress, HdHomerunManager.HdHomeRunPort));
localAddress = tcpSocket.LocalEndPoint.IpAddress;
tcpSocket.Close();
}
catch (Exception)
{
_logger.Error("Unable to determine local ip address for Legacy HDHomerun stream.");
return;
}
}
while (!cancellationToken.IsCancellationRequested)
{
try
{
// send url to start streaming
2017-03-06 02:32:56 +00:00
await hdHomerunManager.StartStreaming(remoteAddress, localAddress, localPort, _channelCommands, _numTuners, cancellationToken).ConfigureAwait(false);
2017-03-03 05:53:21 +00:00
2017-03-06 02:32:56 +00:00
_logger.Info("Opened HDHR UDP stream from {0}", remoteAddress);
2017-03-03 05:53:21 +00:00
if (!cancellationToken.IsCancellationRequested)
{
2017-05-22 04:54:02 +00:00
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(_tempFilePath));
2017-06-01 04:51:43 +00:00
using (var fileStream = FileSystem.GetFileStream(_tempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
2017-03-03 05:53:21 +00:00
{
2017-06-01 04:51:43 +00:00
CopyTo(udpClient, fileStream, openTaskCompletionSource, cancellationToken);
2017-05-22 04:54:02 +00:00
}
2017-03-03 05:53:21 +00:00
}
}
2017-03-23 19:10:10 +00:00
catch (OperationCanceledException ex)
2017-03-03 05:53:21 +00:00
{
2017-03-23 19:10:10 +00:00
_logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
openTaskCompletionSource.TrySetException(ex);
2017-03-03 05:53:21 +00:00
break;
}
catch (Exception ex)
{
if (isFirstAttempt)
{
_logger.ErrorException("Error opening live stream:", ex);
openTaskCompletionSource.TrySetException(ex);
break;
}
_logger.ErrorException("Error copying live stream, will reopen", ex);
}
isFirstAttempt = false;
}
await hdHomerunManager.StopStreaming().ConfigureAwait(false);
_liveStreamTaskCompletionSource.TrySetResult(true);
}
}
2017-05-22 04:54:02 +00:00
await DeleteTempFile(_tempFilePath).ConfigureAwait(false);
});
}
2017-05-23 16:44:11 +00:00
private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
2017-05-22 04:54:02 +00:00
{
2017-05-23 16:44:11 +00:00
Task.Run(() =>
{
openTaskCompletionSource.TrySetResult(true);
});
2017-03-02 21:32:20 +00:00
}
2017-06-01 05:05:36 +00:00
public async Task CopyToAsync(Stream outputStream, CancellationToken cancellationToken)
2017-03-02 21:32:20 +00:00
{
2017-06-01 05:05:36 +00:00
var path = _tempFilePath;
2017-05-23 16:44:11 +00:00
2017-06-01 04:51:43 +00:00
long startPosition = -20000;
2017-05-25 13:00:14 +00:00
if (startPosition < 0)
2017-05-23 16:44:11 +00:00
{
2017-05-25 13:00:14 +00:00
var length = FileSystem.GetFileInfo(path).Length;
startPosition = Math.Max(length - startPosition, 0);
}
2017-06-01 04:51:43 +00:00
_logger.Info("Live stream starting position is {0} bytes", startPosition.ToString(CultureInfo.InvariantCulture));
var allowAsync = Environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows;
// use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
using (var inputStream = GetInputStream(path, startPosition, allowAsync))
2017-05-25 13:00:14 +00:00
{
if (startPosition > 0)
{
inputStream.Position = startPosition;
}
2017-05-23 16:44:11 +00:00
2017-06-01 04:51:43 +00:00
while (!cancellationToken.IsCancellationRequested)
2017-05-23 16:44:11 +00:00
{
2017-06-01 04:51:43 +00:00
long bytesRead;
if (allowAsync)
{
bytesRead = await AsyncStreamCopier.CopyStream(inputStream, outputStream, 81920, 2, cancellationToken).ConfigureAwait(false);
}
else
{
StreamHelper.CopyTo(inputStream, outputStream, 81920, cancellationToken);
bytesRead = 1;
}
2017-05-25 13:00:14 +00:00
//var position = fs.Position;
//_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
if (bytesRead == 0)
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
2017-05-23 16:44:11 +00:00
}
}
}
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
private static int RtpHeaderBytes = 12;
private void CopyTo(ISocket udpClient, Stream target, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
2017-05-25 13:00:14 +00:00
{
2017-06-01 04:51:43 +00:00
var source = _socketFactory.CreateNetworkStream(udpClient, false);
var bufferSize = 81920;
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
byte[] buffer = new byte[bufferSize];
int read;
2017-06-01 05:05:36 +00:00
var resolved = false;
2017-06-01 04:51:43 +00:00
while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
{
cancellationToken.ThrowIfCancellationRequested();
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
read -= RtpHeaderBytes;
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
if (read > 0)
{
target.Write(buffer, RtpHeaderBytes, read);
}
2017-06-01 05:05:36 +00:00
if (!resolved)
{
resolved = true;
Resolve(openTaskCompletionSource);
}
2017-05-25 13:00:14 +00:00
}
2017-06-01 04:51:43 +00:00
//var copier = new AsyncStreamCopier(source, target, 0, cancellationToken, false, bufferSize, bufferCount);
//copier.IndividualReadOffset = RtpHeaderBytes;
//var taskCompletion = new TaskCompletionSource<long>();
//copier.TaskCompletionSource = taskCompletion;
//var result = copier.BeginCopy(StreamCopyCallback, copier);
//if (openTaskCompletionSource != null)
//{
// Resolve(openTaskCompletionSource);
// openTaskCompletionSource = null;
//}
//if (result.CompletedSynchronously)
//{
// StreamCopyCallback(result);
//}
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
//cancellationToken.Register(() => taskCompletion.TrySetCanceled());
2017-05-25 13:00:14 +00:00
2017-06-01 04:51:43 +00:00
//return taskCompletion.Task;
2017-05-25 13:00:14 +00:00
}
private void StreamCopyCallback(IAsyncResult result)
{
var copier = (AsyncStreamCopier)result.AsyncState;
var taskCompletion = copier.TaskCompletionSource;
try
{
copier.EndCopy(result);
taskCompletion.TrySetResult(0);
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
}
2017-03-02 21:32:20 +00:00
}
2017-03-23 19:10:10 +00:00
}