/
TvTimeShiftPositionWatcher.cs
409 lines (348 loc) · 12.8 KB
/
TvTimeShiftPositionWatcher.cs
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
using System;
using System.Collections.Generic;
using System.Threading;
using TvControl;
using TvDatabase;
using TvLibrary.Interfaces;
using TvLibrary.Log;
using TvEngine.Events;
using System.Timers;
namespace TsBufferExtractor
{
public class TvTimeShiftPositionWatcher
{
#region Variables
private long _snapshotBufferId = 0;
private long _bufferId = 0;
private System.Timers.Timer _timer = null;
private int _idChannelToWatch = -1;
private Int64 _snapshotBufferPosition = -1;
private string _snapshotBufferFile = string.Empty;
private decimal _preRecordInterval = -1;
private int _secondsElapsed = 0;
private TvServerEventArgs _tvEvent;
private string _tsBufferExtractorSetup;
private static string _isManual = string.Empty; //empty if no client
int _errors = 0;
#endregion
public TvTimeShiftPositionWatcher(TvServerEventArgs eventArgs)
{
_tvEvent = eventArgs;
SetNewChannel(_tvEvent.Card.IdChannel);
}
#region Event handlers
/// <summary>
/// Handles the OnTvServerEvent event fired by the server.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="eventArgs">The <see cref="System.EventArgs"/> the event data.</param>
void events_OnTvServerEvent(object sender, EventArgs eventArgs)
{
TvServerEventArgs tvEvent = (TvServerEventArgs)eventArgs;
if (eventArgs == null || tvEvent == null)
{
return;
}
if ((tvEvent.EventType == TvServerEventType.EndTimeShifting || tvEvent.EventType == TvServerEventType.StartZapChannel)
&& _idChannelToWatch == tvEvent.Card.IdChannel && _tvEvent.User.Name == tvEvent.User.Name)
{
StopTimer();
}
if (tvEvent.EventType == TvServerEventType.RecordingStarted && _idChannelToWatch == tvEvent.Card.IdChannel)
{
int i = 0;
while (i < 100)
{
Log.Debug("TsBufferExtractor: waiting for the signal.");
if (_isManual == _tvEvent.User.Name)
{
break;
}
Thread.Sleep(100);
i++;
}
if (_isManual == _tvEvent.User.Name)
{
_isManual = string.Empty;
CheckRecordingStatus();
SnapshotTimeShiftBuffer();
}
else
{
Log.Debug("TsBufferExtractor: it is not a manual recording or timeout.");
}
}
}
#endregion
#region Public methods
public static string IsManual
{
set {_isManual = value;}
}
public void SetNewChannel(int idChannel)
{
try
{
TvBusinessLayer layer = new TvBusinessLayer();
_tsBufferExtractorSetup = layer.GetSetting("TsBufferExtractorSetup", "A").Value;
_preRecordInterval = Decimal.Parse(layer.GetSetting("preRecordInterval", "5").Value);
_snapshotBufferPosition = -1;
_snapshotBufferFile = string.Empty;
_snapshotBufferId = 0;
Log.Debug("TsBufferExtractor: SetNewChannel({0})", idChannel);
_idChannelToWatch = idChannel;
StartTimer();
}
catch (Exception ex)
{
Log.Error("TsBufferExtractor: Exception {0}", ex.Message);
}
}
#endregion
#region Private methods
private void StopTimer()
{
_timer.Stop();
_timer.Dispose();
ITvServerEvent events = GlobalServiceProvider.Instance.Get<ITvServerEvent>();
events.OnTvServerEvent -= new TvServerEventHandler(events_OnTvServerEvent);
Log.Debug("TsBufferExtractor: Timer stopped on {0}, errors = {1}", _tvEvent.User.Name, _errors);
}
private void _timer_Tick(object sender, EventArgs e)
{
if (_errors >= 10)
{
StopTimer();
}
if (_tsBufferExtractorSetup != "A" && _snapshotBufferPosition == -1)
{
SnapshotTimeShiftBuffer();
Log.Debug("TsBufferExtractor: storing the timeshift position on the channel change.");
}
UpdateTimeShiftReusedStatus();
_secondsElapsed++;
if (_secondsElapsed == 60)
{
_secondsElapsed = 0;
CheckOrUpdateTimeShiftPosition();
}
}
private void StartTimer()
{
Channel chan = Channel.Retrieve(_idChannelToWatch);
if (chan != null && chan.IsRadio)
{
Log.Debug("TsBufferExtractor: IsRadio = True");
return;
}
if (_timer == null)
{
_timer = new System.Timers.Timer();
_timer.Elapsed += new ElapsedEventHandler(_timer_Tick);
_timer.AutoReset = true;
_timer.Interval = 500;
_timer.Start();
try
{
ITvServerEvent events = GlobalServiceProvider.Instance.Get<ITvServerEvent>();
events.OnTvServerEvent += new TvServerEventHandler(events_OnTvServerEvent);
}
catch (Exception ex)
{
Log.Error("TsBufferExtractor exception : {0}", ex);
}
}
Log.Debug("TsBufferExtractor: started on {1}, BufferExtractorSetup = {0}", _tsBufferExtractorSetup, _tvEvent.User.Name);
}
public void CheckRecordingStatus()
{
try
{
if (_tvEvent.Card.IsRecording)
{
int scheduleId = _tvEvent.Card.RecordingScheduleId;
if (scheduleId > 0)
{
Recording rec = Recording.ActiveRecording(scheduleId);
Log.Info("TsBufferExtractor: Detected a started recording on {0}, ProgramName: {1}", _tvEvent.User.Name, rec.Title);
InitiateBufferFilesCopyProcess(rec);
}
}
}
catch (Exception ex)
{
Log.Error("TsBufferExtractor.CheckRecordingStatus exception : {0}", ex);
}
}
private void InitiateBufferFilesCopyProcess(Recording rec)
{
if (_tsBufferExtractorSetup == "A" && _snapshotBufferPosition == -2)
{
Log.Info("TsBufferExtractor: there is no program information, skip the ts buffer copy.");
return;
}
string recordingFilename = rec.FileName;
IUser u = _tvEvent.Card.User;
long bufferId = 0;
Int64 currentPosition = -1;
var layer = new TvBusinessLayer();
Int64 maximumFileSize = Int64.Parse(layer.GetSetting("timeshiftMaxFileSize", "30").Value) * 1000 * 1000;
int maxFiles = Convert.ToInt16(layer.GetSetting("timeshiftMaxFiles", "30").Value);
List<string[]> itemlist = new List<string[]>();
if (RemoteControl.Instance.TimeShiftGetCurrentFilePosition(ref u, ref currentPosition, ref bufferId))
{
string currentFile = RemoteControl.Instance.TimeShiftFileName(ref u) + bufferId.ToString() + ".ts";
if (_snapshotBufferPosition == -2)
{
_snapshotBufferId = bufferId + 1;
Log.Debug("TsBufferExtractor: snapshotBufferPosition was overwritten, the new _snapshotBufferId {0}", _snapshotBufferId);
}
Log.Info("TsBufferExtractor: current TS Position {0}, TS bufferId {1}, snapshotBufferId {2}, recording file {3}",
currentPosition, bufferId, _snapshotBufferId, recordingFilename);
if (_snapshotBufferId < bufferId)
{
Log.Debug("TsBufferExtractor: snapshotBufferId {0}, bufferId {1}", _snapshotBufferId, bufferId);
string nextFile;
for (long i = _snapshotBufferId; i < bufferId; i++)
{
nextFile = RemoteControl.Instance.TimeShiftFileName(ref u) + i + ".ts";
Log.Debug("TsBufferExtractor: nextFile {0}", nextFile);
itemlist.Add(new[] { nextFile, string.Format("{0}", maximumFileSize), recordingFilename });
}
}
else if (_snapshotBufferId > bufferId)
{
{
string nextFile;
for (long i = _snapshotBufferId; i <= maxFiles; i++)
{
nextFile = RemoteControl.Instance.TimeShiftFileName(ref u) + i + ".ts";
Log.Debug("TsBufferExtractor: nextFile {0}", nextFile);
itemlist.Add(new[] { nextFile, string.Format("{0}", maximumFileSize), recordingFilename });
}
if (1 < _bufferId)
{
for (long i = 1; i < _bufferId; i++)
{
nextFile = RemoteControl.Instance.TimeShiftFileName(ref u) + i + ".ts";
Log.Debug("TsBufferExtractor: nextFile {0}", nextFile);
itemlist.Add(new[] { nextFile, string.Format("{0}", maximumFileSize), recordingFilename });
}
}
}
}
itemlist.Add(new[] { currentFile, string.Format("{0}", currentPosition), recordingFilename });
Log.Debug("TsBufferExtractor: currentFile {0}", currentFile);
try
{
Schedule newSchedule = new Schedule(rec.IdChannel, rec.Title, rec.StartTime, DateTime.Now);
newSchedule.PreRecordInterval = 0;
newSchedule.PostRecordInterval = 0;
newSchedule.Persist();
Copyer Copy = new Copyer();
Copy.CopyTimeShiftFile(itemlist, rec, newSchedule);
}
catch (Exception ex)
{
Log.Error("TsBufferExtractor.CopyTimeShiftFile exception : {0}", ex);
}
}
_snapshotBufferPosition = -1;
_snapshotBufferFile = string.Empty;
_snapshotBufferId = 0;
}
private void SnapshotTimeShiftBuffer()
{
IUser u = _tvEvent.Card.User;
if (u == null)
{
Log.Error("TsBufferExtractor.SnapshotTimeShiftBuffer: Snapshot buffer failed. TvHome.Card.User==null");
_errors++;
return;
}
Log.Debug("TsBufferExtractor.SnapshotTimeShiftBuffer: Snapshotting timeshift buffer. User: {0}", _tvEvent.User.Name);
if (_idChannelToWatch == -1 || !_tvEvent.Card.IsTimeShifting)
{
Log.Debug("TsBufferExtractor.SnapshotTimeShiftBuffer: not timeshifting");
_errors++;
return;
}
if (!RemoteControl.Instance.TimeShiftGetCurrentFilePosition(ref u, ref _snapshotBufferPosition, ref _snapshotBufferId))
{
Log.Debug("TsBufferExtractor.SnapshotTimeShiftBuffer: TimeShiftGetCurrentFilePosition failed.");
_errors++;
return;
}
_snapshotBufferFile = RemoteControl.Instance.TimeShiftFileName(ref u) + _snapshotBufferId.ToString() + ".ts";
Log.Info("TsBufferExtractor.SnapshotTimeShiftBuffer: Snapshot done - position: {0}, filename: {1}", _snapshotBufferPosition, _snapshotBufferFile);
}
private void CheckOrUpdateTimeShiftPosition()
{
if (_idChannelToWatch == -1 || !_tvEvent.Card.IsTimeShifting)
{
Log.Debug("TsBufferExtractor: not timeshifting");
_errors++;
return;
}
Channel chan = Channel.Retrieve(_idChannelToWatch);
if (chan == null || chan.CurrentProgram == null)
{
Log.Debug("TsBufferExtractor: no EPG data, returning");
return;
}
if (_tsBufferExtractorSetup != "C")
{
try
{
DateTime current = DateTime.Now;
current = current.AddMinutes((double)_preRecordInterval);
current = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, 0);
DateTime dtProgEnd = chan.CurrentProgram.EndTime;
dtProgEnd = new DateTime(dtProgEnd.Year, dtProgEnd.Month, dtProgEnd.Day, dtProgEnd.Hour, dtProgEnd.Minute, 0);
Log.Debug("TsBufferExtractor: Ch: ({5}) CurrentProgram ({0}) Checking {1} == {2}, _bufferId {3}, _snapshotBufferId {4}, user: {6}", chan.CurrentProgram.Title,
current.ToString("dd.MM.yy HH:mm"), dtProgEnd.ToString("dd.MM.yy HH:mm"), _bufferId, _snapshotBufferId, chan.DisplayName, _tvEvent.User.Name);
if (current == dtProgEnd)
{
Log.Debug("TsBufferExtractor: Next program starts within the configured Pre-Rec interval. Current program: ({0}) ending: {1}", chan.CurrentProgram.Title, chan.CurrentProgram.EndTime.ToString());
SnapshotTimeShiftBuffer();
}
}
catch (Exception ex)
{
Log.Error("TsBufferExtractor.CheckOrUpdateTimeShiftPosition exception : {0}", ex);
}
}
}
private void UpdateTimeShiftReusedStatus()
{
Int64 currentPosition = -1;
_bufferId = GetTimeShiftPosition(ref currentPosition);
if (_snapshotBufferId == _bufferId && _snapshotBufferPosition > currentPosition)
{
_snapshotBufferPosition = -2; //magic number
_snapshotBufferId = 0;
Log.Info("TsBufferExtractor: snapshot buffer is reused on {0}", _tvEvent.User.Name);
}
}
private long GetTimeShiftPosition(ref Int64 currentPosition)
{
if (!_tvEvent.Card.IsTimeShifting)
return 0;
IUser u = _tvEvent.Card.User;
long bufferId = 0;
try
{
if (RemoteControl.Instance.TimeShiftGetCurrentFilePosition(ref u, ref currentPosition, ref bufferId))
{
return bufferId;
}
}
catch
{
Log.Error("TsBufferExtractor: error in GetTimeShiftPosition");
}
return 0;
}
#endregion
}
}