summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrake.ApplicationServices
diff options
context:
space:
mode:
authorsr55 <[email protected]>2015-01-31 15:19:14 +0000
committersr55 <[email protected]>2015-01-31 15:19:14 +0000
commit6d57e42b6b2cc38cf256f2970b23b94121e49479 (patch)
tree6841b6c50f50b6ac34bfa9dba954f959f030b480 /win/CS/HandBrake.ApplicationServices
parenta4416e99f06e31e1da8767d071e882f32c5a4e67 (diff)
WinGui: Remove a bunch of CLI handling code.
git-svn-id: svn://svn.handbrake.fr/HandBrake/trunk@6840 b64f7644-9d1e-0410-96f1-a4d463321fa5
Diffstat (limited to 'win/CS/HandBrake.ApplicationServices')
-rw-r--r--win/CS/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj2
-rw-r--r--win/CS/HandBrake.ApplicationServices/Isolation/BackgroundServiceConnector.cs15
-rw-r--r--win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeBase.cs37
-rw-r--r--win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeService.cs332
-rw-r--r--win/CS/HandBrake.ApplicationServices/Services/Encode/Interfaces/IEncode.cs11
-rw-r--r--win/CS/HandBrake.ApplicationServices/Services/Encode/LibEncode.cs21
-rw-r--r--win/CS/HandBrake.ApplicationServices/Services/Scan/LibScan.cs9
-rw-r--r--win/CS/HandBrake.ApplicationServices/Utilities/GeneralUtilities.cs6
-rw-r--r--win/CS/HandBrake.ApplicationServices/Utilities/QueryGeneratorUtility.cs1059
9 files changed, 35 insertions, 1457 deletions
diff --git a/win/CS/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj b/win/CS/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj
index 63844f7ab..e3436d19f 100644
--- a/win/CS/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj
+++ b/win/CS/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj
@@ -159,7 +159,6 @@
</Compile>
<Compile Include="ServicesWindsorInstaller.cs" />
<Compile Include="Services\Encode\EncodeBase.cs" />
- <Compile Include="Services\Encode\EncodeService.cs" />
<Compile Include="Services\Encode\Interfaces\IEncode.cs" />
<Compile Include="Services\Interfaces\IQueueProcessor.cs" />
<Compile Include="Services\Scan\Interfaces\IScan.cs" />
@@ -169,7 +168,6 @@
<Compile Include="Utilities\CharCodesUtilities.cs" />
<Compile Include="Utilities\GeneralUtilities.cs" />
<Compile Include="Utilities\LanguageUtilities.cs" />
- <Compile Include="Utilities\QueryGeneratorUtility.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
diff --git a/win/CS/HandBrake.ApplicationServices/Isolation/BackgroundServiceConnector.cs b/win/CS/HandBrake.ApplicationServices/Isolation/BackgroundServiceConnector.cs
index 5a1c69c72..0fa7c2474 100644
--- a/win/CS/HandBrake.ApplicationServices/Isolation/BackgroundServiceConnector.cs
+++ b/win/CS/HandBrake.ApplicationServices/Isolation/BackgroundServiceConnector.cs
@@ -4,7 +4,7 @@
// </copyright>
// <summary>
// Background Service Connector.
-// HandBrake has the ability to connect to a service app that will control HandBrakeCLI or Libhb.
+// HandBrake has the ability to connect to a service app that will control Libhb.
// This acts as process isolation.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
@@ -16,14 +16,13 @@ namespace HandBrake.ApplicationServices.Isolation
using System.ServiceModel;
using System.Threading;
- using HandBrake.ApplicationServices.EventArgs;
using HandBrake.ApplicationServices.Exceptions;
using HandBrake.ApplicationServices.Services.Encode.EventArgs;
using HandBrake.ApplicationServices.Services.Interfaces;
/// <summary>
/// Background Service Connector.
- /// HandBrake has the ability to connect to a service app that will control HandBrakeCLI or Libhb.
+ /// HandBrake has the ability to connect to a service app that will control Libhb.
/// This acts as process isolation.
/// </summary>
public class BackgroundServiceConnector : IHbServiceCallback, IDisposable
@@ -83,9 +82,9 @@ namespace HandBrake.ApplicationServices.Isolation
ProcessStartInfo processStartInfo = new ProcessStartInfo(
"HandBrake.Server.exe", port)
{
- UseShellExecute = false,
- CreateNoWindow = true,
- RedirectStandardOutput = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
};
backgroundProcess = new Process { StartInfo = processStartInfo };
@@ -101,8 +100,8 @@ namespace HandBrake.ApplicationServices.Isolation
try
{
pipeFactory = new DuplexChannelFactory<IServerService>(
- new InstanceContext(this),
- new NetTcpBinding(),
+ new InstanceContext(this),
+ new NetTcpBinding(),
new EndpointAddress(string.Format("net.tcp://127.0.0.1:{0}/IHbService", port)));
// Connect and Subscribe to the Server
diff --git a/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeBase.cs b/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeBase.cs
index 8737ba64f..9c5c9f7bd 100644
--- a/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeBase.cs
+++ b/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeBase.cs
@@ -10,7 +10,6 @@
namespace HandBrake.ApplicationServices.Services.Encode
{
using System;
- using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
@@ -21,7 +20,6 @@ namespace HandBrake.ApplicationServices.Services.Encode
using HandBrake.ApplicationServices.Model;
using HandBrake.ApplicationServices.Services.Encode.EventArgs;
using HandBrake.ApplicationServices.Services.Encode.Interfaces;
- using HandBrake.ApplicationServices.Services.Encode.Model;
using HandBrake.ApplicationServices.Utilities;
/// <summary>
@@ -59,19 +57,19 @@ namespace HandBrake.ApplicationServices.Services.Encode
public EncodeBase()
{
this.logBuffer = new StringBuilder();
- this.header = GeneralUtilities.CreateCliLogHeader();
+ this.header = GeneralUtilities.CreateLogHeader();
this.LogIndex = 0;
}
#region Events
/// <summary>
- /// Fires when a new CLI QueueTask starts
+ /// Fires when a new QueueTask starts
/// </summary>
public event EventHandler EncodeStarted;
/// <summary>
- /// Fires when a CLI QueueTask finishes.
+ /// Fires when a QueueTask finishes.
/// </summary>
public event EncodeCompletedStatus EncodeCompleted;
@@ -83,6 +81,7 @@ namespace HandBrake.ApplicationServices.Services.Encode
#endregion
#region Properties
+
/// <summary>
/// Gets or sets a value indicating whether IsEncoding.
/// </summary>
@@ -236,7 +235,7 @@ namespace HandBrake.ApplicationServices.Services.Encode
}
/// <summary>
- /// Pase the CLI status output (from standard output)
+ /// Pase the status output (from standard output)
/// </summary>
/// <param name="encodeStatus">
/// The encode Status.
@@ -252,7 +251,7 @@ namespace HandBrake.ApplicationServices.Services.Encode
try
{
Match m = Regex.Match(
- encodeStatus,
+ encodeStatus,
@"^Encoding: task ([0-9]*) of ([0-9]*), ([0-9]*\.[0-9]*) %( \(([0-9]*\.[0-9]*) fps, avg ([0-9]*\.[0-9]*) fps, ETA ([0-9]{2})h([0-9]{2})m([0-9]{2})s\))?");
if (m.Success)
@@ -278,16 +277,16 @@ namespace HandBrake.ApplicationServices.Services.Encode
EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
{
- AverageFrameRate = avgFps,
- CurrentFrameRate = currentFps,
+ AverageFrameRate = avgFps,
+ CurrentFrameRate = currentFps,
EstimatedTimeLeft =
Converters.EncodeToTimespan(
- remaining),
- PercentComplete = percent,
- Task = currentTask,
- TaskCount = totalTasks,
+ remaining),
+ PercentComplete = percent,
+ Task = currentTask,
+ TaskCount = totalTasks,
ElapsedTime =
- DateTime.Now - startTime,
+ DateTime.Now - startTime,
};
return eventArgs;
@@ -319,14 +318,8 @@ namespace HandBrake.ApplicationServices.Services.Encode
try
{
- string query = QueryGeneratorUtility.GenerateQuery(new EncodeTask(encodeQueueTask.Task), encodeQueueTask.Configuration);
this.logBuffer = new StringBuilder();
- if (!isLibhb)
- {
- this.logBuffer.AppendLine(String.Format("CLI Query: {0}", query));
- }
-
this.logBuffer.AppendLine();
// Clear the current Encode Logs)
@@ -344,10 +337,6 @@ namespace HandBrake.ApplicationServices.Services.Encode
{
this.fileWriter = new StreamWriter(logFile) { AutoFlush = true };
this.fileWriter.WriteLine(this.header);
- if (!isLibhb)
- {
- this.fileWriter.WriteLine("CLI Query: {0}", query);
- }
this.fileWriter.WriteLine();
}
}
diff --git a/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeService.cs b/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeService.cs
deleted file mode 100644
index 1aaa0d301..000000000
--- a/win/CS/HandBrake.ApplicationServices/Services/Encode/EncodeService.cs
+++ /dev/null
@@ -1,332 +0,0 @@
-// --------------------------------------------------------------------------------------------------------------------
-// <copyright file="EncodeService.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>
-// Class which handles the CLI
-// </summary>
-// --------------------------------------------------------------------------------------------------------------------
-
-namespace HandBrake.ApplicationServices.Services.Encode
-{
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Windows.Forms;
-
- using HandBrake.ApplicationServices.Exceptions;
- using HandBrake.ApplicationServices.Model;
- using HandBrake.ApplicationServices.Services.Encode.EventArgs;
- using HandBrake.ApplicationServices.Services.Encode.Interfaces;
- using HandBrake.ApplicationServices.Services.Encode.Model;
- using HandBrake.ApplicationServices.Utilities;
-
- /// <summary>
- /// Class which handles the CLI
- /// </summary>
- public class EncodeService : EncodeBase, IEncode
- {
- #region Private Variables
-
- /// <summary>
- /// Gets the Process ID
- /// </summary>
- private int processId;
-
- /// <summary>
- /// The Start time of the current Encode;
- /// </summary>
- private DateTime startTime;
-
- /// <summary>
- /// The Current Task
- /// </summary>
- private QueueTask currentTask;
-
- /// <summary>
- /// The init shutdown.
- /// </summary>
- private bool initShutdown;
-
- #endregion
-
- #region Properties
-
- /// <summary>
- /// Gets or sets The HB Process
- /// </summary>
- protected Process HbProcess { get; set; }
-
- /// <summary>
- /// Gets a value indicating whether can pause.
- /// </summary>
- public bool CanPause
- {
- get
- {
- return false;
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether is pasued.
- /// </summary>
- public bool IsPasued { get; private set; }
-
- #endregion
-
- #region Public Methods
-
- /// <summary>
- /// Execute a HandBrakeCLI process.
- /// This should only be called from the UI thread.
- /// </summary>
- /// <param name="encodeQueueTask">
- /// The encodeQueueTask.
- /// </param>
- public void Start(QueueTask encodeQueueTask)
- {
- try
- {
- if (this.IsEncoding)
- {
- throw new GeneralApplicationException("HandBrake is already encodeing.", "Please try again in a minute", null);
- }
-
- this.IsEncoding = true;
- this.currentTask = encodeQueueTask;
-
- try
- {
- this.SetupLogging(this.currentTask, false);
- }
- catch (Exception)
- {
- this.IsEncoding = false;
- throw;
- }
-
- // Make sure the path exists, attempt to create it if it doesn't
- this.VerifyEncodeDestinationPath(this.currentTask);
-
- string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
-
- // TODO tidy this code up, it's kinda messy.
- string query = this.currentTask.Task.IsPreviewEncode
- ? QueryGeneratorUtility.GeneratePreviewQuery(
- new EncodeTask(this.currentTask.Task),
- encodeQueueTask.Configuration,
- this.currentTask.Task.PreviewEncodeDuration.HasValue ? this.currentTask.Task.PreviewEncodeDuration.Value : 0,
- this.currentTask.Task.PreviewEncodeStartAt.HasValue ? this.currentTask.Task.PreviewEncodeStartAt.Value : 0)
- : QueryGeneratorUtility.GenerateQuery(new EncodeTask(this.currentTask.Task), encodeQueueTask.Configuration);
-
- ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, query)
- {
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- CreateNoWindow = true
- };
-
- this.HbProcess = new Process { StartInfo = cliStart };
-
- this.HbProcess.Start();
-
- this.startTime = DateTime.Now;
-
- this.HbProcess.ErrorDataReceived += this.HbProcErrorDataReceived;
- this.HbProcess.BeginErrorReadLine();
-
- this.HbProcess.OutputDataReceived += this.HbProcess_OutputDataReceived;
- this.HbProcess.BeginOutputReadLine();
-
- this.processId = this.HbProcess.Id;
-
- // Set the process Priority
- if (this.processId != -1)
- {
- this.HbProcess.EnableRaisingEvents = true;
- this.HbProcess.Exited += this.HbProcessExited;
- }
-
- // Set the Process Priority
- switch (encodeQueueTask.Configuration.ProcessPriority)
- {
- case "Realtime":
- this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
- break;
- case "High":
- this.HbProcess.PriorityClass = ProcessPriorityClass.High;
- break;
- case "Above Normal":
- this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
- break;
- case "Normal":
- this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
- break;
- case "Low":
- this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
- break;
- default:
- this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
- break;
- }
-
- // Fire the Encode Started Event
- this.InvokeEncodeStarted(System.EventArgs.Empty);
- }
- catch (Exception exc)
- {
- encodeQueueTask.Status = QueueItemStatus.Error;
- this.IsEncoding = false;
- this.InvokeEncodeCompleted(
- new EncodeCompletedEventArgs(
- false, exc, "An Error occured when trying to encode this source. ", this.currentTask.Task.Destination));
- throw;
- }
- }
-
- /// <summary>
- /// The pause.
- /// </summary>
- /// <exception cref="NotImplementedException">
- /// This feature is not available for CLI based encoding.
- /// </exception>
- public void Pause()
- {
- throw new NotImplementedException("This feature is not available for CLI based encoding.");
- }
-
- /// <summary>
- /// The resume.
- /// </summary>
- /// <exception cref="NotImplementedException">
- /// This feature is not available for CLI based encoding.
- /// </exception>
- public void Resume()
- {
- throw new NotImplementedException("This feature is not available for CLI based encoding.");
- }
-
- /// <summary>
- /// Kill the CLI process
- /// </summary>
- public override void Stop()
- {
- try
- {
- if (this.HbProcess != null && !this.HbProcess.HasExited)
- {
- this.HbProcess.Kill();
- }
- }
- catch (Exception)
- {
- // No need to report anything to the user. If it fails, it's probably already stopped.
- }
- }
-
- /// <summary>
- /// Shutdown the service.
- /// </summary>
- public void Shutdown()
- {
- // Nothing to do.
- }
-
- #endregion
-
- #region Private Helper Methods
-
- /// <summary>
- /// The HandBrakeCLI process has exited.
- /// </summary>
- /// <param name="sender">
- /// The sender.
- /// </param>
- /// <param name="e">
- /// The EventArgs.
- /// </param>
- private void HbProcessExited(object sender, System.EventArgs e)
- {
- this.HbProcess.WaitForExit();
-
- try
- {
- this.HbProcess.CancelErrorRead();
- this.HbProcess.CancelOutputRead();
- this.ShutdownFileWriter();
- }
- catch (Exception)
- {
- // This exception doesn't warrent user interaction, but it should be logged (TODO)
- }
-
- this.currentTask.Status = QueueItemStatus.Completed;
- this.IsEncoding = false;
- this.InvokeEncodeCompleted(new EncodeCompletedEventArgs(true, null, string.Empty, this.currentTask.Task.Destination));
- }
-
- /// <summary>
- /// Recieve the Standard Error information and process it
- /// </summary>
- /// <param name="sender">
- /// The Sender Object
- /// </param>
- /// <param name="e">
- /// DataReceived EventArgs
- /// </param>
- /// <remarks>
- /// Worker Thread.
- /// </remarks>
- private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
- {
- if (!String.IsNullOrEmpty(e.Data))
- {
- if (this.initShutdown && this.LogBuffer.Length < 25000000)
- {
- this.initShutdown = false; // Reset this flag.
- }
-
- if (this.LogBuffer.Length > 25000000 && !this.initShutdown) // Approx 23.8MB and make sure it's only printed once
- {
- this.ProcessLogMessage("ERROR: Initiating automatic shutdown of encode process. The size of the log file indicates that there is an error! ");
- this.initShutdown = true;
- this.Stop();
- }
-
- this.ProcessLogMessage(e.Data);
- }
- }
-
- /// <summary>
- /// The hb process output data received.
- /// </summary>
- /// <param name="sender">
- /// The sender.
- /// </param>
- /// <param name="e">
- /// The e.
- /// </param>
- private void HbProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
- {
- if (!String.IsNullOrEmpty(e.Data) && this.IsEncoding)
- {
- EncodeProgressEventArgs eventArgs = this.ReadEncodeStatus(e.Data, this.startTime);
- if (eventArgs != null)
- {
- if (!this.IsEncoding)
- {
- // We can get events out of order since the CLI progress is monitored on a background thread.
- // So make sure we don't send a status update after an encode complete event.
- return;
- }
-
- this.InvokeEncodeStatusChanged(eventArgs);
- }
- }
- }
-
- #endregion
- }
-} \ No newline at end of file
diff --git a/win/CS/HandBrake.ApplicationServices/Services/Encode/Interfaces/IEncode.cs b/win/CS/HandBrake.ApplicationServices/Services/Encode/Interfaces/IEncode.cs
index 90c42149b..aa53ed180 100644
--- a/win/CS/HandBrake.ApplicationServices/Services/Encode/Interfaces/IEncode.cs
+++ b/win/CS/HandBrake.ApplicationServices/Services/Encode/Interfaces/IEncode.cs
@@ -42,12 +42,12 @@ namespace HandBrake.ApplicationServices.Services.Encode.Interfaces
public interface IEncode
{
/// <summary>
- /// Fires when a new CLI Job starts
+ /// Fires when a new Job starts
/// </summary>
event EventHandler EncodeStarted;
/// <summary>
- /// Fires when a CLI job finishes.
+ /// Fires when a job finishes.
/// </summary>
event EncodeCompletedStatus EncodeCompleted;
@@ -100,7 +100,7 @@ namespace HandBrake.ApplicationServices.Services.Encode.Interfaces
void Resume();
/// <summary>
- /// Kill the CLI process
+ /// Kill the process
/// </summary>
void Stop();
@@ -114,10 +114,5 @@ namespace HandBrake.ApplicationServices.Services.Encode.Interfaces
/// The configuration.
/// </param>
void ProcessLogs(string destination, HBConfiguration configuration);
-
- /// <summary>
- /// Shutdown the service.
- /// </summary>
- void Shutdown();
}
} \ No newline at end of file
diff --git a/win/CS/HandBrake.ApplicationServices/Services/Encode/LibEncode.cs b/win/CS/HandBrake.ApplicationServices/Services/Encode/LibEncode.cs
index 208f8d307..82bb4b1a7 100644
--- a/win/CS/HandBrake.ApplicationServices/Services/Encode/LibEncode.cs
+++ b/win/CS/HandBrake.ApplicationServices/Services/Encode/LibEncode.cs
@@ -174,31 +174,26 @@ namespace HandBrake.ApplicationServices.Services.Encode
}
/// <summary>
- /// Kill the CLI process
+ /// Kill the process
/// </summary>
public override void Stop()
{
try
{
this.IsEncoding = false;
- this.instance.StopEncode();
- ServiceLogMessage("Encode Stopped");
+ if (instance != null)
+ {
+ this.instance.StopEncode();
+ ServiceLogMessage("Encode Stopped");
+ }
}
- catch (Exception)
+ catch (Exception exc)
{
- // Do Nothing.
+ Debug.WriteLine(exc);
}
}
/// <summary>
- /// Shutdown the service.
- /// </summary>
- public void Shutdown()
- {
- // Nothing to do for this implementation.
- }
-
- /// <summary>
/// The scan completed.
/// </summary>
/// <param name="job">
diff --git a/win/CS/HandBrake.ApplicationServices/Services/Scan/LibScan.cs b/win/CS/HandBrake.ApplicationServices/Services/Scan/LibScan.cs
index 721959a90..bc9304f8e 100644
--- a/win/CS/HandBrake.ApplicationServices/Services/Scan/LibScan.cs
+++ b/win/CS/HandBrake.ApplicationServices/Services/Scan/LibScan.cs
@@ -39,13 +39,6 @@ namespace HandBrake.ApplicationServices.Services.Scan
/// </summary>
public class LibScan : IScan
{
- /*
- * TODO
- * 1. Expose the Previews code.
- * 2. Cleanup old instances.
- *
- */
-
#region Private Variables
/// <summary>
@@ -101,7 +94,7 @@ namespace HandBrake.ApplicationServices.Services.Scan
public LibScan()
{
this.logging = new StringBuilder();
- this.header = GeneralUtilities.CreateCliLogHeader();
+ this.header = GeneralUtilities.CreateLogHeader();
}
#region Events
diff --git a/win/CS/HandBrake.ApplicationServices/Utilities/GeneralUtilities.cs b/win/CS/HandBrake.ApplicationServices/Utilities/GeneralUtilities.cs
index aa9b55a13..7a790f7f9 100644
--- a/win/CS/HandBrake.ApplicationServices/Utilities/GeneralUtilities.cs
+++ b/win/CS/HandBrake.ApplicationServices/Utilities/GeneralUtilities.cs
@@ -108,12 +108,12 @@ namespace HandBrake.ApplicationServices.Utilities
}
/// <summary>
- /// Add the CLI Query to the Log File.
+ /// Generate the header for the log file.
/// </summary>
/// <returns>
- /// The create cli log header.
+ /// The generatedlog header.
/// </returns>
- public static StringBuilder CreateCliLogHeader()
+ public static StringBuilder CreateLogHeader()
{
var logHeader = new StringBuilder();
diff --git a/win/CS/HandBrake.ApplicationServices/Utilities/QueryGeneratorUtility.cs b/win/CS/HandBrake.ApplicationServices/Utilities/QueryGeneratorUtility.cs
deleted file mode 100644
index 47c29db0a..000000000
--- a/win/CS/HandBrake.ApplicationServices/Utilities/QueryGeneratorUtility.cs
+++ /dev/null
@@ -1,1059 +0,0 @@
-// --------------------------------------------------------------------------------------------------------------------
-// <copyright file="QueryGeneratorUtility.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>
-// Generate a CLI Query for HandBrakeCLI
-// </summary>
-// --------------------------------------------------------------------------------------------------------------------
-
-namespace HandBrake.ApplicationServices.Utilities
-{
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Globalization;
- using System.IO;
- using System.Linq;
-
- using HandBrake.ApplicationServices.Model;
- using HandBrake.ApplicationServices.Services.Encode.Model;
- using HandBrake.ApplicationServices.Services.Encode.Model.Models;
- using HandBrake.Interop.Model.Encoding;
-
- /// <summary>
- /// Generate a CLI Query for HandBrakeCLI
- /// </summary>
- public class QueryGeneratorUtility
- {
- /// <summary>
- /// Generate a CLI Query for an EncodeTask Model object
- /// </summary>
- /// <param name="task">
- /// The task.
- /// </param>
- /// <param name="configuration">
- /// The configuration.
- /// </param>
- /// <returns>
- /// A Cli Query
- /// </returns>
- public static string GenerateQuery(EncodeTask task, HBConfiguration configuration)
- {
- if (string.IsNullOrEmpty(task.Source))
- {
- return "No source selected";
- }
-
- string query = string.Empty;
- query += SourceQuery(task, null, -1, configuration.PreviewScanCount);
- query += DestinationQuery(task);
- query += GenerateTabbedComponentsQuery(task, true, configuration.Verbosity, configuration.IsDvdNavDisabled, configuration.DisableQuickSyncDecoding, configuration.EnableDxva, configuration.ScalingMode == VideoScaler.BicubicCl);
-
- return query;
- }
-
- /// <summary>
- /// Generate a Query for a Preview Encode
- /// </summary>
- /// <param name="task">
- /// The task.
- /// </param>
- /// <param name="configuration">
- /// The configuration.
- /// </param>
- /// <param name="duration">
- /// The duration.
- /// </param>
- /// <param name="startAtPreview">
- /// The start At Preview.
- /// </param>
- /// <returns>
- /// A Cli query suitable for generating a preview video.
- /// </returns>
- public static string GeneratePreviewQuery(EncodeTask task, HBConfiguration configuration, int duration, int startAtPreview)
- {
- string query = string.Empty;
- query += SourceQuery(task, duration, startAtPreview, configuration.PreviewScanCount);
- query += DestinationQuery(task);
- query += GenerateTabbedComponentsQuery(task, true, configuration.Verbosity, configuration.IsDvdNavDisabled, configuration.DisableQuickSyncDecoding, false, false);
-
- return query;
- }
-
- #region Individual Query Sections
-
- /// <summary>
- /// Generate a Query from an Encode Task Object.
- /// </summary>
- /// <param name="task">
- /// The task.
- /// </param>
- /// <param name="enableFilters">
- /// The enableFilters.
- /// </param>
- /// <param name="verbosity">
- /// The verbosity.
- /// </param>
- /// <param name="disableLibDvdNav">
- /// The disable Lib Dvd Nav.
- /// </param>
- /// <param name="disableQsvDecode">
- /// The disable Qsv Decode.
- /// </param>
- /// <param name="enableHwd">
- /// The enable Hwd.
- /// </param>
- /// <param name="enableOpenCL">
- /// The enable Open CL.
- /// </param>
- /// <returns>
- /// The CLI query for the Tabbed section of the main window UI
- /// </returns>
- private static string GenerateTabbedComponentsQuery(EncodeTask task, bool enableFilters, int verbosity, bool disableLibDvdNav, bool disableQsvDecode, bool enableHwd, bool enableOpenCL)
- {
- string query = string.Empty;
-
- // Output Settings
- query += OutputSettingsQuery(task);
-
- // Filters Panel
- if (enableFilters)
- query += FiltersQuery(task);
-
- // Picture Settings
- query += PictureSettingsQuery(task);
-
- // Video Settings
- query += VideoSettingsQuery(task);
-
- // Audio Settings
- query += AudioSettingsQuery(task);
-
- // Subtitles Panel
- query += SubtitlesQuery(task);
-
- // Chapter Markers
- query += ChapterMarkersQuery(task);
-
- // Advanced Panel
- query += AdvancedQuery(task);
-
- // Extra Settings
- query += ExtraSettings(verbosity, disableLibDvdNav, disableQsvDecode, enableHwd, enableOpenCL, task.VideoEncoder == VideoEncoder.QuickSync);
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Source
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <param name="duration">
- /// The duration.
- /// </param>
- /// <param name="preview">
- /// The preview.
- /// </param>
- /// <param name="previewScanCount">
- /// The preview Scan Count.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string SourceQuery(EncodeTask task, int? duration, int preview, int previewScanCount)
- {
- string query = string.Empty;
-
- query += task.Source.EndsWith("\\")
- ? string.Format(" -i \"{0}\\\\\"", task.Source.TrimEnd('\\'))
- : string.Format(" -i \"{0}\"", task.Source);
-
- query += string.Format(" -t {0}", task.Title);
- query += string.Format(" --angle {0}", task.Angle);
-
- // Decide what part of the video we want to encode.
- switch (task.PointToPointMode)
- {
- case PointToPointMode.Chapters: // Chapters
-
- if (task.StartPoint == task.EndPoint)
- query += string.Format(" -c {0}", task.StartPoint);
- else
- query += string.Format(" -c {0}-{1}", task.StartPoint, task.EndPoint);
- break;
- case PointToPointMode.Seconds: // Seconds
- int calculatedDuration = task.EndPoint - task.StartPoint;
- query += string.Format(" --start-at duration:{0} --stop-at duration:{1}", task.StartPoint, calculatedDuration);
- break;
- case PointToPointMode.Frames: // Frames
- calculatedDuration = task.EndPoint - task.StartPoint;
- query += string.Format(" --start-at frame:{0} --stop-at frame:{1}", task.StartPoint, calculatedDuration);
- break;
- case PointToPointMode.Preview: // Preview
- query += " --previews " + previewScanCount + " ";
- query += " --start-at-preview " + preview;
- query += " --stop-at duration:" + duration + " ";
- break;
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Destination File
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string DestinationQuery(EncodeTask task)
- {
- return string.Format(" -o \"{0}\" ", task.Destination);
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Output Settings
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string OutputSettingsQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- query += string.Format(" -f {0} ", EnumHelper<Enum>.GetDescription(task.OutputFormat).ToLower());
-
- // These are output settings features
- if (task.IPod5GSupport)
- query += " -I ";
-
- if (task.OptimizeMP4)
- query += " -O ";
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Picture Settings tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string PictureSettingsQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- if (task.Anamorphic != Anamorphic.Strict)
- {
- if (task.Width.HasValue && task.Width != 0) query += string.Format(" -w {0}", task.Width);
-
- if (task.Height.HasValue && task.Height != 0) query += string.Format(" -l {0}", task.Height);
- }
-
- query += string.Format(
- " --crop {0}:{1}:{2}:{3}",
- task.Cropping.Top,
- task.Cropping.Bottom,
- task.Cropping.Left,
- task.Cropping.Right);
-
- switch (task.Anamorphic)
- {
- case Anamorphic.Strict:
- query += " --strict-anamorphic ";
- break;
- case Anamorphic.Loose:
- query += " --loose-anamorphic ";
- break;
- case Anamorphic.Custom:
- query += " --custom-anamorphic ";
-
- if (task.DisplayWidth.HasValue)
- query += " --display-width " + task.DisplayWidth + " ";
-
- if (task.KeepDisplayAspect)
- query += " --keep-display-aspect ";
-
- if (!task.KeepDisplayAspect)
- query += string.Format(" --pixel-aspect {0}:{1}", task.PixelAspectX, task.PixelAspectY);
- break;
- }
-
- if (task.Modulus.HasValue)
- {
- query += " --modulus " + task.Modulus;
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Filters Tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string FiltersQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- switch (task.Detelecine) // DeTelecine
- {
- case Detelecine.Off:
- query += string.Empty;
- break;
- case Detelecine.Default:
- query += " --detelecine";
- break;
- case Detelecine.Custom:
- query += string.Format(" --detelecine=\"{0}\"", task.CustomDetelecine);
- break;
- default:
- query += string.Empty;
- break;
- }
-
- switch (task.Decomb) // Decomb
- {
- case Decomb.Off:
- query += string.Empty;
- break;
- case Decomb.Default:
- query += " --decomb";
- break;
- case Decomb.Custom:
- query += string.Format(" --decomb=\"{0}\"", task.CustomDecomb);
- break;
- case Decomb.Fast:
- query += " --decomb=\"fast\"";
- break;
- case Decomb.Bob:
- query += " --decomb=\"bob\"";
- break;
- default:
- query += string.Empty;
- break;
- }
-
- switch (task.Deinterlace) // DeInterlace
- {
- case Deinterlace.Fast:
- query += " --deinterlace=\"fast\"";
- break;
- case Deinterlace.Slow:
- query += " --deinterlace=\"slow\"";
- break;
- case Deinterlace.Slower:
- query += " --deinterlace=\"slower\"";
- break;
- case Deinterlace.Custom:
- query += string.Format(" --deinterlace=\"{0}\"", task.CustomDeinterlace);
- break;
-
- case Deinterlace.Bob:
- query += " --deinterlace=\"bob\"";
- break;
- default:
- query += string.Empty;
- break;
- }
-
- if (task.Denoise == Denoise.hqdn3d)
- {
- switch (task.DenoisePreset) // Denoise
- {
- case DenoisePreset.Weak:
- query += " --denoise=\"weak\"";
- break;
- case DenoisePreset.Medium:
- query += " --denoise=\"medium\"";
- break;
- case DenoisePreset.Strong:
- query += " --denoise=\"strong\"";
- break;
- case DenoisePreset.Custom:
- query += string.Format(" --denoise=\"{0}\"", task.CustomDenoise);
- break;
- }
- }
-
- // NL Means
- if (task.Denoise == Denoise.NLMeans)
- {
- switch (task.DenoisePreset) // Denoise
- {
- case DenoisePreset.Light:
- query += " --nlmeans=\"light\"";
- break;
- case DenoisePreset.Ultralight:
- query += " --nlmeans=\"ultralight\"";
- break;
- case DenoisePreset.Medium:
- query += " --nlmeans=\"medium\"";
- break;
- case DenoisePreset.Strong:
- query += " --nlmeans=\"strong\"";
- break;
- default:
- query += string.Empty;
- break;
- }
-
- switch (task.DenoiseTune)
- {
- case DenoiseTune.Animation:
- query += " --nlmeans-tune=\"animation\"";
- break;
- case DenoiseTune.Film:
- query += " --nlmeans-tune=\"film\"";
- break;
- case DenoiseTune.Grain:
- query += " --nlmeans-tune=\"grain\"";
- break;
- case DenoiseTune.HighMotion:
- query += " --nlmeans-tune=\"highmotion\"";
- break;
- default:
- query += string.Empty;
- break;
- }
- }
-
- if (task.Deblock > 4)
- query += string.Format(" --deblock={0}", task.Deblock);
-
- if (task.Grayscale)
- query += " -g ";
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Video Settings Tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string VideoSettingsQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- switch (task.VideoEncoder)
- {
- case VideoEncoder.FFMpeg:
- query += " -e ffmpeg4";
- break;
- case VideoEncoder.FFMpeg2:
- query += " -e ffmpeg2";
- break;
- case VideoEncoder.X264:
- query += " -e x264";
- break;
- case VideoEncoder.QuickSync:
- query += " -e qsv_h264";
- break;
- case VideoEncoder.Theora:
- query += " -e theora";
- break;
- case VideoEncoder.VP8:
- query += " -e VP8";
- break;
- default:
- query += " -e x264";
- break;
- case VideoEncoder.X265:
- query += " -e x265";
- break;
- }
-
- switch (task.VideoEncodeRateType)
- {
- case VideoEncodeRateType.AverageBitrate:
- if (task.VideoBitrate.HasValue)
- query += string.Format(" -b {0}", task.VideoBitrate.Value);
- break;
- case VideoEncodeRateType.ConstantQuality:
- query += string.Format(" -q {0}", task.Quality.Value.ToString(CultureInfo.InvariantCulture));
- break;
- }
-
- if (task.TwoPass)
- query += " -2 ";
-
- if (task.TurboFirstPass && task.VideoEncoder == VideoEncoder.X264)
- query += " -T ";
-
- if (task.Framerate.HasValue)
- query += string.Format(" -r {0}", task.Framerate.Value.ToString(CultureInfo.InvariantCulture));
-
- switch (task.FramerateMode)
- {
- case FramerateMode.CFR:
- query += " --cfr";
- break;
- case FramerateMode.VFR:
- query += " --vfr";
- break;
- case FramerateMode.PFR:
- query += " --pfr";
- break;
- default:
- query += " --vfr";
- break;
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Audio Settings Tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string AudioSettingsQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- ObservableCollection<AudioTrack> audioTracks = task.AudioTracks;
-
- List<int> tracks = new List<int>();
- List<AudioEncoder> codecs = new List<AudioEncoder>();
- List<Mixdown> mixdowns = new List<Mixdown>();
- List<double> samplerates = new List<double>();
- List<int> bitrates = new List<int>();
- List<double> drcs = new List<double>();
- List<double> gains = new List<double>();
- List<string> trackNames = new List<string>();
-
- // No Audio
- if (audioTracks.Count == 0)
- query += " -a none ";
-
- // Gather information about each audio track and store them in the declared lists.
- foreach (AudioTrack track in audioTracks)
- {
- if (track.Track == null)
- {
- continue;
- }
-
- tracks.Add(track.Track.Value);
-
- // Audio Codec (-E)
- codecs.Add(track.Encoder);
-
- // Audio Mixdown (-6)
- mixdowns.Add(track.IsPassthru ? Mixdown.None : track.MixDown);
-
- // Sample Rate (-R)
- samplerates.Add(track.IsPassthru ? 0 : track.SampleRate);
-
- // Audio Bitrate (-B)
- bitrates.Add(track.IsPassthru ? 0 : track.Bitrate);
-
- // DRC (-D)
- drcs.Add(track.IsPassthru ? 0 : track.DRC);
-
- // Gain (--gain)
- gains.Add(track.IsPassthru ? 0 : track.Gain);
-
- // Audio Track Name (--aname)
- trackNames.Add(track.TrackName);
- }
-
- // Audio Track (-a)
- string audioItems = string.Empty;
- bool firstLoop = true;
-
- foreach (int item in tracks)
- {
- if (firstLoop)
- {
- audioItems = item.ToString();
- firstLoop = false;
- }
- else
- audioItems += "," + item;
- }
- if (audioItems.Trim() != String.Empty)
- query += " -a " + audioItems;
- firstLoop = true;
- audioItems = string.Empty; // Reset for another pass.
-
- // Audio Codec (-E)
- foreach (AudioEncoder item in codecs)
- {
- if (firstLoop)
- {
- audioItems = Converters.GetCliAudioEncoder(item);
- firstLoop = false;
- }
- else
- audioItems += "," + Converters.GetCliAudioEncoder(item);
- }
- if (audioItems.Trim() != String.Empty)
- query += " -E " + audioItems;
- firstLoop = true;
- audioItems = string.Empty; // Reset for another pass.
-
- // Audio Mixdown (-6)
- foreach (Mixdown item in mixdowns)
- {
- if (firstLoop)
- {
- audioItems = Converters.GetCliMixDown(item);
- firstLoop = false;
- }
- else
- audioItems += "," + Converters.GetCliMixDown(item);
- }
- if (audioItems.Trim() != String.Empty)
- query += " -6 " + audioItems;
- firstLoop = true;
- audioItems = string.Empty; // Reset for another pass.
-
- // Sample Rate (-R)
- foreach (double item in samplerates)
- {
- string add = (item == 0.0) ? "Auto" : item.ToString(new CultureInfo("en-US"));
- if (firstLoop)
- {
- audioItems = add;
- firstLoop = false;
- }
- else
- audioItems += "," + add;
- }
- if (audioItems.Trim() != String.Empty)
- query += " -R " + audioItems;
- firstLoop = true;
- audioItems = string.Empty; // Reset for another pass.
-
- // Audio Bitrate (-B)
- foreach (int item in bitrates)
- {
- if (firstLoop)
- {
- audioItems = item.ToString();
- firstLoop = false;
- }
- else
- audioItems += "," + item;
- }
- if (audioItems.Trim() != String.Empty)
- query += " -B " + audioItems;
- firstLoop = true;
- audioItems = string.Empty; // Reset for another pass.
-
- // DRC (-D)
- foreach (var itm in drcs)
- {
- string item = itm.ToString(new CultureInfo("en-US"));
- if (firstLoop)
- {
- audioItems = item;
- firstLoop = false;
- }
- else
- audioItems += "," + item;
- }
- if (audioItems.Trim() != String.Empty)
- query += " -D " + audioItems;
-
- audioItems = string.Empty; // Reset for another pass.
- firstLoop = true;
-
- // Gain (--gain)
- foreach (var itm in gains)
- {
- string item = itm.ToString(new CultureInfo("en-US"));
- if (firstLoop)
- {
- audioItems = item;
- firstLoop = false;
- }
- else
- audioItems += "," + item;
- }
- if (audioItems.Trim() != String.Empty)
- query += " --gain " + audioItems;
-
- audioItems = string.Empty; // Reset for another pass.
- firstLoop = true;
-
- // Audio Track Names (--aname)
- bool foundTrackName = false;
- foreach (string trackName in trackNames)
- {
- if (!string.IsNullOrEmpty(trackName))
- {
- foundTrackName = true;
- }
-
- string fixedTrackName = trackName != null ? trackName.Replace(",", "\\,") : string.Empty;
-
- if (firstLoop)
- {
- audioItems = string.IsNullOrEmpty(fixedTrackName) ? string.Empty : string.Format("{0}", fixedTrackName.Trim());
- firstLoop = false;
- }
- else
- audioItems += "," + (string.IsNullOrEmpty(fixedTrackName) ? string.Empty : string.Format("{0}", fixedTrackName.Trim()));
- }
- if (foundTrackName)
- query += string.Format(" --aname=\"{0}\"", audioItems);
-
- // Passthru Settings
- if (task.AllowedPassthruOptions != null)
- {
- string fallbackEncoders = string.Empty;
-
- if (task.AllowedPassthruOptions.AudioAllowAACPass != null && task.AllowedPassthruOptions.AudioAllowAACPass.Value)
- {
- fallbackEncoders += "aac";
- }
-
- if (task.AllowedPassthruOptions.AudioAllowAC3Pass != null && task.AllowedPassthruOptions.AudioAllowAC3Pass.Value)
- {
- fallbackEncoders += string.IsNullOrEmpty(fallbackEncoders) ? "ac3" : ",ac3";
- }
-
- if (task.AllowedPassthruOptions.AudioAllowDTSHDPass != null && task.AllowedPassthruOptions.AudioAllowDTSHDPass.Value)
- {
- fallbackEncoders += string.IsNullOrEmpty(fallbackEncoders) ? "dtshd" : ",dtshd";
- }
-
- if (task.AllowedPassthruOptions.AudioAllowDTSPass != null && task.AllowedPassthruOptions.AudioAllowDTSPass.Value)
- {
- fallbackEncoders += string.IsNullOrEmpty(fallbackEncoders) ? "dts" : ",dts";
- }
-
- if (task.AllowedPassthruOptions.AudioAllowMP3Pass != null && task.AllowedPassthruOptions.AudioAllowMP3Pass.Value)
- {
- fallbackEncoders += string.IsNullOrEmpty(fallbackEncoders) ? "mp3" : ",mp3";
- }
-
- if (!string.IsNullOrEmpty(fallbackEncoders))
- {
- // Special Case, The CLI alredy defaults to ALL, so if all area selected, then don't need to set copy mask
- if (fallbackEncoders != "aac,ac3,dtshd,dts,mp3")
- {
- query += string.Format(" --audio-copy-mask {0}", fallbackEncoders);
- }
- }
- else
- {
- query += string.Format(" --audio-copy-mask none");
- }
-
- query += string.Format(" --audio-fallback {0}", Converters.GetCliAudioEncoder(task.AllowedPassthruOptions.AudioEncoderFallback));
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Subtitles Tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string SubtitlesQuery(EncodeTask task)
- {
- string query = string.Empty;
- if (task.SubtitleTracks.Count != 0)
- {
- // BitMap and CC's
- string subtitleTracks = String.Empty;
- string subtitleForced = String.Empty;
- string subtitleBurn = String.Empty;
- string subtitleDefault = String.Empty;
-
- // SRT
- string srtFile = String.Empty;
- string srtCodeset = String.Empty;
- string srtOffset = String.Empty;
- string srtLang = String.Empty;
- string srtDefault = String.Empty;
- int? srtBurnTrack = null;
- int srtCount = 0;
- int subCount = 0;
-
- // Languages
- IDictionary<string, string> langMap = LanguageUtilities.MapLanguages();
-
- foreach (SubtitleTrack item in task.SubtitleTracks)
- {
- string itemToAdd;
-
- if (item.IsSrtSubtitle) // We have an SRT file
- {
- srtCount++; // SRT track id.
-
- srtLang += srtLang == string.Empty ? langMap[item.SrtLang] : "," + langMap[item.SrtLang];
- srtCodeset += srtCodeset == string.Empty ? item.SrtCharCode : "," + item.SrtCharCode;
-
- if (item.Default)
- srtDefault = srtCount.ToString();
-
- itemToAdd = item.SrtPath.Replace("\\", "\\\\").Replace(",", "\\,");
- srtFile += srtFile == string.Empty ? itemToAdd : "," + itemToAdd;
-
- itemToAdd = item.SrtOffset.ToString();
- srtOffset += srtOffset == string.Empty ? itemToAdd : "," + itemToAdd;
- if (item.Burned)
- srtBurnTrack = srtCount;
- }
- else // We have Bitmap or CC
- {
- subCount++;
-
- // Find --subtitle <string>
- if (item.SourceTrack.SubtitleType == SubtitleType.ForeignAudioSearch)
- itemToAdd = "scan";
- else
- {
- string[] tempSub = item.Track.Split(' ');
- itemToAdd = tempSub[0];
- }
-
- subtitleTracks += subtitleTracks == string.Empty ? itemToAdd : "," + itemToAdd;
-
- // Find --subtitle-forced
- if (item.Forced)
- subtitleForced += subtitleForced == string.Empty ? subCount.ToString() : "," + subCount;
-
- // Find --subtitle-burn
- if (item.Burned)
- subtitleBurn = subCount.ToString();
-
- // Find --subtitle-default
- if (item.Default)
- subtitleDefault = subCount.ToString();
- }
- }
-
- // Build The CLI Subtitles Query
- if (subtitleTracks != string.Empty)
- {
- query += " --subtitle " + subtitleTracks;
-
- if (subtitleForced != string.Empty)
- query += " --subtitle-forced=" + subtitleForced;
- if (subtitleBurn != string.Empty)
- query += " --subtitle-burned=" + subtitleBurn;
- if (subtitleDefault != string.Empty)
- query += " --subtitle-default=" + subtitleDefault;
- }
-
- if (srtFile != string.Empty) // SRTs
- {
- query += " --srt-file " + "\"" + srtFile + "\"";
-
- if (srtCodeset != string.Empty)
- query += " --srt-codeset " + srtCodeset;
- if (srtOffset != string.Empty)
- query += " --srt-offset " + srtOffset;
- if (srtLang != string.Empty)
- query += " --srt-lang " + srtLang;
- if (srtDefault != string.Empty)
- query += " --srt-default=" + srtDefault;
- if (srtBurnTrack.HasValue)
- query += " --srt-burn=" + srtBurnTrack.Value;
- }
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Chapter markers tab
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string ChapterMarkersQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- // Attach Source name and dvd title to the start of the chapters.csv filename.
- // This is for the queue. It allows different chapter name files for each title.
- string destName = Path.GetFileNameWithoutExtension(task.Destination);
- string sourceTitle = task.Title.ToString();
-
- if (task.IncludeChapterMarkers && destName != null)
- {
- if (destName.Trim() != String.Empty)
- {
- string path = sourceTitle != "Automatic"
- ? Path.Combine(Path.GetTempPath(), destName + "-" + sourceTitle + "-chapters.csv")
- : Path.Combine(Path.GetTempPath(), destName + "-chapters.csv");
-
- if (ChapterCsvSave(task.ChapterNames, path) == false)
- query += " -m ";
- else
- query += " --markers=" + "\"" + path + "\"";
- }
- else
- query += " -m";
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for the Advanced Encoder Options
- /// </summary>
- /// <param name="task">
- /// The encode task.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string AdvancedQuery(EncodeTask task)
- {
- string query = string.Empty;
-
- if (task.VideoEncoder == VideoEncoder.X264 || task.VideoEncoder == VideoEncoder.X265 || task.VideoEncoder == VideoEncoder.QuickSync)
- {
- if (!task.ShowAdvancedTab)
- {
- query += string.Format(" --encoder-preset={0} ", task.VideoPreset.ShortName);
-
- string tuneQuery = task.VideoTunes.Aggregate(string.Empty, (current, tune) => string.IsNullOrEmpty(current) ? tune.ShortName : string.Format(",{0}", tune.ShortName));
- if (!string.IsNullOrEmpty(tuneQuery))
- {
- query += string.Format(" --encoder-tune=\"{0}\" ", tuneQuery);
- }
-
- query += string.Format(" --encoder-profile={0} ", task.VideoProfile.ShortName);
-
- query += string.Format(" --encoder-level=\"{0}\" ", task.VideoLevel.ShortName);
-
- if (!string.IsNullOrEmpty(task.ExtraAdvancedArguments))
- {
- query += string.Format(" -x {0}", task.ExtraAdvancedArguments);
- }
- }
- }
- else if (!task.ShowAdvancedTab && !string.IsNullOrEmpty(task.ExtraAdvancedArguments))
- {
- query += string.Format(" -x {0}", task.ExtraAdvancedArguments);
- }
-
-
- // options that apply to all encoders
- if (task.ShowAdvancedTab && !string.IsNullOrEmpty(task.AdvancedEncoderOptions))
- {
- query += string.Format(" -x {0}", task.AdvancedEncoderOptions);
- }
-
- return query;
- }
-
- /// <summary>
- /// Generate the Command Line Arguments for any additional advanced options.
- /// </summary>
- /// <param name="verbosity">
- /// The verbosity.
- /// </param>
- /// <param name="disableLibdvdNav">
- /// The disable Libdvd Nav.
- /// </param>
- /// <param name="disableQsvDecode">
- /// The disable Qsv Decode.
- /// </param>
- /// <param name="enableHwd">
- /// The enable Hwd.
- /// </param>
- /// <param name="enableOpenCL">
- /// The enable Open CL.
- /// </param>
- /// <param name="isQsv">
- /// The is Qsv.
- /// </param>
- /// <returns>
- /// A Cli Query as a string
- /// </returns>
- private static string ExtraSettings(int verbosity, bool disableLibdvdNav, bool disableQsvDecode, bool enableHwd, bool enableOpenCL, bool isQsv)
- {
- string query = string.Empty;
-
- // Verbosity Level
- query += string.Format(" --verbose={0}", verbosity);
-
- // LibDVDNav
- if (disableLibdvdNav)
- query += " --no-dvdnav";
-
- if (disableQsvDecode)
- query += " --disable-qsv-decoding";
-
- if (enableOpenCL && !isQsv)
- query += " -P ";
-
- if (enableHwd && !isQsv)
- {
- query += " -U ";
- }
-
- return query;
- }
-
- #endregion
-
- #region Helpers
-
- /// <summary>
- /// Create a CSV file with the data from the Main Window Chapters tab
- /// </summary>
- /// <param name="chapters">The List of chapters</param>
- /// <param name="filePathName">Path to save the csv file</param>
- /// <returns>True if successful </returns>
- private static bool ChapterCsvSave(IEnumerable<ChapterMarker> chapters, string filePathName)
- {
- string csv = string.Empty;
- int counter = 1;
-
- foreach (ChapterMarker name in chapters)
- {
- csv += counter + "," + name.ChapterName.Replace(",", "\\,") + Environment.NewLine;
- counter++;
- }
-
- StreamWriter file = new StreamWriter(filePathName);
- file.Write(csv);
- file.Close();
- file.Dispose();
- return true;
- }
- #endregion
- }
-} \ No newline at end of file