-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
369 lines (314 loc) · 19.6 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dropbox.Api;
using Dropbox.Api.Files;
using ICSharpCode.SharpZipLib.Zip;
namespace DropboxStreamUploader
{
internal class Program
{
static async Task Main(string[] args)
{
try
{
var token = args[0];
var streamUrl = args[1];
var dropboxDirectory = args[2];
if (!IsEndingWithSeparator(dropboxDirectory))
dropboxDirectory += Path.AltDirectorySeparatorChar;
string password = args[3];
var mpegExe = args[4];
var offlineRecordsDirectory = args[5];
string reservedFilePath = Path.Combine(offlineRecordsDirectory, "reserved.tmp");
await DoRecording(null);
await Task.Delay(-1);
async Task DoRecording(DateTime? latestCleanup)
{
Process mpegProcess = null;
var stopReading = new CancellationTokenSource();
try
{
var mpegStart = new ProcessStartInfo(mpegExe, $"-rtsp_transport tcp -i \"{streamUrl}\" -f matroska -c:v copy -c:a copy - ");
mpegStart.UseShellExecute = false;
mpegStart.RedirectStandardOutput = true;
mpegStart.RedirectStandardInput = true;
mpegStart.RedirectStandardError = true;
mpegProcess = Process.Start(mpegStart);
mpegProcess.Exited += (s, a) => stopReading.Cancel();
var mpegSource = new AsyncBufferedReader(mpegProcess.StandardOutput.BaseStream);
_ = mpegSource.Start(1024 * 1024 * 10, stopReading.Token)
.ContinueWith(t =>
{
if (t.Exception != null && !(t.Exception is OperationCanceledException))
{
Console.WriteLine(t.Exception);
}
});
_ = new AsyncBufferedReader(mpegProcess.StandardError.BaseStream)
.Start(1024 * 1024 * 10, stopReading.Token)
.ContinueWith(t =>
{
if (t.Exception != null && !(t.Exception is OperationCanceledException))
{
Console.WriteLine(t.Exception);
}
});
var startedAt = Stopwatch.StartNew();
var fileName = $"video{DateTime.Now:yyyyMMdd-HHmmss}.zip";
string offlineFilePath = Path.Combine(offlineRecordsDirectory, Path.GetFileNameWithoutExtension(fileName) + ".mkv");
Console.WriteLine("Started new recording to " + offlineFilePath);
using (var dropbox = new DropboxClient(token))
{
if (latestCleanup == null || (DateTime.UtcNow - latestCleanup > TimeSpan.FromHours(1)))
{
Console.WriteLine("Cleaning up");
try
{
await dropbox.Files.CreateFolderV2Async(dropboxDirectory.TrimEnd('/'));
}
catch
{
}
var filesToDelete = new HashSet<string>();
try
{
for (var list = await dropbox.Files.ListFolderAsync(dropboxDirectory.TrimEnd('/'), true, limit: 2000);
list != null;
list = list.HasMore ? await dropbox.Files.ListFolderContinueAsync(list.Cursor) : null)
{
foreach (var entry in list.Entries)
{
if (!entry.IsFile) continue;
if (!entry.PathLower.Substring(dropboxDirectory.Length).EndsWith(".zip")) continue;
if ((DateTime.UtcNow - entry.AsFile.ServerModified).TotalHours >= 1)
filesToDelete.Add(entry.PathLower);
}
}
await DeleteFilesBatchAsync();
async Task DeleteFilesBatchAsync()
{
if (filesToDelete.Count > 0)
{
Console.WriteLine($"Deleting files: \n{string.Join("\n", filesToDelete)}");
var j = await dropbox.Files.DeleteBatchAsync(filesToDelete.Select(x => new DeleteArg(x)));
if (j.IsAsyncJobId)
{
for (DeleteBatchJobStatus r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value);
r.IsInProgress;
r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value))
{
await Task.Delay(5000);
}
}
filesToDelete.Clear();
}
}
latestCleanup = DateTime.UtcNow;
}
catch (Exception e)
{
Console.WriteLine("Ignoring cleanup error: " + e);
}
}
if (await mpegProcess.WaitForExitAsync(new CancellationTokenSource(Math.Max(10000 - (int) startedAt.ElapsedMilliseconds, 1)).Token))
throw new Exception("ffmpeg terminated abnormally");
ZipStrings.UseUnicode = true;
ZipStrings.CodePage = 65001;
var entryFactory = new ZipEntryFactory();
byte[] msBuffer = new byte[1000 * 1000 * 50];
int zipBufferSize = 1000 * 1000 * 50;
Stopwatch signalledExitAt = null;
const int ChunkMinIntervalSeconds = 5;
const int ChunkMaxIntervalSeconds = 30;
const int ChunkSize = 1024 * 1024 * 2;
const int SecondsPerFile = 60;
using (var zipWriterUnderlyingStream = new CopyStream())
{
var bufferStream = new MemoryStream(msBuffer);
bufferStream.SetLength(0);
UploadSessionStartResult session = null;
long offset = 0;
FileStream CreateOfflineFileStream()
{
try
{
// we attempt to overwrite same file again and again so it can't be restored
File.Move(reservedFilePath, offlineFilePath);
var f = new FileStream(offlineFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, zipBufferSize);
f.SetLength(0);
return f;
}
catch
{
return new FileStream(offlineFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None, zipBufferSize);
}
}
using (var offlineFileWriter = CreateOfflineFileStream())
{
using (var zipWriter = new ZipOutputStream(zipWriterUnderlyingStream, zipBufferSize)
{ IsStreamOwner = false, Password = password, UseZip64 = UseZip64.On })
{
try
{
zipWriterUnderlyingStream.CopyTo = bufferStream;
zipWriter.SetLevel(0);
var entry = entryFactory.MakeFileEntry("video.mkv", '/' + "video.mkv", false);
entry.AESKeySize = 256;
zipWriter.PutNextEntry(entry);
async Task ExitCheck()
{
if ((signalledExitAt == null) && (startedAt.Elapsed.TotalSeconds > SecondsPerFile || mpegSource.NewDataLength == 0))
{
Console.WriteLine("Signaling exit to ffmpeg");
signalledExitAt = Stopwatch.StartNew();
_ = DoRecording(latestCleanup);
await Task.Delay(1000);
mpegProcess.StandardInput.Write('q');
}
else if (signalledExitAt?.Elapsed.TotalSeconds >= 5 && !mpegProcess.HasExited)
{
try
{
Console.WriteLine("Killing ffmpeg");
stopReading.Cancel();
mpegProcess.Kill();
}
catch
{
}
}
}
var waitingFrom = Stopwatch.StartNew();
while (!mpegProcess.HasExited || mpegSource.NewDataLength > 0)
{
// wait at least this time
await Task.Delay(TimeSpan.FromSeconds(signalledExitAt == null ? ChunkMinIntervalSeconds : 1));
while ((mpegSource.NewDataLength < ChunkSize) && (waitingFrom.Elapsed.TotalSeconds < ChunkMaxIntervalSeconds)
&& !mpegProcess.HasExited
&& signalledExitAt == null)
{
await Task.Delay(100);
await ExitCheck();
}
int read;
do
{
await ExitCheck();
read = mpegSource.Advance();
if (read == 0) break;
Console.WriteLine($"Processing {read} bytes of {offlineFilePath}");
zipWriter.Write(mpegSource.Buffer, 0, read);
zipWriter.Flush();
//bufferStream.WriteTo(offlineFileWriter);
offlineFileWriter.Write(mpegSource.Buffer, 0, read);
offlineFileWriter.Flush(true);
bufferStream.Position = 0;
var length = bufferStream.Length;
if (session == null)
{
session = await AsyncEx.Retry(() =>
{
var copy = new MemoryStream(msBuffer, 0, (int) bufferStream.Length);
return dropbox.Files.UploadSessionStartAsync(new UploadSessionStartArg(), copy);
});
}
else
{
await AsyncEx.Retry(() =>
{
var copy = new MemoryStream(msBuffer, 0, (int) bufferStream.Length);
return dropbox.Files.UploadSessionAppendV2Async(new UploadSessionCursor(session.SessionId, (ulong) offset), false,
copy);
});
}
offset += length;
zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer);
bufferStream.SetLength(0);
} while (mpegSource.NewDataLength >= ChunkSize);
waitingFrom.Restart();
}
}
finally
{
// disposing ZipOutputStream causes writing to bufferStream
if (!bufferStream.CanRead && !bufferStream.CanWrite)
zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer);
try
{
bufferStream.SetLength(0);
zipWriter.CloseEntry();
zipWriter.Finish();
zipWriter.Close();
//bufferStream.WriteTo(offlineFileWriter);
//offlineFileWriter.Flush(true);
}
catch
{
}
}
}
if (session != null) // can be null if no data
{
bufferStream.Position = 0;
var commitInfo = new CommitInfo(Path.Combine(dropboxDirectory, fileName),
WriteMode.Overwrite.Instance,
false,
DateTime.UtcNow);
await AsyncEx.Retry(() =>
{
var copy = new MemoryStream(msBuffer, 0, (int) bufferStream.Length);
return dropbox.Files.UploadSessionFinishAsync(new UploadSessionCursor(session.SessionId, (ulong) offset), commitInfo, copy);
});
}
Console.WriteLine("Recording successfully finished, deleting " + offlineFilePath);
var rng = new Random();
var overwriteBuffer = new byte[ChunkSize];
offlineFileWriter.Position = 0;
long chunks = offlineFileWriter.Length / ChunkSize;
for (int i = 0; i <= chunks; i++)
{
rng.NextBytes(overwriteBuffer);
offlineFileWriter.Write(overwriteBuffer, 0, ChunkSize);
}
}
try
{
File.Move(offlineFilePath, reservedFilePath);
}
catch
{
File.Delete(offlineFilePath);
}
}
}
}
catch (Exception e)
{
if (mpegProcess?.HasExited == false)
mpegProcess.Kill();
stopReading.Cancel();
// redirecting error to normal output
Console.WriteLine(e);
Thread.Sleep(TimeSpan.FromMinutes(1));
_ = DoRecording(latestCleanup);
}
}
}
catch (Exception e)
{
// redirecting error to normal output
Console.WriteLine(e);
throw;
}
}
static bool IsEndingWithSeparator(string s)
{
return (s.Length != 0) && ((s[s.Length - 1] == Path.DirectorySeparatorChar) || (s[s.Length - 1] == Path.AltDirectorySeparatorChar));
}
}
}