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

205 lines
7.9 KiB
C#
Raw Normal View History

using System;
2019-07-07 07:39:35 -07:00
using System.Buffers;
using System.Collections.Generic;
2017-03-02 14:32:20 -07:00
using System.IO;
using System.Net;
using System.Net.Sockets;
2017-03-02 14:32:20 -07:00
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
2017-03-02 14:32:20 -07:00
namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
2017-03-02 22:53:21 -07:00
public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
2017-03-02 14:32:20 -07:00
{
2019-07-07 07:39:35 -07:00
private const int RtpHeaderBytes = 12;
2017-03-02 14:32:20 -07:00
private readonly IServerApplicationHost _appHost;
2018-09-12 10:26:21 -07:00
private readonly MediaBrowser.Model.Net.ISocketFactory _socketFactory;
2017-03-02 14:32:20 -07:00
2017-03-05 19:32:56 -07:00
private readonly IHdHomerunChannelCommands _channelCommands;
2017-03-02 14:32:20 -07:00
private readonly int _numTuners;
2017-03-02 21:36:20 -07:00
private readonly INetworkManager _networkManager;
2017-03-02 14:32:20 -07:00
public HdHomerunUdpStream(
MediaSourceInfo mediaSource,
TunerHostInfo tunerHostInfo,
string originalStreamId,
IHdHomerunChannelCommands channelCommands,
int numTuners,
IFileSystem fileSystem,
ILogger logger,
IServerApplicationPaths appPaths,
IServerApplicationHost appHost,
MediaBrowser.Model.Net.ISocketFactory socketFactory,
2019-07-07 07:39:35 -07:00
INetworkManager networkManager,
IStreamHelper streamHelper)
: base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths, streamHelper)
2017-03-02 14:32:20 -07:00
{
_appHost = appHost;
_socketFactory = socketFactory;
2017-03-02 21:36:20 -07:00
_networkManager = networkManager;
2017-03-02 14:32:20 -07:00
OriginalStreamId = originalStreamId;
2017-03-05 19:32:56 -07:00
_channelCommands = channelCommands;
2017-03-02 14:32:20 -07:00
_numTuners = numTuners;
2017-11-14 00:41:21 -07:00
EnableStreamSharing = true;
2017-03-02 14:32:20 -07:00
}
2017-10-23 12:14:11 -07:00
public override async Task Open(CancellationToken openCancellationToken)
2017-03-02 14:32:20 -07:00
{
2017-10-13 23:52:56 -07:00
LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
2017-03-02 14:32:20 -07:00
var mediaSource = OriginalMediaSource;
2017-03-02 21:36:20 -07:00
var uri = new Uri(mediaSource.Path);
var localPort = _networkManager.GetRandomUnusedUdpPort();
2017-03-02 14:32:20 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
2017-10-23 12:14:11 -07:00
2018-12-20 05:11:26 -07:00
Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);
2017-03-02 14:32:20 -07:00
2018-09-12 10:26:21 -07:00
var remoteAddress = IPAddress.Parse(uri.Host);
IPAddress localAddress = null;
using (var tcpClient = new TcpClient())
2017-10-23 12:14:11 -07:00
{
try
{
await tcpClient.ConnectAsync(remoteAddress, HdHomerunManager.HdHomeRunPort).ConfigureAwait(false);
localAddress = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address;
tcpClient.Close();
2017-10-23 12:14:11 -07:00
}
2018-12-20 05:11:26 -07:00
catch (Exception ex)
2017-10-23 12:14:11 -07:00
{
2018-12-20 05:11:26 -07:00
Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream.");
2017-10-23 12:14:11 -07:00
return;
}
}
var udpClient = _socketFactory.CreateUdpSocket(localPort);
2019-07-07 07:39:35 -07:00
var hdHomerunManager = new HdHomerunManager();
2017-10-23 12:14:11 -07:00
try
{
// send url to start streaming
2019-08-16 12:18:37 -07:00
await hdHomerunManager.StartStreaming(
remoteAddress,
localAddress,
localPort,
_channelCommands,
_numTuners,
openCancellationToken).ConfigureAwait(false);
2017-10-23 12:14:11 -07:00
}
catch (Exception ex)
{
using (udpClient)
2018-12-20 05:11:26 -07:00
using (hdHomerunManager)
2017-10-23 12:14:11 -07:00
{
2018-12-20 05:11:26 -07:00
if (!(ex is OperationCanceledException))
2017-10-23 12:14:11 -07:00
{
2018-12-20 05:11:26 -07:00
Logger.LogError(ex, "Error opening live stream:");
2017-10-23 12:14:11 -07:00
}
2018-12-20 05:11:26 -07:00
throw;
2017-10-23 12:14:11 -07:00
}
}
2017-03-02 14:32:20 -07:00
var taskCompletionSource = new TaskCompletionSource<bool>();
2019-07-07 07:39:35 -07:00
await StartStreaming(
udpClient,
hdHomerunManager,
remoteAddress,
taskCompletionSource,
LiveStreamCancellationTokenSource.Token).ConfigureAwait(false);
2017-03-02 14:32:20 -07:00
//OpenedMediaSource.Protocol = MediaProtocol.File;
//OpenedMediaSource.Path = tempFile;
//OpenedMediaSource.ReadAtNativeFramerate = true;
2018-09-12 10:26:21 -07:00
MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
MediaSource.Protocol = MediaProtocol.Http;
2017-05-19 09:39:40 -07:00
//OpenedMediaSource.SupportsDirectPlay = false;
//OpenedMediaSource.SupportsDirectStream = true;
//OpenedMediaSource.SupportsTranscoding = true;
2017-03-02 14:32:20 -07:00
//await Task.Delay(5000).ConfigureAwait(false);
2017-10-23 12:14:11 -07:00
await taskCompletionSource.Task.ConfigureAwait(false);
2017-03-02 14:32:20 -07:00
}
2018-09-12 10:26:21 -07:00
private Task StartStreaming(MediaBrowser.Model.Net.ISocket udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
2017-03-02 14:32:20 -07:00
{
2017-05-21 21:54:02 -07:00
return Task.Run(async () =>
2017-03-02 22:53:21 -07:00
{
2017-10-23 12:14:11 -07:00
using (udpClient)
2018-12-20 05:11:26 -07:00
using (hdHomerunManager)
2017-03-02 22:53:21 -07:00
{
2018-12-20 05:11:26 -07:00
try
2017-03-02 22:53:21 -07:00
{
2018-12-20 05:11:26 -07:00
await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
2017-03-02 22:53:21 -07:00
}
2018-12-20 05:11:26 -07:00
catch (OperationCanceledException ex)
{
Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
openTaskCompletionSource.TrySetException(ex);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error opening live stream:");
openTaskCompletionSource.TrySetException(ex);
}
EnableStreamSharing = false;
2017-03-02 22:53:21 -07:00
}
2018-09-12 10:26:21 -07:00
await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
2017-05-21 21:54:02 -07:00
});
}
2018-09-12 10:26:21 -07:00
private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
2017-05-25 06:00:14 -07:00
{
2019-07-07 07:39:35 -07:00
byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamDefaults.DefaultCopyToBufferSize);
try
2017-05-31 21:51:43 -07:00
{
2019-07-07 07:39:35 -07:00
using (var source = _socketFactory.CreateNetworkStream(udpClient, false))
using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
2018-12-20 05:11:26 -07:00
{
2019-07-07 07:39:35 -07:00
var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token;
int read;
var resolved = false;
while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
{
cancellationToken.ThrowIfCancellationRequested();
2017-05-25 06:00:14 -07:00
2019-07-07 07:39:35 -07:00
currentCancellationToken = cancellationToken;
2017-05-31 22:05:36 -07:00
2019-07-07 07:39:35 -07:00
read -= RtpHeaderBytes;
2017-10-23 12:14:11 -07:00
2019-07-07 07:39:35 -07:00
if (read > 0)
{
await fileStream.WriteAsync(buffer, RtpHeaderBytes, read).ConfigureAwait(false);
}
2017-10-23 12:14:11 -07:00
2019-07-07 07:39:35 -07:00
if (!resolved)
{
resolved = true;
DateOpened = DateTime.UtcNow;
openTaskCompletionSource.TrySetResult(true);
}
2017-10-23 12:14:11 -07:00
}
2017-05-31 22:05:36 -07:00
}
2017-05-25 06:00:14 -07:00
}
2019-07-07 07:39:35 -07:00
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
2017-05-25 06:00:14 -07:00
}
2017-03-02 14:32:20 -07:00
}
}