diff --git a/Application/FileConverter/Application.xaml.cs b/Application/FileConverter/Application.xaml.cs index 2f4a3f4..bd058a4 100644 --- a/Application/FileConverter/Application.xaml.cs +++ b/Application/FileConverter/Application.xaml.cs @@ -21,12 +21,14 @@ namespace FileConverter using System.Threading; using System.Windows; + using FileConverter.ConversionJobs; + public partial class Application : System.Windows.Application { private static readonly Version Version = new Version() { Major = 0, - Minor = 2, + Minor = 3, }; private readonly List conversionJobs = new List(); @@ -84,7 +86,7 @@ namespace FileConverter { this.cancelAutoExit = true; } - + private void Initialize() { // Load settigns. @@ -100,17 +102,11 @@ namespace FileConverter if (args.Length <= 1) { this.debugMode = true; - System.Array.Resize(ref args, 9); + System.Array.Resize(ref args, 5); args[1] = "--conversion-preset"; args[2] = "To Mp3"; - args[3] = @"D:\Projects\FileConverter\TestFiles\Herbie Hancock - Speak Like A Child [RVG Edition].flac"; - args[3] = @"D:\Projects\FileConverter\TestFiles\01 - Le Bruit Du Bang.wma"; - args[4] = @"D:\Projects\FileConverter\TestFiles\test\Toccata.wav"; - args[5] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (4).wav"; - args[5] = "--verbose"; - args[6] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (3).wav"; - args[7] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (2).wav"; - args[8] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (5).wav"; + args[3] = "--verbose"; + args[4] = @"D:\Test\10 - Get around town (lp version).ogg"; System.Array.Resize(ref args, 2); args[1] = "--settings"; @@ -151,7 +147,7 @@ namespace FileConverter case "conversion-preset": if (index >= args.Length - 1) { - MessageBox.Show(string.Format("ERROR ! Invalid format."), "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show(string.Format("Invalid format. (code 0x01)"), "Error", MessageBoxButton.OK, MessageBoxImage.Error); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; } @@ -159,7 +155,7 @@ namespace FileConverter conversionPreset = Settings.GetPresetFromName(args[index + 1]); if (conversionPreset == null) { - MessageBox.Show(string.Format("Invalid conversion preset '{0}'.", args[index + 1]), "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show(string.Format("Invalid conversion preset '{0}'. (code 0x02)", args[index + 1]), "Error", MessageBoxButton.OK, MessageBoxImage.Error); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; } @@ -195,7 +191,9 @@ namespace FileConverter for (int index = 0; index < filePaths.Count; index++) { string inputFilePath = filePaths[index]; - ConversionJob conversionJob = new ConversionJob(conversionPreset, inputFilePath); + ConversionJob conversionJob = ConversionJobFactory.Create(conversionPreset); + conversionJob.PrepareConversion(inputFilePath); + this.conversionJobs.Add(conversionJob); } @@ -207,23 +205,16 @@ namespace FileConverter for (int index = 0; index < this.conversionJobs.Count; index++) { ConversionJob conversionJob = this.conversionJobs[index]; + if (conversionJob.State != ConversionJob.ConversionState.Ready) + { + continue; + } + conversionJob.StartConvertion(); if (System.IO.File.Exists(conversionJob.OutputFilePath)) { Diagnostics.Log("Success!"); - - if (this.debugMode) - { - Diagnostics.Log("Delete file {0}.", conversionJob.OutputFilePath); - try - { - System.IO.File.Delete(conversionJob.OutputFilePath); - } - catch - { - } - } } else { diff --git a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml new file mode 100644 index 0000000..2169861 --- /dev/null +++ b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + diff --git a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs new file mode 100644 index 0000000..90f6421 --- /dev/null +++ b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs @@ -0,0 +1,181 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Controls +{ + using System.Diagnostics; + using System.Windows; + using System.Windows.Controls; + + /// + /// Interaction logic for EncodingQualitySliderControl. + /// + public partial class EncodingQualitySliderControl : UserControl + { + public static readonly DependencyProperty BitrateProperty = DependencyProperty.Register( + "Bitrate", + typeof(double), + typeof(EncodingQualitySliderControl), + new FrameworkPropertyMetadata(new PropertyChangedCallback(EncodingQualitySliderControl.OnBitrateValueChanged), new CoerceValueCallback(EncodingQualitySliderControl.CoerceBitrateValue))); + + public static readonly DependencyProperty EncodingModeProperty = DependencyProperty.Register( + "EncodingMode", + typeof(EncodingMode), + typeof(EncodingQualitySliderControl), + new PropertyMetadata(new PropertyChangedCallback(EncodingQualitySliderControl.OnEncodingModeValueChanged))); + + public EncodingQualitySliderControl() + { + this.InitializeComponent(); + + this.CoerceValue(EncodingQualitySliderControl.BitrateProperty); + + this.slider.ValueChanged += this.Slider_ValueChanged; + } + + public EncodingMode EncodingMode + { + get + { + return (EncodingMode)this.GetValue(EncodingQualitySliderControl.EncodingModeProperty); + } + + set + { + this.SetCurrentValue(EncodingQualitySliderControl.EncodingModeProperty, value); + } + } + + public double Bitrate + { + get + { + return (double)this.GetValue(EncodingQualitySliderControl.BitrateProperty); + } + + set + { + this.SetCurrentValue(EncodingQualitySliderControl.BitrateProperty, this.GetNearestTickValue(value)); + } + } + + private static void OnBitrateValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs) + { + EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl; + encodingQualitySliderControl.slider.Value = (double)eventArgs.NewValue; + } + + private static object CoerceBitrateValue(DependencyObject sender, object basevalue) + { + EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl; + return encodingQualitySliderControl.GetNearestTickValue((double)basevalue); + } + + private static void OnEncodingModeValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs) + { + EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl; + Slider sliderControl = encodingQualitySliderControl.slider; + + switch (encodingQualitySliderControl.EncodingMode) + { + case EncodingMode.Mp3VBR: + { + sliderControl.Minimum = 65; + sliderControl.Maximum = 245; + sliderControl.SelectionStart = 115; + sliderControl.SelectionEnd = 245; + sliderControl.Ticks.Clear(); + sliderControl.Ticks.Add(65); + sliderControl.Ticks.Add(85); + sliderControl.Ticks.Add(100); + sliderControl.Ticks.Add(115); + sliderControl.Ticks.Add(130); + sliderControl.Ticks.Add(165); + sliderControl.Ticks.Add(175); + sliderControl.Ticks.Add(190); + sliderControl.Ticks.Add(225); + sliderControl.Ticks.Add(245); + break; + } + + case EncodingMode.Mp3CBR: + { + sliderControl.Minimum = 8; + sliderControl.Maximum = 320; + sliderControl.SelectionStart = 128; + sliderControl.SelectionEnd = 256; + sliderControl.Ticks.Clear(); + sliderControl.Ticks.Add(8); + sliderControl.Ticks.Add(16); + sliderControl.Ticks.Add(24); + sliderControl.Ticks.Add(32); + sliderControl.Ticks.Add(40); + sliderControl.Ticks.Add(48); + sliderControl.Ticks.Add(64); + sliderControl.Ticks.Add(80); + sliderControl.Ticks.Add(96); + sliderControl.Ticks.Add(112); + sliderControl.Ticks.Add(128); + sliderControl.Ticks.Add(160); + sliderControl.Ticks.Add(192); + sliderControl.Ticks.Add(224); + sliderControl.Ticks.Add(256); + sliderControl.Ticks.Add(320); + break; + } + + case EncodingMode.OggVBR: + { + sliderControl.Minimum = 32; + sliderControl.Maximum = 500; + sliderControl.SelectionStart = 80; + sliderControl.SelectionEnd = 192; + sliderControl.Ticks.Clear(); + sliderControl.Ticks.Add(32); + sliderControl.Ticks.Add(48); + sliderControl.Ticks.Add(64); + sliderControl.Ticks.Add(80); + sliderControl.Ticks.Add(96); + sliderControl.Ticks.Add(112); + sliderControl.Ticks.Add(128); + sliderControl.Ticks.Add(160); + sliderControl.Ticks.Add(192); + sliderControl.Ticks.Add(224); + sliderControl.Ticks.Add(256); + sliderControl.Ticks.Add(320); + sliderControl.Ticks.Add(500); + break; + } + } + + encodingQualitySliderControl.CoerceValue(EncodingQualitySliderControl.BitrateProperty); + } + + private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (this.Bitrate == e.NewValue) + { + return; + } + + this.SetCurrentValue(EncodingQualitySliderControl.BitrateProperty, e.NewValue); + } + + private double GetNearestTickValue(double value) + { + double minimumDifference = float.PositiveInfinity; + double nearestTick = value; + for (int index = 0; index < this.slider.Ticks.Count; index++) + { + double tick = this.slider.Ticks[index]; + double difference = System.Math.Abs(value - tick); + if (difference < minimumDifference) + { + minimumDifference = difference; + nearestTick = tick; + } + } + + return nearestTick; + } + } +} diff --git a/Application/FileConverter/ConversionJob.cs b/Application/FileConverter/ConversionJob.cs deleted file mode 100644 index 0e575f7..0000000 --- a/Application/FileConverter/ConversionJob.cs +++ /dev/null @@ -1,269 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter -{ - using System; - using System.ComponentModel; - using System.Diagnostics; - using System.IO; - using System.Runtime.CompilerServices; - using System.Text.RegularExpressions; - - public class ConversionJob : INotifyPropertyChanged - { - private readonly Regex durationRegex = new Regex(@"Duration:\s*([0-9][0-9]):([0-9][0-9]):([0-9][0-9])\.([0-9][0-9]),.*bitrate:\s*([0-9]+) kb\/s"); - private readonly Regex progressRegex = new Regex(@"size=\s*([0-9]+)kB\s+time=([0-9][0-9]):([0-9][0-9]):([0-9][0-9]).([0-9][0-9])\s+bitrate=\s*([0-9]+.[0-9])kbits\/s"); - - private TimeSpan fileDuration; - private TimeSpan actualConvertedDuration; - - private ProcessStartInfo ffmpegProcessStartInfo; - - private float progress; - - private ConversionState state; - - private string exitingMessage; - - public ConversionJob() - { - this.ConversionPreset = null; - this.progress = 0f; - this.InputFilePath = string.Empty; - this.OutputFilePath = string.Empty; - this.State = ConversionState.Unknown; - this.ExitingMessage = string.Empty; - } - - public ConversionJob(ConversionPreset conversionPreset, string inputFilePath) - { - this.ConversionPreset = conversionPreset; - this.InputFilePath = inputFilePath; - - string extension = System.IO.Path.GetExtension(inputFilePath); - this.OutputFilePath = inputFilePath.Substring(0, inputFilePath.Length - extension.Length) + "." + this.ConversionPreset.OutputType.ToString().ToLowerInvariant(); - - this.Initialize(); - } - - public event PropertyChangedEventHandler PropertyChanged; - - public enum ConversionState - { - Unknown, - - Ready, - InProgress, - Done, - Failed, - } - - public ConversionPreset ConversionPreset - { - get; - private set; - } - - public string InputFilePath - { - get; - private set; - } - - public string OutputFilePath - { - get; - private set; - } - - public ConversionState State - { - get - { - return this.state; - } - - private set - { - this.state = value; - this.NotifyPropertyChanged(); - } - } - - public float Progress - { - get - { - return this.progress; - } - - private set - { - this.progress = value; - this.NotifyPropertyChanged(); - } - } - - public string ExitingMessage - { - get - { - return this.exitingMessage; - } - - set - { - this.exitingMessage = value; - this.NotifyPropertyChanged(); - } - } - - public void StartConvertion() - { - if (this.ConversionPreset == null) - { - throw new Exception("The conversion preset must be valid."); - } - - Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath); - - string arguments = string.Empty; - switch (this.ConversionPreset.OutputType) - { - case OutputType.Mp3: - arguments = string.Format("-n -stats -i \"{0}\" -qscale:a 2 \"{1}\"", this.InputFilePath, this.OutputFilePath); - break; - - case OutputType.Ogg: - arguments = string.Format("-n -stats -i \"{0}\" -acodec libvorbis -qscale:a 2 \"{1}\"", this.InputFilePath, this.OutputFilePath); - break; - - case OutputType.Flac: - case OutputType.Wav: - arguments = string.Format("-n -stats -i \"{0}\" \"{1}\"", this.InputFilePath, this.OutputFilePath); - break; - - default: - throw new NotImplementedException("Converter not implemented for output file type " + this.ConversionPreset.OutputType); - } - - if (string.IsNullOrEmpty(arguments) || this.ffmpegProcessStartInfo == null) - { - return; - } - - this.State = ConversionState.InProgress; - - try - { - Diagnostics.Log(string.Empty); - this.ffmpegProcessStartInfo.Arguments = arguments; - Diagnostics.Log("Execute command: {0} {1}.", this.ffmpegProcessStartInfo.FileName, this.ffmpegProcessStartInfo.Arguments); - using (Process exeProcess = Process.Start(this.ffmpegProcessStartInfo)) - { - using (StreamReader reader = exeProcess.StandardError) - { - while (!reader.EndOfStream) - { - string result = reader.ReadLine(); - - this.ParseFFMPEGOutput(result); - - Diagnostics.Log("ffmpeg output: {0}", result); - } - } - - exeProcess.WaitForExit(); - } - } - catch - { - this.State = ConversionState.Failed; - throw; - } - - if (!string.IsNullOrEmpty(this.ExitingMessage)) - { - this.State = ConversionState.Failed; - return; - } - - this.Progress = 1f; - this.State = ConversionState.Done; - - Diagnostics.Log("\nDone!"); - } - - private void Initialize() - { - if (this.ConversionPreset == null) - { - throw new Exception("The conversion preset must be valid."); - } - - this.ffmpegProcessStartInfo = null; - - string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); - string ffmpegPath = string.Format("{0}\\ffmpeg.exe", applicationDirectory); - if (!System.IO.File.Exists(ffmpegPath)) - { - Diagnostics.Log("Can't find ffmpeg executable ({0}). Try to reinstall the application.", ffmpegPath); - return; - } - - this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath); - - this.ffmpegProcessStartInfo.CreateNoWindow = true; - this.ffmpegProcessStartInfo.UseShellExecute = false; - this.ffmpegProcessStartInfo.RedirectStandardOutput = true; - this.ffmpegProcessStartInfo.RedirectStandardError = true; - - this.State = ConversionState.Ready; - } - - private void ParseFFMPEGOutput(string input) - { - Match match = this.durationRegex.Match(input); - if (match.Success && match.Groups.Count >= 6) - { - int hours = int.Parse(match.Groups[1].Value); - int minutes = int.Parse(match.Groups[2].Value); - int seconds = int.Parse(match.Groups[3].Value); - int milliseconds = int.Parse(match.Groups[4].Value); - float bitrate = float.Parse(match.Groups[5].Value); - this.fileDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds); - return; - } - - match = this.progressRegex.Match(input); - if (match.Success && match.Groups.Count >= 7) - { - int size = int.Parse(match.Groups[1].Value); - int hours = int.Parse(match.Groups[2].Value); - int minutes = int.Parse(match.Groups[3].Value); - int seconds = int.Parse(match.Groups[4].Value); - int milliseconds = int.Parse(match.Groups[5].Value); - float bitrate = 0f; - float.TryParse(match.Groups[6].Value, out bitrate); - - this.actualConvertedDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds); - - this.Progress = this.actualConvertedDuration.Ticks / (float)this.fileDuration.Ticks; - return; - } - - if (input.Contains("Exiting.")) - { - this.ExitingMessage = input; - } - } - - private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - } -} diff --git a/Application/FileConverter/ConversionJobs/ConversionJob.cs b/Application/FileConverter/ConversionJobs/ConversionJob.cs new file mode 100644 index 0000000..5968f77 --- /dev/null +++ b/Application/FileConverter/ConversionJobs/ConversionJob.cs @@ -0,0 +1,269 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ConversionJobs +{ + using System; + using System.ComponentModel; + using System.Runtime.CompilerServices; + using System.Text; + + public class ConversionJob : INotifyPropertyChanged + { + private float progress = 0f; + private ConversionState state = ConversionState.Unknown; + private string errorMessage = string.Empty; + private string initialInputPath = string.Empty; + + public ConversionJob() + { + this.State = ConversionState.Unknown; + this.ConversionPreset = null; + this.InputFilePath = string.Empty; + } + + public ConversionJob(ConversionPreset conversionPreset) : this() + { + if (conversionPreset == null) + { + throw new ArgumentNullException("conversionPreset"); + } + + this.ConversionPreset = conversionPreset; + } + + public event PropertyChangedEventHandler PropertyChanged; + + public enum ConversionState + { + Unknown, + + Ready, + InProgress, + Done, + Failed, + } + + public ConversionPreset ConversionPreset + { + get; + private set; + } + + public string InputFilePath + { + get; + private set; + } + + public string OutputFilePath + { + get; + private set; + } + + public ConversionState State + { + get + { + return this.state; + } + + private set + { + this.state = value; + this.NotifyPropertyChanged(); + } + } + + public float Progress + { + get + { + return this.progress; + } + + protected set + { + this.progress = value; + this.NotifyPropertyChanged(); + } + } + + public string ErrorMessage + { + get + { + return this.errorMessage; + } + + private set + { + this.errorMessage = value; + this.NotifyPropertyChanged(); + } + } + + public void PrepareConversion(string inputFilePath) + { + if (string.IsNullOrEmpty(inputFilePath)) + { + throw new ArgumentNullException("inputFilePath"); + } + + if (this.ConversionPreset == null) + { + throw new Exception("The conversion preset must be valid."); + } + + this.initialInputPath = inputFilePath; + this.InputFilePath = inputFilePath; + this.OutputFilePath = this.ConversionPreset.GenerateOutputFilePath(inputFilePath); + + if (!PathHelpers.IsPathValid(this.OutputFilePath)) + { + this.ConvertionFailed("Invalid output path generated by output file path template."); + Diagnostics.Log(string.Format("Invalid output path generated: {0} from input: {1}.", this.OutputFilePath, this.InputFilePath)); + return; + } + + if (this.OutputFilePath == this.InputFilePath) + { + // If the input post conversion action is to move or delete the input file, change its name in order to keep the output name intact. + if (this.ConversionPreset.InputPostConversionAction == InputPostConversionAction.MoveInArchiveFolder || + this.ConversionPreset.InputPostConversionAction == InputPostConversionAction.Delete) + { + string inputExtension = System.IO.Path.GetExtension(this.InputFilePath); + string pathWithoutExtension = this.InputFilePath.Substring(0, this.InputFilePath.Length - inputExtension.Length); + this.InputFilePath = PathHelpers.GenerateUniquePath(pathWithoutExtension + "_TEMP" + inputExtension); + System.IO.File.Move(inputFilePath, this.InputFilePath); + } + } + + // Create output folder that doesn't exist. + { + StringBuilder path = new StringBuilder(this.OutputFilePath.Length); + foreach (string directory in PathHelpers.GetDirectories(this.OutputFilePath)) + { + path.Append(directory); + path.Append('\\'); + + if (!System.IO.Directory.Exists(path.ToString())) + { + try + { + System.IO.Directory.CreateDirectory(path.ToString()); + } + catch (Exception) + { + this.ConvertionFailed("Invalid output path generated by output file path template."); + Diagnostics.Log(string.Format("Can't create directories for path {0}", this.OutputFilePath)); + return; + } + } + } + } + + // Make the output path valid. + try + { + this.OutputFilePath = PathHelpers.GenerateUniquePath(this.OutputFilePath); + } + catch (Exception exception) + { + this.ConvertionFailed("Can't generate a valid output filename."); + Diagnostics.Log(exception.Message); + return; + } + + this.Initialize(); + + if (this.State == ConversionState.Unknown) + { + this.State = ConversionState.Ready; + } + } + + public void StartConvertion() + { + if (this.ConversionPreset == null) + { + throw new Exception("The conversion preset must be valid."); + } + + if (this.State != ConversionState.Ready) + { + throw new Exception("Invalid conversion state."); + } + + Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath); + + this.State = ConversionState.InProgress; + + this.Convert(); + + if (this.State != ConversionState.Failed) + { + this.OnConversionSucceed(); + } + } + + protected virtual void Convert() + { + } + + protected virtual void Initialize() + { + } + + protected virtual void OnConversionSucceed() + { + Diagnostics.Log("Conversion Succeed!"); + + // Apply the input post conversion action. + switch (this.ConversionPreset.InputPostConversionAction) + { + case InputPostConversionAction.None: + break; + + case InputPostConversionAction.MoveInArchiveFolder: + string basePath = System.IO.Path.GetDirectoryName(this.initialInputPath); + string inputFilename = System.IO.Path.GetFileName(this.initialInputPath); + string archivePath = basePath + "\\" + this.ConversionPreset.ConversionArchiveFolderName; + if (!System.IO.Directory.Exists(archivePath)) + { + System.IO.Directory.CreateDirectory(archivePath); + } + + string newPath = PathHelpers.GenerateUniquePath(archivePath + "\\" + inputFilename); + System.IO.File.Move(this.InputFilePath, newPath); + Diagnostics.Log("Input file moved in archive folder: '{0}'", newPath); + break; + + case InputPostConversionAction.Delete: + System.IO.File.Delete(this.InputFilePath); + Diagnostics.Log("Input file deleted: '{0}'", this.initialInputPath); + break; + } + + Diagnostics.Log(string.Empty); + + this.Progress = 1f; + this.State = ConversionState.Done; + Diagnostics.Log("Conversion Done!"); + } + + protected void ConvertionFailed(string exitingMessage) + { + this.State = ConversionState.Failed; + this.ErrorMessage = exitingMessage; + } + + protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") + { + if (this.PropertyChanged != null) + { + this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + } +} diff --git a/Application/FileConverter/ConversionJobs/ConversionJobFactory.cs b/Application/FileConverter/ConversionJobs/ConversionJobFactory.cs new file mode 100644 index 0000000..c919ca4 --- /dev/null +++ b/Application/FileConverter/ConversionJobs/ConversionJobFactory.cs @@ -0,0 +1,14 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ConversionJobs +{ + public static class ConversionJobFactory + { + public static ConversionJob Create(ConversionPreset conversionPreset) + { + ConversionJob conversionJob = new ConversionJob_FFMPEG(conversionPreset); + + return conversionJob; + } + } +} diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs new file mode 100644 index 0000000..11e25c5 --- /dev/null +++ b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs @@ -0,0 +1,307 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ConversionJobs +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Text.RegularExpressions; + + public class ConversionJob_FFMPEG : ConversionJob + { + private readonly Regex durationRegex = new Regex(@"Duration:\s*([0-9][0-9]):([0-9][0-9]):([0-9][0-9])\.([0-9][0-9]),.*bitrate:\s*([0-9]+) kb\/s"); + private readonly Regex progressRegex = new Regex(@"size=\s*([0-9]+)kB\s+time=([0-9][0-9]):([0-9][0-9]):([0-9][0-9]).([0-9][0-9])\s+bitrate=\s*([0-9]+.[0-9])kbits\/s"); + + private TimeSpan fileDuration; + private TimeSpan actualConvertedDuration; + + private ProcessStartInfo ffmpegProcessStartInfo; + + public ConversionJob_FFMPEG() : base() + { + } + + public ConversionJob_FFMPEG(ConversionPreset conversionPreset) : base(conversionPreset) + { + } + + protected override void Initialize() + { + base.Initialize(); + + if (this.ConversionPreset == null) + { + throw new Exception("The conversion preset must be valid."); + } + + this.ffmpegProcessStartInfo = null; + + string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + string ffmpegPath = string.Format("{0}\\ffmpeg.exe", applicationDirectory); + if (!System.IO.File.Exists(ffmpegPath)) + { + this.ConvertionFailed("Can't find ffmpeg executable. You should try to reinstall the application."); + Diagnostics.Log("Can't find ffmpeg executable ({0}). Try to reinstall the application.", ffmpegPath); + return; + } + + this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath); + + this.ffmpegProcessStartInfo.CreateNoWindow = true; + this.ffmpegProcessStartInfo.UseShellExecute = false; + this.ffmpegProcessStartInfo.RedirectStandardOutput = true; + this.ffmpegProcessStartInfo.RedirectStandardError = true; + + string arguments = string.Empty; + switch (this.ConversionPreset.OutputType) + { + case OutputType.Wav: + { + EncodingMode encodingMode = this.ConversionPreset.GetSettingsValue("Encoding"); + string encoderArgs = string.Format("-acodec {0}", this.WAVEncodingToCodecArgument(encodingMode)); + arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs); + } + + break; + + case OutputType.Mp3: + { + string encoderArgs = string.Empty; + EncodingMode encodingMode = this.ConversionPreset.GetSettingsValue("Encoding"); + int encodingQuality = this.ConversionPreset.GetSettingsValue("Bitrate"); + switch (encodingMode) + { + case EncodingMode.Mp3VBR: + encoderArgs = string.Format("-codec:a libmp3lame -q:a {0}", this.MP3VBRBitrateToQualityIndex(encodingQuality)); + break; + + case EncodingMode.Mp3CBR: + encoderArgs = string.Format("-codec:a libmp3lame -b:a {0}k", encodingQuality); + break; + + default: + break; + } + + arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs); + } + + break; + + case OutputType.Ogg: + { + int encodingQuality = this.ConversionPreset.GetSettingsValue("Bitrate"); + string encoderArgs = string.Format("-codec:a libvorbis -qscale:a {0}", this.OGGVBRBitrateToQualityIndex(encodingQuality)); + arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs); + } + + break; + + case OutputType.Flac: + arguments = string.Format("-n -stats -i \"{0}\" \"{1}\"", this.InputFilePath, this.OutputFilePath); + break; + + default: + throw new NotImplementedException("Converter not implemented for output file type " + this.ConversionPreset.OutputType); + } + + if (string.IsNullOrEmpty(arguments)) + { + throw new Exception("Invalid ffmpeg process arguments."); + } + + this.ffmpegProcessStartInfo.Arguments = arguments; + } + + protected override void Convert() + { + if (this.ConversionPreset == null) + { + throw new Exception("The conversion preset must be valid."); + } + + Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath); + Diagnostics.Log(string.Empty); + Diagnostics.Log("Execute command: {0} {1}.", this.ffmpegProcessStartInfo.FileName, this.ffmpegProcessStartInfo.Arguments); + + try + { + using (Process exeProcess = Process.Start(this.ffmpegProcessStartInfo)) + { + using (StreamReader reader = exeProcess.StandardError) + { + while (!reader.EndOfStream) + { + string result = reader.ReadLine(); + + this.ParseFFMPEGOutput(result); + + Diagnostics.Log("ffmpeg output: {0}", result); + } + } + + exeProcess.WaitForExit(); + } + } + catch + { + this.ConvertionFailed("Failed to launch FFMPEG process."); + throw; + } + } + + private int MP3VBRBitrateToQualityIndex(int bitrate) + { + switch (bitrate) + { + case 245: + return 0; + + case 225: + return 1; + + case 190: + return 2; + + case 175: + return 3; + + case 165: + return 4; + + case 130: + return 5; + + case 115: + return 6; + + case 100: + return 7; + + case 85: + return 8; + + case 65: + return 9; + } + + throw new Exception("Unknown VBR bitrate."); + } + + /// + /// Convert bitrate in vorbis encoder quality index. + /// + /// Wanted bitrate value. + /// The vorbis encoder quality index associated to the given bitrate value. + /// http://wiki.hydrogenaud.io/index.php?title=Recommended_Ogg_Vorbis + private int OGGVBRBitrateToQualityIndex(int bitrate) + { + switch (bitrate) + { + case 500: + return 10; + + case 320: + return 9; + + case 256: + return 8; + + case 224: + return 7; + + case 192: + return 6; + + case 160: + return 5; + + case 128: + return 4; + + case 112: + return 3; + + case 96: + return 2; + + case 80: + return 1; + + case 64: + return 0; + + case 48: + return -1; + + case 32: + return -2; + } + + throw new Exception("Unknown VBR bitrate."); + } + + /// + /// Convert encoding mode setting to ffmpeg argument option. + /// + /// The encoding mode setting. + /// Returns the ffmpeg argument corresponding to the given encoding mode. + /// https://trac.ffmpeg.org/wiki/audio%20types + private string WAVEncodingToCodecArgument(EncodingMode encoding) + { + switch (encoding) + { + case EncodingMode.Wav8: + return "pcm_s8le"; + + case EncodingMode.Wav16: + return "pcm_s16le"; + + case EncodingMode.Wav24: + return "pcm_s24le"; + + case EncodingMode.Wav32: + return "pcm_s32le"; + } + + throw new Exception("Unknown Wav encoding."); + } + + private void ParseFFMPEGOutput(string input) + { + Match match = this.durationRegex.Match(input); + if (match.Success && match.Groups.Count >= 6) + { + int hours = int.Parse(match.Groups[1].Value); + int minutes = int.Parse(match.Groups[2].Value); + int seconds = int.Parse(match.Groups[3].Value); + int milliseconds = int.Parse(match.Groups[4].Value); + float bitrate = float.Parse(match.Groups[5].Value); + this.fileDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds); + return; + } + + match = this.progressRegex.Match(input); + if (match.Success && match.Groups.Count >= 7) + { + int size = int.Parse(match.Groups[1].Value); + int hours = int.Parse(match.Groups[2].Value); + int minutes = int.Parse(match.Groups[3].Value); + int seconds = int.Parse(match.Groups[4].Value); + int milliseconds = int.Parse(match.Groups[5].Value); + float bitrate = 0f; + float.TryParse(match.Groups[6].Value, out bitrate); + + this.actualConvertedDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds); + + this.Progress = this.actualConvertedDuration.Ticks / (float)this.fileDuration.Ticks; + return; + } + + if (input.Contains("Exiting.")) + { + this.ConvertionFailed(input); + } + } + } +} diff --git a/Application/FileConverter/ConversionPreset.cs b/Application/FileConverter/ConversionPreset.cs deleted file mode 100644 index 85899f3..0000000 --- a/Application/FileConverter/ConversionPreset.cs +++ /dev/null @@ -1,151 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -using System.Collections.Generic; - -namespace FileConverter -{ - using System.ComponentModel; - using System.Linq; - using System.Runtime.CompilerServices; - using System.Xml.Serialization; - - using FileConverter.Annotations; - - [XmlRoot] - [XmlType] - public class ConversionPreset : INotifyPropertyChanged, IDataErrorInfo - { - private string name; - - private OutputType outputType; - - private List inputTypes; - - public ConversionPreset() - { - this.Name = "New Preset"; - } - - public ConversionPreset(string name, OutputType outputType, string[] inputTypes) - { - this.Name = name; - this.OutputType = outputType; - this.InputTypes = new List(); - this.InputTypes.AddRange(inputTypes); - } - - public event PropertyChangedEventHandler PropertyChanged; - - [XmlAttribute] - public string Name - { - get - { - return this.name; - } - - set - { - this.name = value; - this.OnPropertyChanged(); - } - } - - [XmlAttribute] - public OutputType OutputType - { - get - { - return outputType; - } - - set - { - outputType = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public List InputTypes - { - get - { - return inputTypes; - } - - set - { - inputTypes = value; - this.OnPropertyChanged(); - } - } - - [XmlIgnore] - public ConversionPreset.Setting[] Settings - { - get; - set; - } - - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - public class Setting - { - } - - public string this[string columnName] - { - get - { - return this.Validate(columnName); - } - } - - public string Error - { - get - { - return this.Validate("Name"); - } - } - - private string Validate(string properyName) - { - // Return error message if there is an error, else return empty or null string. - switch (properyName) - { - case "Name": - { - if (string.IsNullOrEmpty(this.Name)) - { - return "The preset name can't be empty."; - } - - if (this.Name.Contains(";")) - { - return "The preset name can't contains the character ';'."; - } - - Application application = Application.Current as Application; - if (application?.Settings != null) - { - int count = application.Settings.ConversionPresets.Count(match => match.name == this.Name); - if (count > 1) - { - return "The preset name is already used."; - } - } - } - - break; - } - - return string.Empty; - } - } -} diff --git a/Application/FileConverter/ConversionPreset/ConversionPreset.cs b/Application/FileConverter/ConversionPreset/ConversionPreset.cs new file mode 100644 index 0000000..04e9873 --- /dev/null +++ b/Application/FileConverter/ConversionPreset/ConversionPreset.cs @@ -0,0 +1,511 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Xml.Serialization; + + using FileConverter.Annotations; + using FileConverter.ValueConverters; + + [XmlRoot] + [XmlType] + public class ConversionPreset : INotifyPropertyChanged, IDataErrorInfo, IXmlSerializable + { + private string name; + private OutputType outputType; + private List inputTypes; + private InputPostConversionAction inputPostConversionAction; + private ConversionSettings settings = new ConversionSettings(); + private string outputFileNameTemplate; + private FileNameConverter outputFileNameConverter = new FileNameConverter(); + + public ConversionPreset() + { + this.Name = "New Preset"; + } + + public ConversionPreset(string name, OutputType outputType, string[] inputTypes) + { + this.Name = name; + this.OutputType = outputType; + List inputTypeList = new List(); + inputTypeList.AddRange(inputTypes); + this.InputTypes = inputTypeList; + + this.outputFileNameTemplate = "(p)(f)"; + } + + public event PropertyChangedEventHandler PropertyChanged; + + [XmlAttribute] + public string Name + { + get + { + return this.name; + } + + set + { + this.name = value; + this.OnPropertyChanged(); + } + } + + [XmlAttribute] + public OutputType OutputType + { + get + { + return this.outputType; + } + + set + { + this.outputType = value; + this.InitializeDefaultSettings(this.outputType); + this.OnPropertyChanged(); + } + } + + [XmlElement] + public List InputTypes + { + get + { + return this.inputTypes; + } + + set + { + this.inputTypes = value; + for (int index = 0; index < this.inputTypes.Count; index++) + { + this.inputTypes[index] = this.inputTypes[index].ToLowerInvariant(); + } + + this.OnPropertyChanged(); + } + } + + [XmlElement] + public InputPostConversionAction InputPostConversionAction + { + get + { + return this.inputPostConversionAction; + } + + set + { + this.inputPostConversionAction = value; + this.OnPropertyChanged(); + } + } + + [XmlElement("Settings")] + public ConversionSetting[] XmlSerializableSettings + { + get + { + int index = 0; + ConversionSetting[] settings = new ConversionSetting[this.settings.Count]; + foreach (KeyValuePair keyValuePair in this.settings) + { + settings[index] = new ConversionSetting(keyValuePair); + index++; + } + + return settings; + } + + set + { + if (value != null) + { + for (int index = 0; index < value.Length; index++) + { + this.SetSettingsValue(value[index].Key, value[index].Value); + } + } + + this.OnPropertyChanged("Settings"); + } + } + + [XmlElement] + public string OutputFileNameTemplate + { + get + { + return this.outputFileNameTemplate; + } + + set + { + this.outputFileNameTemplate = value; + this.OnPropertyChanged(); + } + } + + [XmlIgnore] + public string ConversionArchiveFolderName + { + get + { + return "Conversion Archives"; + } + } + + [XmlIgnore] + public IConversionSettings Settings + { + get + { + return this.settings; + } + + set + { + if (value == null) + { + return; + } + + foreach (KeyValuePair conversionSetting in value) + { + if (!this.settings.ContainsKey(conversionSetting.Key)) + { + this.settings.Add(conversionSetting.Key, conversionSetting.Value); + } + else + { + this.settings[conversionSetting.Key] = conversionSetting.Value; + } + } + + this.OnPropertyChanged(); + } + } + + public string Error + { + get + { + string errorString = this.Validate("Name"); + if (!string.IsNullOrEmpty(errorString)) + { + return errorString; + } + + errorString = this.Validate("OutputFileNameTemplate"); + if (!string.IsNullOrEmpty(errorString)) + { + return errorString; + } + + return string.Empty; + } + } + + public string this[string columnName] + { + get + { + return this.Validate(columnName); + } + } + + public void OnDeserializationComplete() + { + for (int index = 0; index < this.InputTypes.Count; index++) + { + this.InputTypes[index] = this.InputTypes[index].ToLowerInvariant(); + } + } + + public void AddInputType(string inputType) + { + if (this.inputTypes.Contains(inputType)) + { + return; + } + + this.inputTypes.Add(inputType); + this.OnPropertyChanged("InputTypes"); + } + + public void RemoveInputType(string inputType) + { + if (this.inputTypes.Remove(inputType)) + { + this.OnPropertyChanged("InputTypes"); + } + } + + public string GenerateOutputFilePath(string inputFilePath) + { + return (string)this.outputFileNameConverter.Convert(new object[] { inputFilePath, this.OutputType, this.OutputFileNameTemplate }, typeof(string), null, null); + } + + public void SetSettingsValue(string settingsKey, string value) + { + if (string.IsNullOrEmpty(settingsKey)) + { + throw new ArgumentNullException("key"); + } + + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentNullException("value"); + } + + if (!this.IsRelevantSetting(settingsKey)) + { + return; + } + + if (!this.settings.ContainsKey(settingsKey)) + { + this.settings.Add(settingsKey, value); + } + + this.settings[settingsKey] = value; + + this.OnPropertyChanged("Settings"); + } + + public string GetSettingsValue(string settingsKey) + { + if (string.IsNullOrEmpty(settingsKey)) + { + throw new ArgumentNullException("key"); + } + + if (this.settings.ContainsKey(settingsKey)) + { + return this.settings[settingsKey]; + } + + return null; + } + + public T GetSettingsValue(string settingsKey) + { + string settingsValue = this.GetSettingsValue(settingsKey); + + Type type = typeof(T); + if (type.IsEnum) + { + return (T)System.Enum.Parse(type, settingsValue); + } + + return (T)System.Convert.ChangeType(settingsValue, type); + } + + [NotifyPropertyChangedInvocator] + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private bool IsRelevantSetting(string settingsKey) + { + switch (this.OutputType) + { + case OutputType.Wav: + switch (settingsKey) + { + case "Encoding": + return true; + } + + break; + + case OutputType.Mp3: + switch (settingsKey) + { + case "Encoding": + case "Bitrate": + return true; + } + + break; + + case OutputType.Ogg: + switch (settingsKey) + { + case "Bitrate": + return true; + } + + break; + } + + return false; + } + + private void InitializeDefaultSettings(OutputType outputType) + { + if (outputType == OutputType.Wav) + { + this.InitializeSettingsValue("Encoding", "Wav16"); + } + + if (outputType == OutputType.Mp3) + { + this.InitializeSettingsValue("Encoding", EncodingMode.Mp3VBR.ToString()); + this.InitializeSettingsValue("Bitrate", "190"); + } + + if (outputType == OutputType.Ogg) + { + this.InitializeSettingsValue("Bitrate", "160"); + } + + this.OnPropertyChanged("Settings"); + } + + private void InitializeSettingsValue(string settingsKey, string value) + { + if (string.IsNullOrEmpty(settingsKey)) + { + throw new ArgumentNullException("key"); + } + + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentNullException("value"); + } + + if (!this.settings.ContainsKey(settingsKey)) + { + this.settings.Add(settingsKey, value); + } + } + + private string Validate(string propertyName) + { + // Return error message if there is an error, else return empty or null string. + switch (propertyName) + { + case "Name": + { + if (string.IsNullOrEmpty(this.Name)) + { + return "The preset name can't be empty."; + } + + if (this.Name.Contains(";")) + { + return "The preset name can't contains the character ';'."; + } + + Application application = Application.Current as Application; + int? count = application?.Settings?.ConversionPresets?.Count(match => match?.name == this.Name); + if (count > 1) + { + return "The preset name is already used."; + } + } + + break; + + case "OutputFileNameTemplate": + { + string sampleOutputFilePath = this.GenerateOutputFilePath(FileConverter.Properties.Resources.OuputFileNameTemplateSample); + if (string.IsNullOrEmpty(sampleOutputFilePath)) + { + return "The output filename template must produce a non empty result."; + } + + if (!PathHelpers.IsPathValid(sampleOutputFilePath)) + { + // Diagnostic to feedback purpose. + // Drive letter. + if (!PathHelpers.IsPathDriveLetterValid(sampleOutputFilePath)) + { + return "The output filename template must define a root (for example c:\\, use (p) to use the input file path)."; + } + + // File name. + string filename = PathHelpers.GetFileName(sampleOutputFilePath); + if (filename == null) + { + return "The output file name must not be empty (use (f) to use the name of the input file)."; + } + + char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars(); + for (int index = 0; index < invalidFileNameChars.Length; index++) + { + if (filename.Contains(invalidFileNameChars[index])) + { + return "The output file name must not contains the character '" + invalidFileNameChars[index] + "'."; + } + } + + // Directory names. + string path = sampleOutputFilePath.Substring(3, sampleOutputFilePath.Length - 3 - filename.Length); + char[] invalidPathChars = System.IO.Path.GetInvalidPathChars(); + for (int index = 0; index < invalidPathChars.Length; index++) + { + if (string.IsNullOrEmpty(path)) + { + return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; + } + + if (path.Contains(invalidPathChars[index])) + { + return "The output directory name must not contains the character '" + invalidPathChars[index] + "'."; + } + } + + string[] directories = path.Split('\\'); + for (int index = 0; index < directories.Length; ++index) + { + string directoryName = directories[index]; + if (string.IsNullOrEmpty(directoryName)) + { + return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; + } + } + + return "The output filename template is invalid"; + } + } + + break; + } + + return string.Empty; + } + + public struct ConversionSetting + { + public ConversionSetting(KeyValuePair keyValuePair) + { + this.Key = keyValuePair.Key; + this.Value = keyValuePair.Value; + } + + [XmlAttribute] + public string Key + { + get; + set; + } + + [XmlAttribute] + public string Value + { + get; + set; + } + } + } +} diff --git a/Application/FileConverter/ConversionPreset/ConversionSettings.cs b/Application/FileConverter/ConversionPreset/ConversionSettings.cs new file mode 100644 index 0000000..41ce227 --- /dev/null +++ b/Application/FileConverter/ConversionPreset/ConversionSettings.cs @@ -0,0 +1,10 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System.Collections.Generic; + + public class ConversionSettings : Dictionary, IConversionSettings + { + } +} \ No newline at end of file diff --git a/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs b/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs new file mode 100644 index 0000000..22eb066 --- /dev/null +++ b/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs @@ -0,0 +1,84 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System.Collections; + using System.Collections.Generic; + + public struct ConversionSettingsOverride : IConversionSettings + { + private string key; + private string value; + + public ConversionSettingsOverride(string key, string value) + { + this.key = key; + this.value = value; + } + + public int Count + { + get + { + return 1; + } + } + + public IEnumerable Keys + { + get + { + yield return this.key; + } + } + + public IEnumerable Values + { + get + { + yield return this.value; + } + } + + public string this[string key] + { + get + { + if (key == this.key) + { + return this.value; + } + + throw new KeyNotFoundException(); + } + } + + public IEnumerator> GetEnumerator() + { + yield return new KeyValuePair(this.key, this.value); + } + + public bool ContainsKey(string key) + { + return key == this.key; + } + + public bool TryGetValue(string key, out string value) + { + value = null; + + if (key == this.key) + { + value = this.value; + return true; + } + + return false; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + } +} diff --git a/Application/FileConverter/ConversionPreset/IConversionSettings.cs b/Application/FileConverter/ConversionPreset/IConversionSettings.cs new file mode 100644 index 0000000..f1b1a33 --- /dev/null +++ b/Application/FileConverter/ConversionPreset/IConversionSettings.cs @@ -0,0 +1,10 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System.Collections.Generic; + + public interface IConversionSettings : IReadOnlyDictionary + { + } +} \ No newline at end of file diff --git a/Application/FileConverter/EncodingMode.cs b/Application/FileConverter/EncodingMode.cs new file mode 100644 index 0000000..36e8d7b --- /dev/null +++ b/Application/FileConverter/EncodingMode.cs @@ -0,0 +1,17 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + public enum EncodingMode + { + Wav8, + Wav16, + Wav24, + Wav32, + + Mp3VBR, + Mp3CBR, + + OggVBR, + } +} \ No newline at end of file diff --git a/Application/FileConverter/FileConverter.csproj b/Application/FileConverter/FileConverter.csproj index 4e77add..9c788ee 100644 --- a/Application/FileConverter/FileConverter.csproj +++ b/Application/FileConverter/FileConverter.csproj @@ -42,7 +42,7 @@ bin\x64\Release\ - Resources\ApplicationIcon-256x256.ico + Resources\ApplicationIcon.ico @@ -51,7 +51,9 @@ + + @@ -71,18 +73,53 @@ MSBuild:Compile Designer + + EncodingQualitySliderControl.xaml + + + + + + + + + + + + Resources.en.resx + True + True + - + + + + + + + + + + + + DiagnosticsWindow.xaml + + + SettingsWindow.xaml + + Designer + MSBuild:Compile + Designer MSBuild:Compile @@ -96,7 +133,7 @@ Code - + MainWindow.xaml @@ -109,9 +146,12 @@ - + + true + Code + true True @@ -123,8 +163,12 @@ Settings.settings True + + PublicResXFileCodeGenerator + Resources.en.Designer.cs + - ResXFileCodeGenerator + PublicResXFileCodeGenerator Resources.Designer.cs @@ -140,11 +184,10 @@ - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + C:\Music\Artist\Album\Song.wav + + + (p): input file path +(f): input filename +(o): output extension type +(i): input extension type +(d0): input parent folder +(d1): input sub parent folder +... +use maj for uppercase version + + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.resx b/Application/FileConverter/Properties/Resources.resx index af7dbeb..e7a1e13 100644 --- a/Application/FileConverter/Properties/Resources.resx +++ b/Application/FileConverter/Properties/Resources.resx @@ -46,7 +46,7 @@ mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with - : System.Serialization.Formatters.Binary.BinaryFormatter + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 @@ -60,6 +60,7 @@ : and then encoded with base64 encoding. --> + @@ -68,9 +69,10 @@ - + + @@ -85,9 +87,10 @@ - + + @@ -109,9 +112,22 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + C:\Music\Artist\Album\Song.wav + + + (p): input file path +(f): input filename +(o): output extension type +(i): input extension type +(d0): input parent folder +(d1): input sub parent folder +... +use maj for uppercase version + \ No newline at end of file diff --git a/Application/FileConverter/Resources/ApplicationIcon-16x16.ico b/Application/FileConverter/Resources/ApplicationIcon-16x16.ico deleted file mode 100644 index 1fe14b0..0000000 Binary files a/Application/FileConverter/Resources/ApplicationIcon-16x16.ico and /dev/null differ diff --git a/Application/FileConverter/Resources/ApplicationIcon-256x256.ico b/Application/FileConverter/Resources/ApplicationIcon-256x256.ico deleted file mode 100644 index 123b9d0..0000000 Binary files a/Application/FileConverter/Resources/ApplicationIcon-256x256.ico and /dev/null differ diff --git a/Application/FileConverter/Resources/ApplicationIcon.ico b/Application/FileConverter/Resources/ApplicationIcon.ico new file mode 100644 index 0000000..1b0191e Binary files /dev/null and b/Application/FileConverter/Resources/ApplicationIcon.ico differ diff --git a/Application/FileConverter/Settings.cs b/Application/FileConverter/Settings.cs index 9725add..d749387 100644 --- a/Application/FileConverter/Settings.cs +++ b/Application/FileConverter/Settings.cs @@ -5,18 +5,17 @@ namespace FileConverter using System; using System.Collections.Generic; using System.Collections.ObjectModel; + using System.ComponentModel; using System.Diagnostics; using System.IO; + using System.Linq; using System.Reflection; + using System.Runtime.CompilerServices; using System.Security.Principal; using System.Windows; - using System.ComponentModel; - using System.Linq; - using System.Runtime.CompilerServices; - - using Microsoft.Win32; using FileConverter.Annotations; + using Microsoft.Win32; public class Settings : INotifyPropertyChanged, IDataErrorInfo { @@ -26,6 +25,29 @@ namespace FileConverter public event PropertyChangedEventHandler PropertyChanged; + public ObservableCollection ConversionPresets + { + get { return this.conversionPresets; } + set { this.conversionPresets = value; } + } + + public string Error + { + get + { + for (int index = 0; index < this.ConversionPresets.Count; index++) + { + string error = this.ConversionPresets[index].Error; + if (!string.IsNullOrEmpty(error)) + { + return error; + } + } + + return string.Empty; + } + } + private static bool IsInAdmininstratorPrivileges { get @@ -34,16 +56,45 @@ namespace FileConverter } } - public ObservableCollection ConversionPresets + public string this[string columnName] { - get { return this.conversionPresets; } - set { this.conversionPresets = value; } + get + { + return this.Error; + } } - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + public static void ApplyTemporarySettings() { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + // Load temporary settings. + string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); + if (!File.Exists(temporaryFilePath)) + { + return; + } + + ICollection conversionPresets = new ObservableCollection(); + XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref conversionPresets); + + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); + if (registryKey == null) + { + MessageBox.Show("Can't apply settings in registry. (code 0x03)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return; + } + + // Compute the registry entries data from settings. + Dictionary> registryEntries = ComputeRegistryEntriesFromConvertionPresets(conversionPresets); + + bool succeed = Settings.ApplyRegistryModifications(registryEntries); + + if (succeed) + { + // Copy temporary settings file to the real settings file. + string userFilePath = Settings.GetUserSettingsFilePath(); + File.Copy(temporaryFilePath, userFilePath, true); + File.Delete(temporaryFilePath); + } } public ConversionPreset GetPresetFromName(string presetName) @@ -118,51 +169,18 @@ namespace FileConverter } } - public static void ApplyTemporarySettings() - { - // Load temporary settings. - string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); - if (!File.Exists(temporaryFilePath)) - { - return; - } - - ICollection conversionPresets = new ObservableCollection(); - XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref conversionPresets); - - RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); - if (registryKey == null) - { - MessageBox.Show("Can't apply settings in registry.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return; - } - - // Compute the registry entries data from settings. - Dictionary> registryEntries = ComputeRegistryEntriesFromConvertionPresets(conversionPresets); - - bool succeed = Settings.ApplyRegistryModifications(registryEntries); - - if (succeed) - { - // Copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - } - private static bool ApplyRegistryModifications(Dictionary> registryEntries) { if (!Settings.IsInAdmininstratorPrivileges) { - MessageBox.Show("Can't apply settings in registry because the application is not in administrator privileges.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Can't apply settings in registry because the application is not in administrator privileges. (code 0x04)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter", RegistryKeyPermissionCheck.ReadWriteSubTree); if (registryKey == null) { - MessageBox.Show("Can't apply settings in registry (ErrorCode=1).", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Can't apply settings in registry. (code 0x05)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } @@ -174,9 +192,9 @@ namespace FileConverter { registryKey.DeleteSubKey(subKeyNames[index]); } - catch (Exception exception) + catch (Exception) { - MessageBox.Show("Can't apply settings in registry (ErrorCode=2).", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Can't apply settings in registry. (code 0x06)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } } @@ -207,7 +225,7 @@ namespace FileConverter if (subKey == null) { - MessageBox.Show("Can't apply settings in registry (ErrorCode=3).", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Can't apply settings in registry. (code 0x07)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } @@ -352,36 +370,17 @@ namespace FileConverter process.Start(); process.WaitForExit(); } - catch (Exception exception) + catch (Exception) { - MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges. (code 0x08)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } - public string this[string columnName] + [NotifyPropertyChangedInvocator] + private void OnPropertyChanged([CallerMemberName] string propertyName = null) { - get - { - return this.Error; - } - } - - public string Error - { - get - { - for (int index = 0; index < this.ConversionPresets.Count; index++) - { - string error = this.ConversionPresets[index].Error; - if (!string.IsNullOrEmpty(error)) - { - return error; - } - } - - return string.Empty; - } + this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } diff --git a/Application/FileConverter/Settings.xml b/Application/FileConverter/Settings.xml index 5efe971..d821028 100644 --- a/Application/FileConverter/Settings.xml +++ b/Application/FileConverter/Settings.xml @@ -1,28 +1,55 @@ - Wav - Flac - Wma - Mp3 - Ape + flac + ape + wav + wma + m4a + avi + mp4 + mp3 + aiff + None + + (p)(f) - Flac - Ogg - Wav - Wma - Ape + ogg + flac + ape + wav + wma + m4a + mp4 + avi + aiff + None + + + (p)(f) - Wav - Ape + ape + wav + avi + mp4 + aiff + None + (p)(f) - Flac - Mp3 - Ogg - Wma - Ape + ape + flac + mp3 + ogg + wma + avi + mp4 + m4a + aiff + None + + (p)(f) \ No newline at end of file diff --git a/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs b/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs index 25a5715..514c818 100644 --- a/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs +++ b/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs @@ -1,6 +1,6 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.ValueConverters { using System; using System.Globalization; @@ -10,12 +10,12 @@ namespace FileConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (!(value is Version)) + if (!(value is FileConverter.Version)) { return "File Converter"; } - Version version = (Version)value; + FileConverter.Version version = (FileConverter.Version)value; return string.Format("File Converter v{0}", version.ToString()); } diff --git a/Application/FileConverter/ValueConverters/BitrateToString.cs b/Application/FileConverter/ValueConverters/BitrateToString.cs new file mode 100644 index 0000000..213b843 --- /dev/null +++ b/Application/FileConverter/ValueConverters/BitrateToString.cs @@ -0,0 +1,28 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class BitrateToString : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is double)) + { + throw new ArgumentException("The value must be a double value."); + } + + double bitrate = (double)value; + + return string.Format("{0} kbit/s", bitrate.ToString("0")); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/ValueConverters/ConversionSettingsToString.cs b/Application/FileConverter/ValueConverters/ConversionSettingsToString.cs new file mode 100644 index 0000000..a1dba3f --- /dev/null +++ b/Application/FileConverter/ValueConverters/ConversionSettingsToString.cs @@ -0,0 +1,76 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class ConversionSettingsToString : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return null; + } + + if (!(value is IConversionSettings)) + { + throw new ArgumentException("The value must be a conversion preset array."); + } + + IConversionSettings settings = (IConversionSettings)value; + + string parameterString = parameter as string; + if (parameterString == null) + { + throw new ArgumentException("The parameter must be a string value."); + } + + string[] parameters = parameterString.Split(','); + if (parameters.Length < 1 || parameters.Length > 2) + { + throw new ArgumentException("The parameter format must be 'SettingsKey[,DefaultValue]'."); + } + + string key = parameters[0]; + string setting; + if (settings.TryGetValue(key, out setting)) + { + return setting; + } + + if (parameters.Length >= 2) + { + return parameters[1]; + } + + return null; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return null; + } + + if (!(value is string)) + { + throw new ArgumentException("value"); + } + + string settingsValue = (string)value; + + if (!(parameter is string)) + { + throw new ArgumentException("parameter"); + } + + string settingsKey = (string)parameter; + + return new ConversionSettingsOverride(settingsKey, settingsValue); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs b/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs index ff7860f..cdad1c0 100644 --- a/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs +++ b/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs @@ -1,12 +1,14 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.ValueConverters { using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; + using FileConverter.ConversionJobs; + public class ConversionStateToBrush : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/FileNameConverter.cs b/Application/FileConverter/ValueConverters/FileNameConverter.cs new file mode 100644 index 0000000..0d3bdcb --- /dev/null +++ b/Application/FileConverter/ValueConverters/FileNameConverter.cs @@ -0,0 +1,81 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class FileNameConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values == null || values.Length != 3) + { + throw new ArgumentException("The values must contains the input file path, the output file extension and the ouput file template."); + } + + if (!(values[1] is OutputType)) + { + return "Invalid output file extension (argument 1)."; + } + + string inputFilePath = values[0] as string; + OutputType outputFileExtension = (OutputType)values[1]; + string outputFileTemplate = values[2] as string; + + if (inputFilePath == null) + { + return "Invalid input file path (argument 0)."; + } + + string inputExtension = System.IO.Path.GetExtension(inputFilePath).Substring(1); + string inputPathWithoutExtension = inputFilePath.Substring(0, inputFilePath.Length - inputExtension.Length - 1); + string outputExtension = outputFileExtension.ToString().ToLowerInvariant(); + + if (outputFileTemplate == null) + { + // Default output path. + return inputPathWithoutExtension + "." + outputExtension; + } + + string fileName = System.IO.Path.GetFileName(inputPathWithoutExtension); + string parentDirectory = System.IO.Path.GetDirectoryName(inputPathWithoutExtension); + string[] directories = parentDirectory.Split(System.IO.Path.DirectorySeparatorChar); + parentDirectory += System.IO.Path.DirectorySeparatorChar; + + // Generate output path from template. + string outputPath = outputFileTemplate; + + outputPath = outputPath.Replace("(path)", parentDirectory); + outputPath = outputPath.Replace("(p)", parentDirectory); + + outputPath = outputPath.Replace("(filename)", fileName); + outputPath = outputPath.Replace("(f)", fileName); + outputPath = outputPath.Replace("(F)", fileName.ToUpperInvariant()); + + outputPath = outputPath.Replace("(outputext)", outputExtension); + outputPath = outputPath.Replace("(o)", outputExtension); + outputPath = outputPath.Replace("(O)", outputExtension.ToUpperInvariant()); + + outputPath = outputPath.Replace("(inputext)", inputExtension); + outputPath = outputPath.Replace("(i)", inputExtension); + outputPath = outputPath.Replace("(I)", inputExtension.ToUpperInvariant()); + + for (int index = 0; index < directories.Length; index++) + { + outputPath = outputPath.Replace(string.Format("(d{0})", directories.Length - index - 1), directories[index]); + outputPath = outputPath.Replace(string.Format("(D{0})", directories.Length - index - 1), directories[index].ToUpperInvariant()); + } + + outputPath += "." + outputExtension; + + return outputPath; + } + + public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/BoolInverterConverter.cs b/Application/FileConverter/ValueConverters/Generic/BoolInverterConverter.cs new file mode 100644 index 0000000..bbab540 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/BoolInverterConverter.cs @@ -0,0 +1,28 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class BoolInverterConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is bool)) + { + throw new System.ArgumentException("The object must be a boolean value."); + } + + bool boolValue = (bool)value; + + return !boolValue; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs b/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs new file mode 100644 index 0000000..f3cd532 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs @@ -0,0 +1,28 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class BoolToVisibility : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is bool)) + { + throw new ArgumentException("The value must be a boolean."); + } + + bool booleanValue = (bool)value; + + return booleanValue ? "Visible" : "Hidden"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/ValueConverters/Generic/CollectionContainsElementToBool.cs b/Application/FileConverter/ValueConverters/Generic/CollectionContainsElementToBool.cs new file mode 100644 index 0000000..7ab3d9c --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/CollectionContainsElementToBool.cs @@ -0,0 +1,66 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Windows.Data; + + public class CollectionContainsElementToBool : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values == null || values.Length != 2) + { + throw new ArgumentException("The values must contains the collection of elements and the researched element."); + } + + //// TODO: Make this converter generic. + + if (!(values[0] is ICollection)) + { + return false; + } + + bool? result = null; + if (values[1] is IEnumerable) + { + ICollection collection = values[0] as ICollection; + IEnumerable objectsToFind = values[1] as IEnumerable; + + bool all = true; + bool none = true; + foreach (string objectToFind in objectsToFind) + { + bool contains = collection.Contains(objectToFind); + all &= contains; + none &= !contains; + } + + if (all) + { + result = true; + } + else if (none) + { + result = false; + } + } + else + { + ICollection collection = values[0] as ICollection; + string objectToFind = values[1] as string; + + result = collection.Contains(objectToFind); + } + + return result; + } + + public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/EqualsConverter.cs b/Application/FileConverter/ValueConverters/Generic/EqualsConverter.cs new file mode 100644 index 0000000..76ed984 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/EqualsConverter.cs @@ -0,0 +1,37 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class EqualsConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return parameter == null; + } + + return value.Equals(parameter); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is bool)) + { + throw new ArgumentException("value"); + } + + bool equals = (bool)value; + if (equals) + { + return parameter; + } + + return null; + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs b/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs new file mode 100644 index 0000000..16d7441 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs @@ -0,0 +1,40 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class StringToEnum : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + string stringValue = value as string; + if (value == null) + { + // TODO default value ? + return null; + } + + string typeName = parameter as string; + if (typeName == null) + { + throw new ArgumentNullException("parameter", "The parameter must contains the enum type."); + } + + Type enumType = Type.GetType(typeName); + if (enumType == null) + { + throw new Exception("Invalid enum type " + typeName + "."); + } + + return Enum.Parse(enumType, stringValue); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs b/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs new file mode 100644 index 0000000..2a19e63 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs @@ -0,0 +1,43 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class StringToValueType : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return null; + } + + string typeName = parameter as string; + if (typeName == null) + { + throw new ArgumentNullException("parameter", "The parameter must contains a convertible type."); + } + + Type type = Type.GetType(typeName); + if (type == null) + { + throw new Exception("Invalid enum type " + typeName + "."); + } + + return System.Convert.ChangeType(value, type); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return null; + } + + return value.ToString(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/ValueConverterGroup.cs b/Application/FileConverter/ValueConverters/Generic/ValueConverterGroup.cs new file mode 100644 index 0000000..637cfb9 --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/ValueConverterGroup.cs @@ -0,0 +1,68 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters.Generic +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Windows.Data; + + public class ValueConverterGroup : List, IValueConverter + { + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + string[] parameters = null; + if (parameter == null) + { + parameters = new string[this.Count]; + } + else + { + string parameterString = parameter as string; + if (parameterString == null) + { + throw new ArgumentException("The parameter must be a string value."); + } + + parameters = parameterString.Split('|'); + if (parameters.Length != this.Count) + { + throw new ArgumentException("The parameter format must be 'Converter1Parameters|Converter2Parameters|...'."); + } + } + + object result = value; + for (int index = 0; index < this.Count; index++) + { + IValueConverter converter = this[index]; + result = converter.Convert(result, targetType, parameters[index], culture); + } + + return result; + } + + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + string parameterString = parameter as string; + if (parameterString == null) + { + throw new ArgumentException("The parameter must be a string value."); + } + + string[] parameters = parameterString.Split('|'); + if (parameters.Length != this.Count) + { + throw new ArgumentException("The parameter format must be 'Converter1Parameters|Converter2Parameters|...'."); + } + + object result = value; + for (int index = this.Count - 1; index >= 0; index--) + { + IValueConverter converter = this[index]; + result = converter.ConvertBack(result, targetType, parameters[index], culture); + } + + return result; + } + } +} diff --git a/Application/FileConverter/ValueConverters/InputTypesToBool.cs b/Application/FileConverter/ValueConverters/InputTypesToBool.cs index b75dcd7..246a19b 100644 --- a/Application/FileConverter/ValueConverters/InputTypesToBool.cs +++ b/Application/FileConverter/ValueConverters/InputTypesToBool.cs @@ -1,6 +1,6 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.ValueConverters { using System; using System.Collections.Generic; diff --git a/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs b/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs new file mode 100644 index 0000000..eded1f2 --- /dev/null +++ b/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs @@ -0,0 +1,40 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class OutputTypeToVisibility : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is OutputType)) + { + throw new ArgumentException("The value must be an output type enum value."); + } + + OutputType outputType = (OutputType)value; + + string referenceTypeName = parameter as string; + if (string.IsNullOrEmpty(referenceTypeName)) + { + return "Hidden"; + } + + OutputType referenceType; + if (!Enum.TryParse(referenceTypeName, out referenceType)) + { + return "Hidden"; + } + + return outputType == referenceType ? "Visible" : "Hidden"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/Version.cs b/Application/FileConverter/Version.cs index 95f2a0c..585c3c5 100644 --- a/Application/FileConverter/Version.cs +++ b/Application/FileConverter/Version.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. namespace FileConverter { diff --git a/Application/FileConverter/Windows/ConversionSettingsTemplateSelector.cs b/Application/FileConverter/Windows/ConversionSettingsTemplateSelector.cs new file mode 100644 index 0000000..46b2fe3 --- /dev/null +++ b/Application/FileConverter/Windows/ConversionSettingsTemplateSelector.cs @@ -0,0 +1,58 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Windows +{ + using System.Windows; + using System.Windows.Controls; + + public class ConversionSettingsTemplateSelector : DataTemplateSelector + { + public DataTemplate DefaultDataTemplate + { + get; + set; + } + + public DataTemplate WavSettingsDataTemplate + { + get; + set; + } + + public DataTemplate Mp3SettingsDataTemplate + { + get; + set; + } + + public DataTemplate OggSettingsDataTemplate + { + get; + set; + } + + public override DataTemplate SelectTemplate(object item, DependencyObject container) + { + if (item == null) + { + return this.DefaultDataTemplate; + } + + OutputType outputType = (OutputType)item; + + switch (outputType) + { + case OutputType.Wav: + return this.WavSettingsDataTemplate; + + case OutputType.Mp3: + return this.Mp3SettingsDataTemplate; + + case OutputType.Ogg: + return this.OggSettingsDataTemplate; + } + + return this.DefaultDataTemplate; + } + } +} diff --git a/Application/FileConverter/Windows/DiagnosticsWindow.xaml b/Application/FileConverter/Windows/DiagnosticsWindow.xaml index 4f5f222..b433847 100644 --- a/Application/FileConverter/Windows/DiagnosticsWindow.xaml +++ b/Application/FileConverter/Windows/DiagnosticsWindow.xaml @@ -6,7 +6,7 @@ xmlns:local="clr-namespace:FileConverter.Windows" xmlns:fileConverter="clr-namespace:FileConverter" mc:Ignorable="d" - Title="Diagnostics" Height="600" Width="800" Icon="/FileConverter;component/Resources/ApplicationIcon-16x16.ico"> + Title="Diagnostics" Height="600" Width="800" Icon="/FileConverter;component/Resources/ApplicationIcon.ico"> diff --git a/Application/FileConverter/Windows/DiagnosticsWindow.xaml.cs b/Application/FileConverter/Windows/DiagnosticsWindow.xaml.cs index d307a44..ce1eb92 100644 --- a/Application/FileConverter/Windows/DiagnosticsWindow.xaml.cs +++ b/Application/FileConverter/Windows/DiagnosticsWindow.xaml.cs @@ -1,27 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. namespace FileConverter.Windows { + using System.Windows; + /// - /// Interaction logic for DiagnosticsWindow.xaml + /// Interaction logic for DiagnosticsWindow. /// public partial class DiagnosticsWindow : Window { public DiagnosticsWindow() { - InitializeComponent(); + this.InitializeComponent(); } } } diff --git a/Application/FileConverter/Windows/InputExtension.cs b/Application/FileConverter/Windows/InputExtension.cs new file mode 100644 index 0000000..ea8c7e7 --- /dev/null +++ b/Application/FileConverter/Windows/InputExtension.cs @@ -0,0 +1,41 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System.ComponentModel; + using System.Runtime.CompilerServices; + + using FileConverter.Annotations; + + public class InputExtension : INotifyPropertyChanged + { + private string name; + + public InputExtension(string name) + { + this.Name = name; + } + + public event PropertyChangedEventHandler PropertyChanged; + + public string Name + { + get + { + return this.name; + } + + set + { + this.name = value; + this.OnPropertyChanged(); + } + } + + [NotifyPropertyChangedInvocator] + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/Windows/InputExtensionCategory.cs b/Application/FileConverter/Windows/InputExtensionCategory.cs new file mode 100644 index 0000000..f1c9924 --- /dev/null +++ b/Application/FileConverter/Windows/InputExtensionCategory.cs @@ -0,0 +1,74 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + using System.Collections.Generic; + using System.ComponentModel; + using System.Runtime.CompilerServices; + + using FileConverter.Annotations; + + public class InputExtensionCategory : INotifyPropertyChanged + { + private string name; + private List inputExtensions = new List(); + + public InputExtensionCategory(string name) + { + this.Name = name; + } + + public event PropertyChangedEventHandler PropertyChanged; + + public string Name + { + get + { + return this.name; + } + + set + { + this.name = value; + this.OnPropertyChanged(); + } + } + + public IEnumerable InputExtensions + { + get + { + return this.inputExtensions; + } + } + + public IEnumerable InputExtensionNames + { + get + { + foreach (InputExtension inputExtension in this.inputExtensions) + { + yield return inputExtension.Name; + } + } + } + + public void AddExtension(string extension) + { + InputExtension inputExtension = this.inputExtensions.Find(match => match.Name == extension); + if (inputExtension == null) + { + inputExtension = new InputExtension(extension); + this.inputExtensions.Add(inputExtension); + this.OnPropertyChanged("InputExtensions"); + this.OnPropertyChanged("InputExtensionNames"); + } + } + + [NotifyPropertyChangedInvocator] + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/Windows/MainWindow.xaml b/Application/FileConverter/Windows/MainWindow.xaml index f04f537..536f3ce 100644 --- a/Application/FileConverter/Windows/MainWindow.xaml +++ b/Application/FileConverter/Windows/MainWindow.xaml @@ -1,13 +1,14 @@  + xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters" + xmlns:conversionJobs="clr-namespace:FileConverter.ConversionJobs" mc:Ignorable="d" x:Class="FileConverter.MainWindow" + x:Name="FileConverterMainWindow" Height="500" Width="950" MinHeight="250" MinWidth="450" WindowStartupLocation="CenterScreen" Icon="/FileConverter;component/Resources/ApplicationIcon.ico"> - - - + + @@ -26,19 +27,16 @@ -