123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349 |
- 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 MediaBrowser.Model.Logging;
- using MediaBrowser.Model.MediaInfo;
- using MediaBrowser.Model.Net;
- using MediaBrowser.Model.System;
- namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
- {
- public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
- {
- private readonly IServerApplicationHost _appHost;
- private readonly ISocketFactory _socketFactory;
- private readonly IHdHomerunChannelCommands _channelCommands;
- private readonly int _numTuners;
- private readonly INetworkManager _networkManager;
- 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, logger, appPaths)
- {
- _appHost = appHost;
- _socketFactory = socketFactory;
- _networkManager = networkManager;
- OriginalStreamId = originalStreamId;
- _channelCommands = channelCommands;
- _numTuners = numTuners;
- }
- public override async Task Open(CancellationToken openCancellationToken)
- {
- LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
- var mediaSource = OriginalMediaSource;
- var uri = new Uri(mediaSource.Path);
- var localPort = _networkManager.GetRandomUnusedUdpPort();
- FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath));
- Logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host);
- var remoteAddress = _networkManager.ParseIpAddress(uri.Host);
- IpAddressInfo localAddress = null;
- using (var tcpSocket = _socketFactory.CreateSocket(remoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, false))
- {
- 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;
- }
- }
- var udpClient = _socketFactory.CreateUdpSocket(localPort);
- var hdHomerunManager = new HdHomerunManager(_socketFactory, Logger);
- try
- {
- // send url to start streaming
- await hdHomerunManager.StartStreaming(remoteAddress, localAddress, localPort, _channelCommands, _numTuners, openCancellationToken).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- using (udpClient)
- {
- using (hdHomerunManager)
- {
- if (!(ex is OperationCanceledException))
- {
- Logger.ErrorException("Error opening live stream:", ex);
- }
- throw;
- }
- }
- }
- var taskCompletionSource = new TaskCompletionSource<bool>();
- StartStreaming(udpClient, hdHomerunManager, remoteAddress, localAddress, localPort, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
- //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;
- //OpenedMediaSource.SupportsDirectPlay = false;
- //OpenedMediaSource.SupportsDirectStream = true;
- //OpenedMediaSource.SupportsTranscoding = true;
- //await Task.Delay(5000).ConfigureAwait(false);
- await taskCompletionSource.Task.ConfigureAwait(false);
- }
- public override void Close()
- {
- Logger.Info("Closing HDHR UDP live stream");
- LiveStreamCancellationTokenSource.Cancel();
- }
- private Task StartStreaming(ISocket udpClient, HdHomerunManager hdHomerunManager, IpAddressInfo remoteAddress, IpAddressInfo localAddress, int localPort, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
- {
- return Task.Run(async () =>
- {
- using (udpClient)
- {
- using (hdHomerunManager)
- {
- try
- {
- await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException ex)
- {
- Logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
- openTaskCompletionSource.TrySetException(ex);
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error opening live stream:", ex);
- openTaskCompletionSource.TrySetException(ex);
- }
- try
- {
- await hdHomerunManager.StopStreaming().ConfigureAwait(false);
- }
- catch
- {
- }
- }
- }
- await DeleteTempFile(TempFilePath).ConfigureAwait(false);
- });
- }
- private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
- {
- Task.Run(() =>
- {
- openTaskCompletionSource.TrySetResult(true);
- });
- }
- private static int RtpHeaderBytes = 12;
- private async Task CopyTo(ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
- {
- var bufferSize = 81920;
- byte[] buffer = new byte[bufferSize];
- int read;
- var resolved = false;
- using (var source = _socketFactory.CreateNetworkStream(udpClient, false))
- {
- 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;
- while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0)
- {
- cancellationToken.ThrowIfCancellationRequested();
- currentCancellationToken = cancellationToken;
- read -= RtpHeaderBytes;
- if (read > 0)
- {
- fileStream.Write(buffer, RtpHeaderBytes, read);
- }
- if (!resolved)
- {
- resolved = true;
- Resolve(openTaskCompletionSource);
- }
- }
- }
- }
- }
- public class UdpClientStream : Stream
- {
- private static int RtpHeaderBytes = 12;
- private static int PacketSize = 1316;
- private readonly ISocket _udpClient;
- bool disposed;
- public UdpClientStream(ISocket udpClient) : base()
- {
- _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();
- }
- }
- }
- }
|