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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LibScan.cs" company="HandBrake Project (http://handbrake.fr)">
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
// Scan a Source
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.Services.Scan
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Media.Imaging;
using HandBrake.ApplicationServices.Interop;
using HandBrake.ApplicationServices.Interop.EventArgs;
using HandBrake.ApplicationServices.Interop.HbLib;
using HandBrake.ApplicationServices.Interop.Interfaces;
using HandBrake.ApplicationServices.Interop.Json.Scan;
using HandBrake.ApplicationServices.Interop.Model;
using HandBrake.ApplicationServices.Interop.Model.Preview;
using HandBrake.ApplicationServices.Model;
using HandBrake.ApplicationServices.Utilities;
using HandBrakeWPF.Properties;
using HandBrakeWPF.Services.Encode.Model;
using HandBrakeWPF.Services.Encode.Model.Models;
using HandBrakeWPF.Services.Scan.EventArgs;
using HandBrakeWPF.Services.Scan.Interfaces;
using HandBrakeWPF.Services.Scan.Model;
using HandBrakeWPF.Utilities;
using Chapter = HandBrakeWPF.Services.Scan.Model.Chapter;
using ScanProgressEventArgs = HandBrake.ApplicationServices.Interop.EventArgs.ScanProgressEventArgs;
using Subtitle = HandBrakeWPF.Services.Scan.Model.Subtitle;
using Title = HandBrakeWPF.Services.Scan.Model.Title;
/// <summary>
/// Scan a Source
/// </summary>
public class LibScan : IScan
{
#region Private Variables
/// <summary>
/// Lock for the log file
/// </summary>
static readonly object LogLock = new object();
/// <summary>
/// Log data from HandBrakeInstance
/// </summary>
private readonly StringBuilder logging;
/// <summary>
/// The Log File Header
/// </summary>
private readonly StringBuilder header;
/// <summary>
/// The Current source scan path.
/// </summary>
private string currentSourceScanPath;
/// <summary>
/// The log dir.
/// </summary>
private static string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
/// <summary>
/// The dvd info path.
/// </summary>
private string dvdInfoPath = Path.Combine(logDir, string.Format("last_scan_log{0}.txt", GeneralUtilities.ProcessId));
/// <summary>
/// The scan log.
/// </summary>
private StreamWriter scanLog;
/// <summary>
/// LibHB Instance
/// </summary>
private IHandBrakeInstance instance;
/// <summary>
/// The post scan operation.
/// </summary>
private Action<bool, Source> postScanOperation;
/// <summary>
/// Global to handle cancelled scans.
/// </summary>
private bool isCancelled = false;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="LibScan"/> class.
/// </summary>
public LibScan()
{
this.logging = new StringBuilder();
this.header = GeneralUtilities.CreateLogHeader();
this.IsScanning = false;
}
#region Events
/// <summary>
/// Scan has Started
/// </summary>
public event EventHandler ScanStarted;
/// <summary>
/// Scan has completed
/// </summary>
public event ScanCompletedStatus ScanCompleted;
/// <summary>
/// Encode process has progressed
/// </summary>
public event ScanProgessStatus ScanStatusChanged;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether IsScanning.
/// </summary>
public bool IsScanning { get; private set; }
/// <summary>
/// Gets ActivityLog.
/// </summary>
public string ActivityLog
{
get
{
string noLog = "There is no log information to display." + Environment.NewLine + Environment.NewLine
+ "This window will only display logging information after you have scanned a source." + Environment.NewLine
+ Environment.NewLine + "You can find previous log files in the log directory or by clicking the 'Open Log Directory' button above.";
return string.IsNullOrEmpty(this.logging.ToString()) ? noLog : this.header + this.logging.ToString();
}
}
#endregion
#region Public Methods
/// <summary>
/// Scan a Source Path.
/// Title 0: scan all
/// </summary>
/// <param name="sourcePath">
/// Path to the file to scan
/// </param>
/// <param name="title">
/// int title number. 0 for scan all
/// </param>
/// <param name="postAction">
/// The post Action.
/// </param>
/// <param name="configuraiton">
/// The configuraiton.
/// </param>
public void Scan(string sourcePath, int title, Action<bool, Source> postAction, HBConfiguration configuraiton)
{
// Try to cleanup any previous scan instances.
if (this.instance != null)
{
try
{
lock (LogLock)
{
this.scanLog.Close();
this.scanLog.Dispose();
this.scanLog = null;
}
this.instance.Dispose();
}
catch (Exception)
{
// Do Nothing
}
}
// Handle the post scan operation.
this.postScanOperation = postAction;
// Clear down the logging
this.logging.Clear();
try
{
// Make we don't pick up a stale last_scan_log_xyz.txt (and that we have rights to the file)
if (File.Exists(this.dvdInfoPath))
{
File.Delete(this.dvdInfoPath);
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
if (!Directory.Exists(Path.GetDirectoryName(this.dvdInfoPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(this.dvdInfoPath));
}
// Create a new scan log.
this.scanLog = new StreamWriter(this.dvdInfoPath);
// Create a new HandBrake Instance.
HandBrakeUtils.MessageLogged += this.HandBrakeInstanceMessageLogged;
HandBrakeUtils.ErrorLogged += this.HandBrakeInstanceErrorLogged;
this.instance = HandBrakeInstanceManager.GetScanInstance(configuraiton.Verbosity);
this.instance.ScanProgress += this.InstanceScanProgress;
this.instance.ScanCompleted += this.InstanceScanCompleted;
// Start the scan on a back
this.ScanSource(sourcePath, title, configuraiton.PreviewScanCount, configuraiton);
}
/// <summary>
/// Kill the scan
/// </summary>
public void Stop()
{
try
{
this.ServiceLogMessage("Stopping Scan.");
this.IsScanning = false;
this.instance.StopScan();
lock (LogLock)
{
if (this.scanLog != null)
{
this.scanLog.Close();
this.scanLog.Dispose();
this.scanLog = null;
}
}
}
catch (Exception exc)
{
this.isCancelled = false;
this.ScanCompleted?.Invoke(this, new ScanCompletedEventArgs(false, exc, Resources.ScanService_ScanStopFailed, null));
// Do Nothing.
}
}
/// <summary>
/// Cancel the current scan.
/// </summary>
public void Cancel()
{
this.isCancelled = true;
this.Stop();
}
/// <summary>
/// Get a Preview image for the current job and preview number.
/// </summary>
/// <param name="job">
/// The job.
/// </param>
/// <param name="preview">
/// The preview.
/// </param>
/// <param name="configuraiton">
/// The configuraiton.
/// </param>
/// <returns>
/// The <see cref="BitmapImage"/>.
/// </returns>
public BitmapImage GetPreview(EncodeTask job, int preview, HBConfiguration configuraiton)
{
if (this.instance == null)
{
return null;
}
BitmapImage bitmapImage = null;
try
{
PreviewSettings settings = new PreviewSettings
{
Cropping = new Cropping(job.Cropping),
MaxWidth = job.MaxWidth ?? 0,
MaxHeight = job.MaxHeight ?? 0,
KeepDisplayAspect = job.KeepDisplayAspect,
TitleNumber = job.Title,
Anamorphic = job.Anamorphic,
Modulus = job.Modulus,
Width = job.Width ?? 0,
Height = job.Height ?? 0,
PixelAspectX = job.PixelAspectX,
PixelAspectY = job.PixelAspectY
};
bitmapImage = this.instance.GetPreview(settings, preview);
}
catch (AccessViolationException e)
{
Console.WriteLine(e);
}
return bitmapImage;
}
#endregion
#region Private Methods
/// <summary>
/// Start a scan for a given source path and title
/// </summary>
/// <param name="sourcePath">
/// Path to the source file
/// </param>
/// <param name="title">
/// the title number to look at
/// </param>
/// <param name="previewCount">
/// The preview Count.
/// </param>
/// <param name="configuraiton">
/// The configuraiton.
/// </param>
private void ScanSource(object sourcePath, int title, int previewCount, HBConfiguration configuraiton)
{
try
{
this.logging.Clear();
string source = sourcePath.ToString().EndsWith("\\") ? string.Format("\"{0}\\\\\"", sourcePath.ToString().TrimEnd('\\'))
: "\"" + sourcePath + "\"";
this.currentSourceScanPath = source;
this.IsScanning = true;
TimeSpan minDuration = TimeSpan.FromSeconds(configuraiton.MinScanDuration);
HandBrakeUtils.SetDvdNav(!configuraiton.IsDvdNavDisabled);
this.ServiceLogMessage("Starting Scan ...");
this.instance.StartScan(sourcePath.ToString(), previewCount, minDuration, title != 0 ? title : 0);
if (this.ScanStarted != null)
this.ScanStarted(this, System.EventArgs.Empty);
}
catch (Exception exc)
{
this.ServiceLogMessage("Scan Failed ..." + Environment.NewLine + exc);
this.Stop();
if (this.ScanCompleted != null)
this.ScanCompleted(this, new ScanCompletedEventArgs(false, exc, "An Error has occured in ScanService.ScanSource()", null));
}
}
#endregion
#region HandBrakeInstance Event Handlers
/// <summary>
/// Scan Completed Event Handler
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The EventArgs.
/// </param>
private void InstanceScanCompleted(object sender, System.EventArgs e)
{
this.ServiceLogMessage("Scan Finished ...");
bool cancelled = this.isCancelled;
this.isCancelled = false;
// Write the log file out before we start processing incase we crash.
try
{
if (this.scanLog != null)
{
this.scanLog.Flush();
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
HandBrakeUtils.MessageLogged -= this.HandBrakeInstanceMessageLogged;
HandBrakeUtils.ErrorLogged -= this.HandBrakeInstanceErrorLogged;
// TODO -> Might be a better place to fix this.
string path = this.currentSourceScanPath;
if (this.currentSourceScanPath.Contains("\""))
{
path = this.currentSourceScanPath.Trim('\"');
}
// Process into internal structures.
Source sourceData = null;
if (this.instance?.Titles != null)
{
sourceData = new Source { Titles = ConvertTitles(this.instance.Titles), ScanPath = path };
}
this.IsScanning = false;
if (this.postScanOperation != null)
{
try
{
this.postScanOperation(true, sourceData);
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
this.postScanOperation = null; // Reset
}
else
{
this.ScanCompleted?.Invoke(this, new ScanCompletedEventArgs(cancelled, null, string.Empty, sourceData));
}
}
/// <summary>
/// Scan Progress Event Handler
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The EventArgs.
/// </param>
private void InstanceScanProgress(object sender, ScanProgressEventArgs e)
{
if (this.ScanStatusChanged != null)
{
HandBrakeWPF.Services.Scan.EventArgs.ScanProgressEventArgs eventArgs =
new HandBrakeWPF.Services.Scan.EventArgs.ScanProgressEventArgs
{
CurrentTitle = e.CurrentTitle,
Titles = e.Titles,
Percentage = Math.Round((decimal)e.Progress * 100, 0)
};
this.ScanStatusChanged(this, eventArgs);
}
}
/// <summary>
/// Log a message
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The MessageLoggedEventArgs.
/// </param>
private void HandBrakeInstanceErrorLogged(object sender, MessageLoggedEventArgs e)
{
this.LogMessage(e.Message);
}
/// <summary>
/// Log a message
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The MessageLoggedEventArgs.
/// </param>
private void HandBrakeInstanceMessageLogged(object sender, MessageLoggedEventArgs e)
{
this.LogMessage(e.Message);
}
/// <summary>
/// Convert Interop Title objects to App Services Title object
/// </summary>
/// <param name="titles">
/// The titles.
/// </param>
/// <returns>
/// The convert titles.
/// </returns>
internal static List<Title> ConvertTitles(JsonScanObject titles)
{
List<Title> titleList = new List<Title>();
foreach (SourceTitle title in titles.TitleList)
{
Title converted = new Title
{
TitleNumber = title.Index,
Duration = new TimeSpan(0, title.Duration.Hours, title.Duration.Minutes, title.Duration.Seconds),
Resolution = new Size(title.Geometry.Width, title.Geometry.Height),
AngleCount = title.AngleCount,
ParVal = new Size(title.Geometry.PAR.Num, title.Geometry.PAR.Den),
AutoCropDimensions = new Cropping
{
Top = title.Crop[0],
Bottom = title.Crop[1],
Left = title.Crop[2],
Right = title.Crop[3]
},
Fps = ((double)title.FrameRate.Num) / title.FrameRate.Den,
SourceName = title.Path,
MainTitle = titles.MainFeature == title.Index,
Playlist = title.Type == 1 ? string.Format(" {0:d5}.MPLS", title.Playlist).Trim() : null,
FramerateNumerator = title.FrameRate.Num,
FramerateDenominator = title.FrameRate.Den
};
int currentTrack = 1;
foreach (SourceChapter chapter in title.ChapterList)
{
string chapterName = !string.IsNullOrEmpty(chapter.Name) ? chapter.Name : string.Empty;
converted.Chapters.Add(new Chapter(currentTrack, chapterName, new TimeSpan(chapter.Duration.Hours, chapter.Duration.Minutes, chapter.Duration.Seconds)));
currentTrack++;
}
int currentAudioTrack = 1;
foreach (SourceAudioTrack track in title.AudioList)
{
converted.AudioTracks.Add(new Audio(currentAudioTrack, track.Language, track.LanguageCode, track.Description, string.Empty, track.SampleRate, track.BitRate));
currentAudioTrack++;
}
int currentSubtitleTrack = 1;
foreach (SourceSubtitleTrack track in title.SubtitleList)
{
SubtitleType convertedType = new SubtitleType();
switch (track.Source)
{
case 0:
convertedType = SubtitleType.VobSub;
break;
case 4:
convertedType = SubtitleType.UTF8Sub;
break;
case 5:
convertedType = SubtitleType.TX3G;
break;
case 6:
convertedType = SubtitleType.SSA;
break;
case 1:
convertedType = SubtitleType.SRT;
break;
case 2:
convertedType = SubtitleType.CC;
break;
case 3:
convertedType = SubtitleType.CC;
break;
case 7:
convertedType = SubtitleType.PGS;
break;
}
bool canBurn = HBFunctions.hb_subtitle_can_burn(track.Source) > 0;
bool canSetForcedOnly = HBFunctions.hb_subtitle_can_force(track.Source) > 0;
converted.Subtitles.Add(new Subtitle(track.Source, currentSubtitleTrack, track.Language, track.LanguageCode, convertedType, canBurn, canSetForcedOnly));
currentSubtitleTrack++;
}
titleList.Add(converted);
}
return titleList;
}
/// <summary>
/// The log message.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
private void LogMessage(string message)
{
lock (LogLock)
{
if (this.scanLog != null)
{
this.scanLog.WriteLine(message);
}
this.logging.AppendLine(message);
}
}
/// <summary>
/// The service log message.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
protected void ServiceLogMessage(string message)
{
this.LogMessage(string.Format("# {0}", message));
}
#endregion
}
}
|