1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
public class LiveStream : ILiveStream
{
public MediaSourceInfo OriginalMediaSource { get; set; }
public MediaSourceInfo MediaSource { get; set; }
public int ConsumerCount { get; set; }
public string OriginalStreamId { get; set; }
public bool EnableStreamSharing { get; set; }
public string UniqueId { get; private set; }
protected readonly IFileSystem FileSystem;
protected readonly IServerApplicationPaths AppPaths;
protected string TempFilePath;
protected readonly ILogger Logger;
protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
public string TunerHostId { get; private set; }
public DateTime DateOpened { get; protected set; }
public Func<Task> OnClose { get; set; }
public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
{
OriginalMediaSource = mediaSource;
FileSystem = fileSystem;
MediaSource = mediaSource;
Logger = logger;
EnableStreamSharing = true;
UniqueId = Guid.NewGuid().ToString("N");
if (tuner != null)
{
TunerHostId = tuner.Id;
}
AppPaths = appPaths;
ConsumerCount = 1;
SetTempFilePath("ts");
}
protected void SetTempFilePath(string extension)
{
TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension);
}
public virtual Task Open(CancellationToken openCancellationToken)
{
DateOpened = DateTime.UtcNow;
return Task.CompletedTask;
}
public Task Close()
{
EnableStreamSharing = false;
Logger.LogInformation("Closing " + GetType().Name);
LiveStreamCancellationTokenSource.Cancel();
if (OnClose != null)
{
return CloseWithExternalFn();
}
return Task.CompletedTask;
}
private async Task CloseWithExternalFn()
{
try
{
await OnClose().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error closing live stream");
}
}
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);
}
public Task DeleteTempFiles()
{
return DeleteTempFiles(GetStreamFilePaths());
}
protected async Task DeleteTempFiles(List<string> paths, int retryCount = 0)
{
if (retryCount == 0)
{
Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
}
var failedFiles = new List<string>();
foreach (var path in paths)
{
try
{
FileSystem.DeleteFile(path);
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
Logger.LogError(ex, "Error deleting file {path}", path);
failedFiles.Add(path);
}
}
if (failedFiles.Count > 0 && retryCount <= 40)
{
await Task.Delay(500).ConfigureAwait(false);
await DeleteTempFiles(failedFiles, retryCount + 1).ConfigureAwait(false);
}
}
protected virtual List<string> GetStreamFilePaths()
{
return new List<string> { TempFilePath };
}
public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
{
cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
var allowAsync = false;
// use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
var nextFileInfo = GetNextFile(null);
var nextFile = nextFileInfo.Item1;
var isLastFile = nextFileInfo.Item2;
while (!string.IsNullOrEmpty(nextFile))
{
var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
seekFile = false;
nextFileInfo = GetNextFile(nextFile);
nextFile = nextFileInfo.Item1;
isLastFile = nextFileInfo.Item2;
}
Logger.LogInformation("Live Stream ended.");
}
private Tuple<string, bool> GetNextFile(string currentFile)
{
var files = GetStreamFilePaths();
//logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
if (string.IsNullOrEmpty(currentFile))
{
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;
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.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
{
if (seekFile)
{
TrySeek(inputStream, -20000);
}
await ApplicationHost.StreamHelper.CopyToAsync(inputStream, stream, 81920, emptyReadLimit, cancellationToken).ConfigureAwait(false);
}
}
protected virtual int EmptyReadLimit => 1000;
private void TrySeek(FileStream stream, long offset)
{
//logger.LogInformation("TrySeek live stream");
try
{
stream.Seek(offset, SeekOrigin.End);
}
catch (IOException)
{
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
Logger.LogError(ex, "Error seeking stream");
}
}
}
}
|