private async Task <List <LiveTvTunerInfo> > GetTunerInfosUdp(TunerHostInfo info, CancellationToken cancellationToken)
        {
            var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);

            var tuners = new List <LiveTvTunerInfo>();

            var uri = new Uri(GetApiUrl(info));

            using (var manager = new HdHomerunManager(_socketFactory, Logger))
            {
                // Legacy HdHomeruns are IPv4 only
                var ipInfo = _networkManager.ParseIpAddress(uri.Host);

                for (int i = 0; i < model.TunerCount; ++i)
                {
                    var name           = string.Format("Tuner {0}", i + 1);
                    var currentChannel = "none"; /// @todo Get current channel and map back to Station Id
                    var isAvailable    = await manager.CheckTunerAvailability(ipInfo, i, cancellationToken).ConfigureAwait(false);

                    var status = isAvailable ? LiveTvTunerStatus.Available : LiveTvTunerStatus.LiveTv;
                    tuners.Add(new LiveTvTunerInfo
                    {
                        Name        = name,
                        SourceType  = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
                        ProgramName = currentChannel,
                        Status      = status
                    });
                }
            }
            return(tuners);
        }
Exemple #2
0
        private async Task <IpAddressInfo> GetIpAddress(string lookupUrl, bool preferIpv4 = false)
        {
            // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
            var logErrors = false;

#if DEBUG
            logErrors = true;
#endif
            using (var stream = await _httpClient.Get(new HttpRequestOptions
            {
                Url = lookupUrl,
                UserAgent = "Emby/" + _appHost.ApplicationVersion,
                LogErrors = logErrors,

                // Seeing block length errors with our server
                EnableHttpCompression = false,
                PreferIpv4 = preferIpv4,
                BufferContent = false
            }).ConfigureAwait(false))
            {
                using (var reader = new StreamReader(stream))
                {
                    var addressString = await reader.ReadToEndAsync().ConfigureAwait(false);

                    return(_networkManager.ParseIpAddress(addressString));
                }
            }
        }
        public override async Task Open(CancellationToken openCancellationToken)
        {
            LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();

            var mediaSource = OriginalMediaSource;

            var uri       = new Uri(mediaSource.Path);
            var localPort = _networkManager.GetRandomUnusedUdpPort();

            Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));

            Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);

            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))
            {
                try
                {
                    tcpSocket.Connect(new IPEndPoint(remoteAddress, HdHomerunManager.HdHomeRunPort));
                    localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address;
                    tcpSocket.Close();
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "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(embyRemoteAddress, localAddress, localPort, _channelCommands, _numTuners, openCancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                using (udpClient)
                    using (hdHomerunManager)
                    {
                        if (!(ex is OperationCanceledException))
                        {
                            Logger.LogError(ex, "Error opening live stream:");
                        }
                        throw;
                    }
            }

            var taskCompletionSource = new TaskCompletionSource <bool>();

            await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token);

            //OpenedMediaSource.Protocol = MediaProtocol.File;
            //OpenedMediaSource.Path = tempFile;
            //OpenedMediaSource.ReadAtNativeFramerate = true;

            MediaSource.Path     = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
            MediaSource.Protocol = MediaProtocol.Http;
            //OpenedMediaSource.SupportsDirectPlay = false;
            //OpenedMediaSource.SupportsDirectStream = true;
            //OpenedMediaSource.SupportsTranscoding = true;

            //await Task.Delay(5000).ConfigureAwait(false);
            await taskCompletionSource.Task.ConfigureAwait(false);
        }
Exemple #4
0
        private async Task StartStreaming(string remoteIp, int localPort, TaskCompletionSource <bool> openTaskCompletionSource, CancellationToken cancellationToken)
        {
            await Task.Run(async() =>
            {
                var isFirstAttempt = true;
                using (var udpClient = _socketFactory.CreateUdpSocket(localPort))
                {
                    using (var hdHomerunManager = new HdHomerunManager(_socketFactory))
                    {
                        var remoteAddress          = _networkManager.ParseIpAddress(remoteIp);
                        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;
                            }
                        }

                        while (!cancellationToken.IsCancellationRequested)
                        {
                            try
                            {
                                // send url to start streaming
                                await hdHomerunManager.StartStreaming(remoteAddress, localAddress, localPort, _channelCommands, _numTuners, cancellationToken).ConfigureAwait(false);

                                var response = await udpClient.ReceiveAsync(cancellationToken).ConfigureAwait(false);
                                _logger.Info("Opened HDHR UDP stream from {0}", remoteAddress);

                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    Action onStarted = null;
                                    if (isFirstAttempt)
                                    {
                                        onStarted = () => openTaskCompletionSource.TrySetResult(true);
                                    }

                                    var stream = new UdpClientStream(udpClient);
                                    await _multicastStream.CopyUntilCancelled(stream, onStarted, cancellationToken).ConfigureAwait(false);
                                }
                            }
                            catch (OperationCanceledException)
                            {
                                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);
                        udpClient.Dispose();
                        _liveStreamTaskCompletionSource.TrySetResult(true);
                    }
                }
            }).ConfigureAwait(false);
        }