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

350 lines
13 KiB
C#
Raw Normal View History

2017-03-02 21:32:20 +00:00
using System;
using System.IO;
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 Microsoft.Extensions.Logging;
2017-03-02 21:32:20 +00:00
using MediaBrowser.Model.MediaInfo;
2017-05-22 04:54:02 +00:00
using MediaBrowser.Model.System;
using MediaBrowser.Model.LiveTv;
2018-09-12 17:26:21 +00:00
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
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 IServerApplicationHost _appHost;
2018-09-12 17:26:21 +00:00
private readonly MediaBrowser.Model.Net.ISocketFactory _socketFactory;
2017-03-02 21:32:20 +00:00
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
2018-09-12 17:26:21 +00:00
public HdHomerunUdpStream(MediaSourceInfo mediaSource, TunerHostInfo tunerHostInfo, string originalStreamId, IHdHomerunChannelCommands channelCommands, int numTuners, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost, MediaBrowser.Model.Net.ISocketFactory socketFactory, INetworkManager networkManager)
: base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths)
2017-03-02 21:32:20 +00:00
{
_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-11-14 07:41:21 +00:00
EnableStreamSharing = true;
2017-03-02 21:32:20 +00:00
}
2018-09-12 17:26:21 +00:00
private Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
return socket;
}
2017-10-23 19:14:11 +00:00
public override async Task Open(CancellationToken openCancellationToken)
2017-03-02 21:32:20 +00:00
{
2017-10-14 06:52:56 +00:00
LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
2017-03-02 21:32:20 +00:00
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-10-23 19:14:11 +00:00
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath));
Logger.LogInformation("Opening HDHR UDP Live stream from {0}", uri.Host);
2017-03-02 21:32:20 +00:00
2018-09-12 17:26:21 +00:00
var remoteAddress = IPAddress.Parse(uri.Host);
var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host);
IPAddress localAddress = null;
using (var tcpSocket = CreateSocket(remoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
2017-10-23 19:14:11 +00:00
{
try
{
2018-09-12 17:26:21 +00:00
tcpSocket.Connect(new IPEndPoint(remoteAddress, HdHomerunManager.HdHomeRunPort));
localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address;
2017-10-23 19:14:11 +00:00
tcpSocket.Close();
}
catch (Exception)
{
Logger.LogError("Unable to determine local ip address for Legacy HDHomerun stream.");
2017-10-23 19:14:11 +00:00
return;
}
}
var udpClient = _socketFactory.CreateUdpSocket(localPort);
var hdHomerunManager = new HdHomerunManager(_socketFactory, Logger);
try
{
// send url to start streaming
2018-09-12 17:26:21 +00:00
await hdHomerunManager.StartStreaming(embyRemoteAddress, localAddress, localPort, _channelCommands, _numTuners, openCancellationToken).ConfigureAwait(false);
2017-10-23 19:14:11 +00:00
}
catch (Exception ex)
{
using (udpClient)
{
using (hdHomerunManager)
{
if (!(ex is OperationCanceledException))
{
Logger.LogError("Error opening live stream:", ex);
2017-10-23 19:14:11 +00:00
}
throw;
}
}
}
2017-03-02 21:32:20 +00:00
var taskCompletionSource = new TaskCompletionSource<bool>();
2018-09-12 17:26:21 +00:00
StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
2017-03-02 21:32:20 +00:00
//OpenedMediaSource.Protocol = MediaProtocol.File;
//OpenedMediaSource.Path = tempFile;
//OpenedMediaSource.ReadAtNativeFramerate = true;
2018-09-12 17:26:21 +00:00
MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
MediaSource.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 Task.Delay(5000).ConfigureAwait(false);
2017-10-23 19:14:11 +00:00
await taskCompletionSource.Task.ConfigureAwait(false);
2017-03-02 21:32:20 +00:00
}
2018-09-12 17:26:21 +00:00
private Task StartStreaming(MediaBrowser.Model.Net.ISocket udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, 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
{
2017-10-23 19:14:11 +00:00
using (udpClient)
2017-03-03 05:53:21 +00:00
{
2017-10-23 19:14:11 +00:00
using (hdHomerunManager)
2017-03-03 05:53:21 +00:00
{
2017-10-23 19:14:11 +00:00
try
{
await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException ex)
2017-03-03 05:53:21 +00:00
{
Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
2017-10-23 19:14:11 +00:00
openTaskCompletionSource.TrySetException(ex);
}
catch (Exception ex)
{
Logger.LogError("Error opening live stream:", ex);
2017-10-23 19:14:11 +00:00
openTaskCompletionSource.TrySetException(ex);
2017-03-03 05:53:21 +00:00
}
EnableStreamSharing = false;
2017-03-03 05:53:21 +00:00
}
}
2018-09-12 17:26:21 +00:00
await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
2017-05-22 04:54:02 +00:00
});
}
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(() =>
2017-10-23 19:14:11 +00:00
{
openTaskCompletionSource.TrySetResult(true);
});
2017-03-02 21:32:20 +00:00
}
2017-06-01 04:51:43 +00:00
private static int RtpHeaderBytes = 12;
2018-09-12 17:26:21 +00:00
private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
2017-05-25 13:00:14 +00:00
{
2017-06-01 04:51:43 +00:00
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-10-23 19:14:11 +00:00
using (var source = _socketFactory.CreateNetworkStream(udpClient, false))
2017-06-01 04:51:43 +00:00
{
2017-10-23 19:14:11 +00:00
using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
{
var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token;
2017-05-25 13:00:14 +00:00
2017-10-23 19:14:11 +00:00
while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
{
cancellationToken.ThrowIfCancellationRequested();
2017-05-25 13:00:14 +00:00
2017-10-23 19:14:11 +00:00
currentCancellationToken = cancellationToken;
2017-06-01 05:05:36 +00:00
2017-10-23 19:14:11 +00:00
read -= RtpHeaderBytes;
if (read > 0)
{
fileStream.Write(buffer, RtpHeaderBytes, read);
}
if (!resolved)
{
resolved = true;
2018-09-12 17:26:21 +00:00
DateOpened = DateTime.UtcNow;
2017-10-23 19:14:11 +00:00
Resolve(openTaskCompletionSource);
}
}
2017-06-01 05:05:36 +00:00
}
2017-05-25 13:00:14 +00:00
}
}
2017-06-01 06:25:07 +00:00
public class UdpClientStream : Stream
{
private static int RtpHeaderBytes = 12;
private static int PacketSize = 1316;
2018-09-12 17:26:21 +00:00
private readonly MediaBrowser.Model.Net.ISocket _udpClient;
2017-06-01 06:25:07 +00:00
bool disposed;
2018-09-12 17:26:21 +00:00
public UdpClientStream(MediaBrowser.Model.Net.ISocket udpClient) : base()
2017-06-01 06:25:07 +00:00
{
_udpClient = udpClient;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset + count < 0)
throw new ArgumentOutOfRangeException("offset + count must not be negative", "offset+count");
if (offset + count > buffer.Length)
throw new ArgumentException("offset + count must not be greater than the length of buffer", "offset+count");
if (disposed)
throw new ObjectDisposedException(typeof(UdpClientStream).ToString());
// This will always receive a 1328 packet size (PacketSize + RtpHeaderSize)
// The RTP header will be stripped so see how many reads we need to make to fill the buffer.
int numReads = count / PacketSize;
int totalBytesRead = 0;
byte[] receiveBuffer = new byte[81920];
for (int i = 0; i < numReads; ++i)
{
var data = await _udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
var bytesRead = data.ReceivedBytes - RtpHeaderBytes;
// remove rtp header
Buffer.BlockCopy(data.Buffer, RtpHeaderBytes, buffer, offset, bytesRead);
offset += bytesRead;
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset + count < 0)
throw new ArgumentOutOfRangeException("offset + count must not be negative", "offset+count");
if (offset + count > buffer.Length)
throw new ArgumentException("offset + count must not be greater than the length of buffer", "offset+count");
if (disposed)
throw new ObjectDisposedException(typeof(UdpClientStream).ToString());
// This will always receive a 1328 packet size (PacketSize + RtpHeaderSize)
// The RTP header will be stripped so see how many reads we need to make to fill the buffer.
int numReads = count / PacketSize;
int totalBytesRead = 0;
byte[] receiveBuffer = new byte[81920];
for (int i = 0; i < numReads; ++i)
{
var receivedBytes = _udpClient.Receive(receiveBuffer, 0, receiveBuffer.Length);
var bytesRead = receivedBytes - RtpHeaderBytes;
// remove rtp header
Buffer.BlockCopy(receiveBuffer, RtpHeaderBytes, buffer, offset, bytesRead);
offset += bytesRead;
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
protected override void Dispose(bool disposing)
{
disposed = true;
}
public override bool CanRead
{
get
{
throw new NotImplementedException();
}
}
public override bool CanSeek
{
get
{
throw new NotImplementedException();
}
}
public override bool CanWrite
{
get
{
throw new NotImplementedException();
}
}
public override long Length
{
get
{
throw new NotImplementedException();
}
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void Flush()
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
2017-03-02 21:32:20 +00:00
}
}