jellyfin/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs

250 lines
7.7 KiB
C#
Raw Normal View History

2017-09-28 17:02:49 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.System;
using MediaBrowser.Model.LiveTv;
2018-09-12 17:26:21 +00:00
using System.Linq;
using MediaBrowser.Controller.Library;
2017-09-28 17:02:49 +00:00
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class LiveStream : ILiveStream
{
public MediaSourceInfo OriginalMediaSource { get; set; }
2018-09-12 17:26:21 +00:00
public MediaSourceInfo MediaSource { get; set; }
public int ConsumerCount { get; set; }
2017-09-28 17:02:49 +00:00
public string OriginalStreamId { get; set; }
public bool EnableStreamSharing { get; set; }
public string UniqueId { get; private set; }
protected readonly IFileSystem FileSystem;
2017-11-14 07:41:21 +00:00
protected readonly IServerApplicationPaths AppPaths;
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
protected string TempFilePath;
2017-09-28 17:02:49 +00:00
protected readonly ILogger Logger;
2017-10-14 06:52:56 +00:00
protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
2017-09-28 17:02:49 +00:00
public string TunerHostId { get; private set; }
2018-09-12 17:26:21 +00:00
public DateTime DateOpened { get; protected set; }
public Func<Task> OnClose { get; set; }
public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
2017-09-28 17:02:49 +00:00
{
OriginalMediaSource = mediaSource;
FileSystem = fileSystem;
2018-09-12 17:26:21 +00:00
MediaSource = mediaSource;
2017-09-28 17:02:49 +00:00
Logger = logger;
EnableStreamSharing = true;
UniqueId = Guid.NewGuid().ToString("N");
2018-09-12 17:26:21 +00:00
if (tuner != null)
{
TunerHostId = tuner.Id;
}
2017-11-14 07:41:21 +00:00
AppPaths = appPaths;
2018-09-12 17:26:21 +00:00
ConsumerCount = 1;
2017-11-14 07:41:21 +00:00
SetTempFilePath("ts");
}
protected void SetTempFilePath(string extension)
{
TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension);
2017-09-28 17:02:49 +00:00
}
2017-10-23 19:14:11 +00:00
public virtual Task Open(CancellationToken openCancellationToken)
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
DateOpened = DateTime.UtcNow;
return Task.CompletedTask;
2017-09-28 17:02:49 +00:00
}
2018-09-12 17:26:21 +00:00
public Task Close()
{
EnableStreamSharing = false;
Logger.Info("Closing " + GetType().Name);
2018-09-12 17:26:21 +00:00
LiveStreamCancellationTokenSource.Cancel();
if (OnClose != null)
{
return CloseWithExternalFn();
}
return Task.CompletedTask;
}
2018-09-12 17:26:21 +00:00
private async Task CloseWithExternalFn()
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
try
{
await OnClose().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.ErrorException("Error closing live stream", ex);
}
2017-09-28 17:02:49 +00:00
}
protected Stream GetInputStream(string path, bool allowAsyncFileRead)
{
var fileOpenOptions = FileOpenOptions.SequentialScan;
if (allowAsyncFileRead)
{
fileOpenOptions |= FileOpenOptions.Asynchronous;
}
return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
}
2018-09-12 17:26:21 +00:00
public Task DeleteTempFiles()
{
return DeleteTempFiles(GetStreamFilePaths());
}
protected async Task DeleteTempFiles(List<string> paths, int retryCount = 0)
2017-09-28 17:02:49 +00:00
{
2017-10-23 19:14:11 +00:00
if (retryCount == 0)
{
2018-09-12 17:26:21 +00:00
Logger.Info("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
2017-10-23 19:14:11 +00:00
}
2018-09-12 17:26:21 +00:00
var failedFiles = new List<string>();
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
foreach (var path in paths)
{
try
{
FileSystem.DeleteFile(path);
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
//Logger.ErrorException("Error deleting file {0}", ex, path);
failedFiles.Add(path);
}
2017-09-28 17:02:49 +00:00
}
2018-09-12 17:26:21 +00:00
if (failedFiles.Count > 0 && retryCount <= 40)
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
await Task.Delay(500).ConfigureAwait(false);
await DeleteTempFiles(failedFiles, retryCount + 1).ConfigureAwait(false);
2017-09-28 17:02:49 +00:00
}
2018-09-12 17:26:21 +00:00
}
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
protected virtual List<string> GetStreamFilePaths()
{
return new List<string> { TempFilePath };
2017-09-28 17:02:49 +00:00
}
public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
{
2017-10-14 06:52:56 +00:00
cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
2018-09-12 17:26:21 +00:00
var allowAsync = false;
2017-09-28 17:02:49 +00:00
// use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
2018-09-12 17:26:21 +00:00
bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
var nextFileInfo = GetNextFile(null);
var nextFile = nextFileInfo.Item1;
var isLastFile = nextFileInfo.Item2;
while (!string.IsNullOrEmpty(nextFile))
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
seekFile = false;
nextFileInfo = GetNextFile(nextFile);
nextFile = nextFileInfo.Item1;
isLastFile = nextFileInfo.Item2;
2017-09-28 17:02:49 +00:00
}
2018-09-12 17:26:21 +00:00
Logger.Info("Live Stream ended.");
2017-09-28 17:02:49 +00:00
}
2018-09-12 17:26:21 +00:00
private Tuple<string, bool> GetNextFile(string currentFile)
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
var files = GetStreamFilePaths();
2017-10-14 06:52:56 +00:00
2018-09-12 17:26:21 +00:00
//Logger.Info("Live stream files: {0}", string.Join(", ", files.ToArray()));
2017-10-14 06:52:56 +00:00
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(currentFile))
2017-09-28 17:02:49 +00:00
{
2018-09-12 17:26:21 +00:00
return new Tuple<string, bool>(files.Last(), true);
}
var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
var isLastFile = nextIndex == files.Count - 1;
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
return new Tuple<string, bool>(files.ElementAtOrDefault(nextIndex), isLastFile);
}
private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
{
//Logger.Info("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
{
if (seekFile)
2017-10-14 06:52:56 +00:00
{
2018-09-12 17:26:21 +00:00
TrySeek(inputStream, -20000);
2017-10-14 06:52:56 +00:00
}
2018-09-12 17:26:21 +00:00
await ApplicationHost.StreamHelper.CopyToAsync(inputStream, stream, 81920, emptyReadLimit, cancellationToken).ConfigureAwait(false);
}
}
2017-09-28 17:02:49 +00:00
2018-09-12 17:26:21 +00:00
protected virtual int EmptyReadLimit
{
get
{
return 1000;
2017-09-28 17:02:49 +00:00
}
}
private void TrySeek(FileStream stream, long offset)
{
2018-09-12 17:26:21 +00:00
//Logger.Info("TrySeek live stream");
2017-09-28 17:02:49 +00:00
try
{
stream.Seek(offset, SeekOrigin.End);
2017-10-05 18:10:46 +00:00
}
catch (IOException)
{
2017-09-28 17:02:49 +00:00
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
Logger.ErrorException("Error seeking stream", ex);
}
}
}
}