-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProjectCompiler.cs
503 lines (406 loc) · 11.9 KB
/
ProjectCompiler.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
using PesMuxer;
using PesMuxer.MuxProject;
using Spp2PgsNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.Remoting;
using System.Threading.Tasks;
using BluraySharp;
using BluraySharp.Common;
using System.Net.Sockets;
using System.ComponentModel;
namespace CsmStudio.ProjectManager.Compile
{
public sealed class ProjectCompiler : IDisposable
{
private object lkMuxer = new object();
private Muxer pesMuxer = null;
private Process muxProc = null;
private Spp2Pgs s2pEncoder = null;
private readonly CompilingSettings settings;
private readonly ICompilingLogger logger;
public ProjectCompiler(CompilingSettings settings, ICompilingLogger logger)
{
logger.AssertNotNull("logger");
try
{
settings.AssertNotNull("settings").Validate();
}
catch(IOException ex)
{
logger.Log(0, ex.Message);
}
this.settings = settings;
this.logger = logger;
InitPgsEncoder();
InitPesMuxer();
}
private void InitPgsEncoder()
{
s2pEncoder = new Spp2Pgs(new MyS2PSettings(settings), new MyS2PLogger(logger));
}
private void InitPesMuxer()
{
var tPmSettings = new MuxerSettings()
{
MuxServerUri = settings.MuxServerUri,
SchemaDir = settings.SchemaDir
};
lock (lkMuxer)
{
Exception tEx = null;
try
{
pesMuxer = new Muxer(tPmSettings); //assume muxer already started.
if (muxProc == null || muxProc.HasExited)
{
Dispose(ref muxProc);
var tProcesses = Process.GetProcessesByName(settings.MuxServerExeFile.Name);
if (tProcesses.Length > 0)
{
muxProc = tProcesses[0];
}
}
return;
}
catch (RemotingException) { }
catch (SocketException) { }
try
{
Dispose(ref muxProc);
ProcessStartInfo tStartInfo = new ProcessStartInfo(settings.MuxServerExeFile.FullName);
tStartInfo.CreateNoWindow = true;
muxProc = Process.Start(tStartInfo);
pesMuxer = new Muxer(tPmSettings); //retry.
}
catch(InvalidOperationException ex)
{
tEx = ex;
}
catch(FileNotFoundException ex)
{
tEx = ex;
}
catch(RemotingException ex)
{
tEx = ex;
}
catch(Win32Exception ex)
{
tEx = ex;
}
if (tEx != null)
{
logger.Log(0, tEx.Message);
}
}
}
private void MuxerProcess_Exited(object sender, EventArgs e)
{
lock (lkMuxer)
{
Dispose(ref muxProc);
Dispose(ref pesMuxer);
}
}
private Muxer GetPesMuxer()
{
lock (lkMuxer)
{
if (pesMuxer == null)
{
InitPesMuxer();
}
object.ReferenceEquals(pesMuxer, null).FalseOrThrow(new NullReferenceException("Muxer not initialized."));
return pesMuxer;
}
}
#region Compiling
private const string PesMuxOutputPath = "MuxTemp.{0}";
private const string PesEncOutputPath = "PesTemp.{0}";
public async Task<bool> Compile(ICompilingProgressReporter reporter, Guid projectId, DirectoryInfo outputDir, params DocumentClipDescriptor[] clips)
{
AssertNotDisposed();
var tPgsNum = clips.Sum(xClip => xClip.Tracks.Count);
var tProgressManager = new CompilingProgressManager(reporter, tPgsNum);
ProjectSettings tProjSettings = new ProjectSettings()
{
OutputDir = outputDir,
TempDir = settings.TempDir.NavigateTo(string.Format(PesMuxOutputPath, projectId))
};
Project tProj = new Project(tProjSettings);
var tPesDir = settings.TempDir.NavigateTo(string.Format(PesEncOutputPath, projectId)).SafeCreate(string.Empty);
var tClipTasks =
(from iClip in clips select CompileDocumentClip(tProgressManager, iClip, tPesDir)).ToArray();
var tPgsEncTask = Task.WhenAll(tClipTasks);
try { await tPgsEncTask; } catch { }
if (tPgsEncTask.Exception != null || reporter.IsCanceled)
{
ReportSummary(reporter, tPgsEncTask.Exception);
return false;
}
tProj.AddClipList(tClipTasks.Select(xClipTask => xClipTask.Result));
var tPesMuxTask = this.GetPesMuxer().Mux(tProj, tProgressManager);
try { await tPesMuxTask; } catch { }
if (tPesMuxTask.Exception != null || reporter.IsCanceled)
{
ReportSummary(reporter, tPesMuxTask.Exception);
return false;
}
ReportSummary(reporter, null);
return true;
}
private void ReportSummary(ICompilingProgressReporter reporter, AggregateException ex)
{
if(ex != null)
{
foreach(var iEx in ex.InnerExceptions)
{
this.logger.Log(iEx);
}
this.logger.Log(128, "Project compiling failed.");
}
else if (reporter.IsCanceled)
{
this.logger.Log(128, "Project compiling canceled.");
}
else
{
this.logger.Log(128, "Project compiled successful.");
}
reporter.OnTaskEnd();
}
private async Task<ClipEntry> CompileDocumentClip(CompilingProgressManager reporter, DocumentClipDescriptor clip, DirectoryInfo pesDir)
{
byte tId = 0;
var tPgsTaskList = new List<Task<PgsEntryDescriptor>>();
foreach (var iTrack in clip.Tracks)
{
tPgsTaskList.Add(Task.Run(
() => CompileTrack(reporter, clip, iTrack, pesDir, Muxer.GetPgsPid(tId++))
));
}
await Task.WhenAll(tPgsTaskList);
TimeSpan tMaxLength = tPgsTaskList.Max(xPgsTask => xPgsTask.Result.Length);
ClipEntry tClipEntry = new ClipEntry(clip.ClipId, clip.InTimeOffset, clip.InTimeOffset + tMaxLength);
foreach (var iPgsTask in tPgsTaskList)
{
var tPgsDesc = iPgsTask.Result;
var tPgs = new PgsEntry(tPgsDesc.Pid, tPgsDesc.PesFile, tPgsDesc.Lang);
tClipEntry.AddPgs(tPgs);
}
return tClipEntry;
}
private PgsEntryDescriptor CompileTrack(CompilingProgressManager reporter, DocumentClipDescriptor clip, EsTrackDescriptor track, DirectoryInfo pesDir, ushort pid)
{
const string PesFileNameFmt = "{0:00000}.{1:x4}.pes";
using (var tPgsStreamServer = new AnonymousPipeServerStream(PipeDirection.Out))
using (var tPgsStream = new AnonymousPipeClientStream(PipeDirection.In, tPgsStreamServer.ClientSafePipeHandle))
using (var tReporter = reporter.CreatePgsProgressReporter())
{
Func<int> tEncodeTaskAction = () =>
{
using (tPgsStreamServer)
{
return EncodePgs(clip, track, tPgsStreamServer, tReporter);
}
};
var tEncodeTask = Task.Run(tEncodeTaskAction);
var tPesFileName = string.Format(PesFileNameFmt, clip.ClipId, pid);
FileInfo tPesFile = pesDir.PickFile(tPesFileName);
Pgs2Pes(tPgsStream, tPesFile);
return new PgsEntryDescriptor(
pid,
tPesFile.FullName,
TimeFromFrameCount(tEncodeTask.Result, clip.Rate),
track.Track.Lang
);
}
}
private int EncodePgs(DocumentClipDescriptor clip, EsTrackDescriptor track, Stream output, Spp2PgsNet.IProgressReporter reporter)
{
int maxFrameCount = 1;
using (var tCtx = s2pEncoder.CreateSubPicProviderContext())
using (var tOutput = s2pEncoder.CreatePgsEncoder(output, clip.Format, clip.Rate))
{
tOutput.RegistAnchor(0);
foreach (var iEsEntry in track)
{
if (iEsEntry == null)
{
continue;
}
using (var tSpp = s2pEncoder.CreateSubPicProvider(tCtx, iEsEntry.Source))
{
var tOffset = (int)FrameCountFromTime(iEsEntry.SyncOffset, clip.Rate);
using (var tAdv =
s2pEncoder.CreateSppFrameStreamAdvisor(
tSpp, clip.Format, clip.Rate, -1, -1,
tOffset, null)
)
{
maxFrameCount = Math.Max(tAdv.LastPossibleImage, tOffset + 1);
using (var tInput = s2pEncoder.CreateFrameStream(tSpp, tAdv))
{
s2pEncoder.Encode(tInput, tOutput, reporter);
}
}
}
}
tOutput.FlushAnchor();
}
return maxFrameCount;
}
#region Pgs2Pes
private static ulong ReadBE(byte[] tBuffer, int index, byte length)
{
var tByteIndex = (index >> 3);
var tShift = (sbyte)(length - (tByteIndex << 3) + index);
ulong tMaskAll = unchecked(0UL - 1);
tMaskAll = ~(tMaskAll << length);
ulong tRet = 0UL;
while ((tShift -= 8) >= 0)
{
ulong tByte = tBuffer[tByteIndex++];
tRet |= (tByte << tShift);
}
tRet |= (((ulong)tBuffer[tByteIndex++]) >> (-tShift));
return tRet & tMaskAll;
}
private static void WriteBE(byte[] tBuffer, int index, byte length, ulong value)
{
var tByteIndex = (index >> 3);
var tShift = (sbyte)(length + index - (tByteIndex << 3));
ulong tMaskAll = unchecked(0UL - 1);
tMaskAll = ~(tMaskAll << length);
byte tMask = 0;
value &= tMaskAll;
while ((tShift -= 8) >= 0)
{
tMask = (byte)(tMaskAll >> tShift);
tBuffer[tByteIndex] &= (byte)~tMask;
tBuffer[tByteIndex] |= (byte)(value >> tShift);
tByteIndex++;
}
tMask = (byte)(tMaskAll << -tShift);
tBuffer[tByteIndex] &= (byte)~tMask;
tBuffer[tByteIndex] |= (byte)(value << -tShift);
}
private static int ForceRead(Stream pgs, byte[] buffer, int offset, int count)
{
int tRead = 0;
while(tRead < count)
{
int tReadLen = pgs.Read(buffer, offset + tRead, count - tRead);
if (tReadLen == 0) break;
tRead += tReadLen;
}
return tRead;
}
private static void Pgs2Pes(Stream pgs, FileInfo pesFile)
{
using (FileStream tPes = pesFile.Create())
using (FileStream tMui = new FileStream(pesFile.FullName + ".mui", FileMode.Create))
{
byte[] buffer = new byte[65536];
WriteBE(buffer, 0, 32, 3);
tMui.Write(buffer, 0, 4); //file header;
long tPtsOffset = 54000000;
int tReadLen = 0;
for (;;)
{
tReadLen = ForceRead(pgs, buffer, 0, 13);
if (tReadLen != 13 || buffer[0] != 'P' || buffer[1] != 'G') break;
uint tPts = (uint)((long)ReadBE(buffer, 16, 32) + tPtsOffset);
uint tDts = (uint)((long)ReadBE(buffer, 48, 32) + tPtsOffset);
byte tType = (byte)ReadBE(buffer, 80, 8);
int tLen = (int)ReadBE(buffer, 88, 16);
WriteBE(buffer, 0, 8, tType);
WriteBE(buffer, 8, 32, (ulong)(tLen + 3));
WriteBE(buffer, 40, 33, (ulong)tDts);
WriteBE(buffer, 73, 33, (ulong)tPts);
WriteBE(buffer, 106, 6, 0);
tMui.Write(buffer, 0, 14);
WriteBE(buffer, 0, 8, tType);
WriteBE(buffer, 8, 16, (ulong)tLen);
tReadLen = ForceRead(pgs, buffer, 3, tLen);
if (tReadLen != tLen) break;
tPes.Write(buffer, 0, tLen + 3);
}
Array.Clear(buffer, 0, 14);
WriteBE(buffer, 0, 8, 0xff);
tMui.Write(buffer, 0, 14);
}
}
#endregion
private static uint FrameCountFromTime(TimeSpan syncOffset, BdViFrameRate rate)
{
return Convert.ToUInt32(rate.ToDouble() * syncOffset.TotalSeconds);
}
private static TimeSpan TimeFromFrameCount(int frames, BdViFrameRate rate)
{
return TimeSpan.FromSeconds(frames / rate.ToDouble());
}
#endregion Compiling
#region IDisposable
private bool isDisposed = false;
private void AssertNotDisposed()
{
isDisposed.FalseOrThrow(new ObjectDisposedException("ProjectCompiler"));
}
private static void Dispose<T>(ref T managedRes)
where T : class, IDisposable
{
if (managedRes != null)
{
managedRes.Dispose();
managedRes = null;
}
}
public void Dispose()
{
if (!isDisposed)
{
lock (lkMuxer)
{
Dispose(ref pesMuxer);
Dispose(ref muxProc);
}
Dispose(ref s2pEncoder);
isDisposed = true;
}
GC.SuppressFinalize(this);
}
#endregion
#region S2P callbacks
class MyS2PSettings : IS2PSettings
{
private readonly CompilingSettings settings;
public MyS2PSettings(CompilingSettings settings)
{
this.settings = settings;
}
public bool IsForcingTmtCompat { get { return false; } }
public ulong MaxCachingSize { get { return 1UL << 32; } }
public int MaxImageBlockSize { get { return 0; } }
public string TempOutputPath { get { return settings.TempDir.FullName; } }
}
class MyS2PLogger : IS2PLogger
{
private readonly ICompilingLogger logger;
public MyS2PLogger(ICompilingLogger logger)
{
this.logger = logger;
}
public void Vlog(int level, string msg)
{
logger.Log(level, msg);
}
}
#endregion
}
}