// ****************************************************************************
//
// CUE Tools
// Copyright (C) 2006-2007 Moitah (moitah@yahoo.com)
// Copyright (C) 2008-2010 Gregory S. Chudov (gchudov@gmail.com)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// ****************************************************************************
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Policy;
using System.Security.Cryptography;
using System.Threading;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Reflection;
using System.Runtime.InteropServices;
using CUETools.Codecs;
using CUETools.CDImage;
using CUETools.AccurateRip;
//using CUETools.CDRepair;
using CUETools.CTDB;
using CUETools.Ripper;
using CUETools.Compression;
using MusicBrainz;
using Freedb;
using CSScriptLibrary;
namespace CUETools.Processor
{
public enum AudioEncoderType
{
Lossless,
Hybrid,
Lossy,
///
/// No Audio
///
NoAudio,
}
public enum CUEAction
{
Encode = 0,
Verify = 1,
CreateDummyCUE = 2,
CorrectFilenames = 3
}
public enum CUEStyle
{
///
/// Single file with embedded CUE
///
SingleFileWithCUE,
///
/// Single file with external CUE
///
SingleFile,
///
/// Gaps prepended file-per-track
///
GapsPrepended,
///
/// Gaps appended (noncompliant) file-per-track
///
GapsAppended,
///
/// Gaps left out file-per-track
///
GapsLeftOut
}
public static class General {
public static CUELine FindCUELine(List list, string command) {
command = command.ToUpper();
foreach (CUELine line in list) {
if (line.Params[0].ToUpper() == command) {
return line;
}
}
return null;
}
public static CUELine FindCUELine(List list, string command, string command2)
{
command = command.ToUpper();
command2 = command2.ToUpper();
foreach (CUELine line in list)
{
if (line.Params.Count > 1 && line.Params[0].ToUpper() == command && line.Params[1].ToUpper() == command2)
{
return line;
}
}
return null;
}
//public static CUELine FindCUELine(List list, string [] commands)
//{
// foreach (CUELine line in list)
// {
// if (line.Params.Count < commands.Length)
// continue;
// for (int i = 0; i < commands.Length; i++)
// {
// if (line.Params[i].ToUpper() != commands[i].ToUpper())
// break;
// if (i == commands.Length - 1)
// return line;
// }
// }
// return null;
//}
public static void SetCUELine(List list, string command, string value, bool quoted)
{
CUELine line = General.FindCUELine(list, command);
if (line == null)
{
line = new CUELine();
line.Params.Add(command); line.IsQuoted.Add(false);
line.Params.Add(value); line.IsQuoted.Add(quoted);
list.Add(line);
}
else
{
while (line.Params.Count > 1)
{
line.Params.RemoveAt(1);
line.IsQuoted.RemoveAt(1);
}
line.Params.Add(value); line.IsQuoted.Add(quoted);
}
}
public static void SetCUELine(List list, string command, string command2, string value, bool quoted)
{
CUELine line = General.FindCUELine(list, command, command2);
if (line == null)
{
line = new CUELine();
line.Params.Add(command); line.IsQuoted.Add(false);
line.Params.Add(command2); line.IsQuoted.Add(false);
line.Params.Add(value); line.IsQuoted.Add(quoted);
list.Add(line);
}
else
{
while (line.Params.Count > 2)
{
line.Params.RemoveAt(2);
line.IsQuoted.RemoveAt(2);
}
line.Params.Add(value); line.IsQuoted.Add(quoted);
}
}
public static void DelCUELine(List list, string command, string command2)
{
CUELine line = General.FindCUELine(list, command, command2);
if (line == null)
return;
list.Remove(line);
}
public static void DelCUELine(List list, string command)
{
CUELine line = General.FindCUELine(list, command);
if (line == null)
return;
list.Remove(line);
}
class TitleFormatFunctionInfo
{
public string func;
public List positions;
public List found;
public TitleFormatFunctionInfo(string _func, int position)
{
func = _func;
positions = new List();
found = new List();
NextArg(position);
}
public void Found()
{
found[found.Count - 1] = true;
}
public void NextArg(int position)
{
positions.Add(position);
found.Add(false);
}
public string GetArg(StringBuilder sb, int no)
{
return sb.ToString().Substring(positions[no],
((no == positions.Count - 1) ? sb.Length : positions[no + 1]) - positions[no]);
}
public int GetIntArg(StringBuilder sb, int no)
{
int res;
return int.TryParse(GetArg(sb, no), out res) ? res : 0;
}
void Returns(StringBuilder sb, string res)
{
sb.Length = positions[0];
sb.Append(res);
}
public bool Finalise(StringBuilder sb)
{
switch (func)
{
case "[":
if (positions.Count != 1)
return false;
if (!found[0])
sb.Length = positions[0];
return true;
case "if":
if (positions.Count != 3)
return false;
Returns(sb, GetArg(sb, found[0] ? 1 : 2));
return true;
case "if2":
if (positions.Count != 2)
return false;
Returns(sb, GetArg(sb, found[0] ? 0 : 1));
return true;
case "if3":
if (positions.Count < 1)
return false;
for (int argno = 0; argno < positions.Count; argno++)
if (found[argno] || argno == positions.Count - 1)
{
Returns(sb, GetArg(sb, argno));
return true;
}
return false;
case "ifgreater":
if (positions.Count != 4)
return false;
Returns(sb, GetArg(sb, (GetIntArg(sb, 0) > GetIntArg(sb, 1)) ? 2 : 3));
return true;
case "iflonger":
if (positions.Count != 4)
return false;
Returns(sb, GetArg(sb, (GetArg(sb, 0).Length > GetIntArg(sb, 1)) ? 2 : 3));
return true;
case "ifequal":
if (positions.Count != 4)
return false;
Returns(sb, GetArg(sb, (GetIntArg(sb, 0) == GetIntArg(sb, 1)) ? 2 : 3));
return true;
case "len":
if (positions.Count != 1)
return false;
Returns(sb, GetArg(sb, 0).Length.ToString());
return true;
case "max":
if (positions.Count != 2)
return false;
Returns(sb, Math.Max(GetIntArg(sb, 0), GetIntArg(sb, 1)).ToString());
return true;
case "directory":
if (positions.Count != 1 && positions.Count != 2 && positions.Count != 3)
return false;
try
{
int arg3 = positions.Count > 1 ? GetIntArg(sb, 1) : 1;
int arg2 = positions.Count > 2 ? GetIntArg(sb, 2) : arg3;
Returns(sb, General.GetDirectoryElements(Path.GetDirectoryName(GetArg(sb, 0)), -arg2, -arg3));
}
catch { return false; }
return true;
case "directory_path":
if (positions.Count != 1)
return false;
try { Returns(sb, Path.GetDirectoryName(GetArg(sb, 0))); }
catch { return false; }
return true;
case "ext":
if (positions.Count != 1)
return false;
try { Returns(sb, Path.GetExtension(GetArg(sb, 0))); }
catch { return false; }
return true;
case "filename":
if (positions.Count != 1)
return false;
try { Returns(sb, Path.GetFileNameWithoutExtension(GetArg(sb, 0))); }
catch { return false; }
return true;
}
return false;
}
}
public static string GetDirectoryElements(string dir, int first, int last)
{
if (dir == null)
return "";
string[] dirSplit = dir.Split(Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar);
int count = dirSplit.Length;
if ((first == 0) && (last == 0))
{
first = 1;
last = count;
}
if (first < 0) first = (count + 1) + first;
if (last < 0) last = (count + 1) + last;
if ((first < 1) && (last < 1))
{
return String.Empty;
}
else if ((first > count) && (last > count))
{
return String.Empty;
}
else
{
int i;
StringBuilder sb = new StringBuilder();
if (first < 1) first = 1;
if (first > count) first = count;
if (last < 1) last = 1;
if (last > count) last = count;
if (last >= first)
{
for (i = first; i <= last; i++)
{
sb.Append(dirSplit[i - 1]);
sb.Append(Path.DirectorySeparatorChar);
}
}
else
{
for (i = first; i >= last; i--)
{
sb.Append(dirSplit[i - 1]);
sb.Append(Path.DirectorySeparatorChar);
}
}
return sb.ToString(0, sb.Length - 1);
}
}
public static string ReplaceMultiple(string s, NameValueCollection tags)
{
List find = new List();
List replace = new List();
foreach (string tag in tags.AllKeys)
{
string key = '%' + tag.ToLower() + '%';
string val = tags[tag];
if (!find.Contains(key) && val != null && val != "")
{
find.Add(key);
replace.Add(val);
}
}
return ReplaceMultiple(s, find, replace);
}
public delegate bool CheckIfExists(string output);
public static string ReplaceMultiple(string fmt, NameValueCollection tags, string unique_key, CheckIfExists exists)
{
string result = ReplaceMultiple(fmt, tags);
if (result == String.Empty || result == null)
return result;
int unique = 1;
try
{
while (exists(result))
{
tags[unique_key] = unique.ToString();
string new_result = ReplaceMultiple(fmt, tags);
if (new_result == result || new_result == String.Empty || new_result == null)
break;
result = new_result;
unique++;
}
}
catch { }
return result;
}
public static string ReplaceMultiple(string s, List find, List replace)
{
if (find.Count != replace.Count)
{
throw new ArgumentException();
}
StringBuilder sb;
int iChar, iFind;
string f;
bool found;
List formatFunctions = new List();
bool quote = false;
sb = new StringBuilder();
for (iChar = 0; iChar < s.Length; iChar++)
{
found = false;
if (quote)
{
if (s[iChar] == '\'')
{
if (iChar > 0 && s[iChar-1] == '\'')
sb.Append(s[iChar]);
quote = false;
continue;
}
sb.Append(s[iChar]);
continue;
}
if (s[iChar] == '\'')
{
quote = true;
continue;
}
if (s[iChar] == '[')
{
formatFunctions.Add(new TitleFormatFunctionInfo("[", sb.Length));
continue;
}
if (s[iChar] == '$')
{
int funcEnd = s.IndexOf('(', iChar + 1);
if (funcEnd < 0)
return null;
formatFunctions.Add(new TitleFormatFunctionInfo(s.Substring(iChar + 1, funcEnd - iChar - 1), sb.Length));
iChar = funcEnd;
continue;
}
if (s[iChar] == ',')
{
if (formatFunctions.Count < 1)
return null;
formatFunctions[formatFunctions.Count - 1].NextArg(sb.Length);
continue;
}
if (s[iChar] == ']')
{
if (formatFunctions.Count < 1 ||
formatFunctions[formatFunctions.Count - 1].func != "["
|| !formatFunctions[formatFunctions.Count - 1].Finalise(sb))
return null;
formatFunctions.RemoveAt(formatFunctions.Count - 1);
continue;
}
if (s[iChar] == ')')
{
if (formatFunctions.Count < 1 ||
formatFunctions[formatFunctions.Count - 1].func == "["
|| !formatFunctions[formatFunctions.Count - 1].Finalise(sb))
return null;
formatFunctions.RemoveAt(formatFunctions.Count - 1);
continue;
}
for (iFind = 0; iFind < find.Count; iFind++)
{
f = find[iFind];
if ((f.Length <= (s.Length - iChar)) && (s.Substring(iChar, f.Length) == f))
{
if (formatFunctions.Count > 0)
{
if (replace[iFind] != null)
{
formatFunctions[formatFunctions.Count - 1].Found();
sb.Append(replace[iFind]);
}
}
else
{
if (replace[iFind] != null)
sb.Append(replace[iFind]);
else
return null;
}
iChar += f.Length - 1;
found = true;
break;
}
}
if (!found)
{
sb.Append(s[iChar]);
}
}
return sb.ToString();
}
public static string EmptyStringToNull(string s)
{
return ((s != null) && (s.Length == 0)) ? null : s;
}
}
public enum CUEToolsTagger
{
TagLibSharp = 0,
APEv2 = 1,
ID3v2 = 2,
}
public class CUEToolsFormat
{
public CUEToolsFormat(
string _extension,
CUEToolsTagger _tagger,
bool _allowLossless,
bool _allowLossy,
bool _allowLossyWAV,
bool _allowEmbed,
bool _builtin,
CUEToolsUDC _encoderLossless,
CUEToolsUDC _encoderLossy,
string _decoder)
{
extension = _extension;
tagger = _tagger;
allowLossless = _allowLossless;
allowLossy = _allowLossy;
allowLossyWAV = _allowLossyWAV;
allowEmbed = _allowEmbed;
builtin = _builtin;
encoderLossless = _encoderLossless;
encoderLossy = _encoderLossy;
decoder = _decoder;
}
public override string ToString()
{
return extension;
}
public string extension;
public CUEToolsUDC encoderLossless;
public CUEToolsUDC encoderLossy;
public string decoder;
public CUEToolsTagger tagger;
public bool allowLossless, allowLossy, allowLossyWAV, allowEmbed, builtin;
}
public class CUEToolsUDC : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public CUEToolsUDC(
string _name,
string _extension,
bool _lossless,
string _supported_modes,
string _default_mode,
string _path,
string _parameters
)
{
name = _name;
extension = _extension;
lossless = _lossless;
supported_modes = _supported_modes;
default_mode = _default_mode;
priority = 0;
path = _path;
parameters = _parameters;
type = null;
}
public CUEToolsUDC(AudioEncoderClass enc, Type enctype)
{
name = enc.EncoderName;
extension = enc.Extension;
lossless = enc.Lossless;
supported_modes = enc.SupportedModes;
default_mode = enc.DefaultMode;
priority = enc.Priority;
path = null;
parameters = null;
type = enctype;
}
public CUEToolsUDC(AudioDecoderClass dec, Type dectype)
{
name = dec.DecoderName;
extension = dec.Extension;
lossless = true;
supported_modes = "";
default_mode = "";
priority = 1;
path = null;
parameters = null;
type = dectype;
}
public override string ToString()
{
return name;
}
public string name = "";
public string extension = "wav";
public string path = "";
public string parameters = "";
public Type type = null;
public string supported_modes = "";
public string default_mode = "";
public bool lossless = false;
public int priority = 0;
public string Name
{
get { return name; }
set { name = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name")); }
}
public string Path
{
get { return path; }
set { path = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Path")); }
}
public string Parameters
{
get { return parameters; }
set { parameters = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Parameters")); }
}
public bool Lossless
{
get { return lossless; }
set { lossless = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Lossless")); }
}
public string Extension
{
get { return extension; }
set { extension = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Extension")); }
}
public string DotExtension
{
get { return "." + extension; }
}
public string SupportedModesStr
{
get { return supported_modes; }
set { supported_modes = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SupportedModesStr")); }
}
public string[] SupportedModes
{
get
{
return supported_modes.Split(' ');
}
}
public int DefaultModeIndex
{
get
{
string[] modes = supported_modes.Split(' ');
if (modes == null || modes.Length < 2)
return -1;
for (int i = 0; i < modes.Length; i++)
if (modes[i] == default_mode)
return i;
return -1;
}
}
public bool CanBeDeleted
{
get
{
return path != null;
}
}
}
public class CUEToolsScript
{
public CUEToolsScript(string _name, bool _builtin, IEnumerable _conditions, string _code)
{
name = _name;
builtin = _builtin;
conditions = new List();
foreach(CUEAction condition in _conditions)
conditions.Add(condition);
code = _code;
}
public override string ToString()
{
return name;
}
public string name;
public bool builtin;
public List conditions;
public string code;
}
public class CUEToolsUDCList : BindingList
{
public CUEToolsUDCList() : base()
{
AddingNew += OnAddingNew;
}
private void OnAddingNew(object sender, AddingNewEventArgs e)
{
string name = "new";
CUEToolsUDC temp;
while (TryGetValue(name, out temp))
name += "(1)";
e.NewObject = new CUEToolsUDC(name, "wav", true, "", "", "", "");
}
public bool TryGetValue(string name, out CUEToolsUDC result)
{
foreach(CUEToolsUDC udc in this)
if (udc.name == name)
{
result = udc;
return true;
}
result = null;
return false;
}
public CUEToolsUDC GetDefault(string extension, bool lossless)
{
CUEToolsUDC result = null;
foreach (CUEToolsUDC udc in this)
if (udc.extension == extension && udc.lossless == lossless && (result == null || result.priority < udc.priority))
result = udc;
return result;
}
public CUEToolsUDC this[string name]
{
get
{
CUEToolsUDC udc;
if (!TryGetValue(name, out udc))
throw new Exception("CUEToolsUDCList: member not found");
return udc;
}
}
}
public static class CUEProcessorPlugins
{
static public List encs;
static public List decs;
static public List arcp;
static public List arcp_fmt;
static public Type hdcd;
static public Type ripper;
static CUEProcessorPlugins()
{
encs = new List();
decs = new List();
arcp = new List();
arcp_fmt = new List();
encs.Add(typeof(CUETools.Codecs.WAVWriter));
decs.Add(typeof(CUETools.Codecs.WAVReader));
//ApplicationSecurityInfo asi = new ApplicationSecurityInfo(AppDomain.CurrentDomain.ActivationContext);
//string arch = asi.ApplicationId.ProcessorArchitecture;
//ActivationContext is null most of the time :(
string arch = Marshal.SizeOf(typeof(IntPtr)) == 8 ? "x64" : "Win32";
string plugins_path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "plugins (" + arch + ")");
if (Directory.Exists(plugins_path))
AddPluginDirectory(plugins_path);
plugins_path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "plugins");
if (Directory.Exists(plugins_path))
AddPluginDirectory(plugins_path);
}
private static void AddPluginDirectory(string plugins_path)
{
foreach (string plugin_path in Directory.GetFiles(plugins_path, "*.dll", SearchOption.TopDirectoryOnly))
{
try
{
AssemblyName name = AssemblyName.GetAssemblyName(plugin_path);
Assembly assembly = Assembly.Load(name);
foreach (Type type in assembly.GetExportedTypes())
{
try
{
if (Attribute.GetCustomAttribute(type, typeof(AudioDecoderClass)) != null)
decs.Add(type);
//if (type.IsClass && !type.IsAbstract && typeof(IAudioDest).IsAssignableFrom(type))
if (Attribute.GetCustomAttribute(type, typeof(AudioEncoderClass)) != null)
encs.Add(type);
CompressionProviderClass archclass = Attribute.GetCustomAttribute(type, typeof(CompressionProviderClass)) as CompressionProviderClass;
if (archclass != null)
{
arcp.Add(type);
if (!arcp_fmt.Contains(archclass.Extension))
arcp_fmt.Add(archclass.Extension);
}
if (type.Name == "HDCDDotNet")
hdcd = type;
if (type.IsClass && !type.IsAbstract && typeof(ICDRipper).IsAssignableFrom(type))
ripper = type;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
}
public class CUEConfig {
public uint fixOffsetMinimumConfidence;
public uint fixOffsetMinimumTracksPercent;
public uint encodeWhenConfidence;
public uint encodeWhenPercent;
public bool encodeWhenZeroOffset;
public bool writeArTagsOnVerify;
public bool writeArLogOnVerify;
public bool writeArTagsOnEncode;
public bool writeArLogOnConvert;
public bool fixOffset;
public bool noUnverifiedOutput;
public bool autoCorrectFilenames;
public bool flacVerify;
public bool flaCudaVerify;
public bool flaCudaGPUOnly;
public bool flaCudaThreads;
public bool preserveHTOA;
public int wvExtraMode;
public bool wvStoreMD5;
public bool keepOriginalFilenames;
public string trackFilenameFormat;
public string singleFilenameFormat;
public bool removeSpecial;
public string specialExceptions;
public bool replaceSpaces;
public bool embedLog;
public bool extractLog;
public bool fillUpCUE;
public bool overwriteCUEData;
public bool filenamesANSISafe;
public bool bruteForceDTL;
public bool createEACLOG;
public bool detectHDCD;
public bool decodeHDCD;
public bool wait750FramesForHDCD;
public bool createM3U;
public bool createTOC;
public bool createCUEFileWhenEmbedded;
public bool truncate4608ExtraSamples;
public int lossyWAVQuality;
public bool decodeHDCDtoLW16;
public bool decodeHDCDto24bit;
public bool disableAsm;
public bool oneInstance;
public bool checkForUpdates;
public string language;
public Dictionary formats;
public CUEToolsUDCList encoders;
public Dictionary decoders;
public Dictionary scripts;
public string defaultVerifyScript;
public string defaultEncodeScript;
public bool writeBasicTagsFromCUEData;
public bool copyBasicTags;
public bool copyUnknownTags;
public bool copyAlbumArt;
public bool embedAlbumArt;
public bool extractAlbumArt;
public bool arLogToSourceFolder;
public bool arLogVerbose;
public bool fixOffsetToNearest;
public int maxAlbumArtSize;
public string arLogFilenameFormat, alArtFilenameFormat;
public CUEStyle gapsHandling;
public bool separateDecodingThread;
public bool useSystemProxySettings;
public bool CopyAlbumArt { get { return copyAlbumArt; } set { copyAlbumArt = value; } }
public bool FlaCudaThreads { get { return flaCudaThreads; } set { flaCudaThreads = value; } }
public bool FlaCudaGPUOnly { get { return flaCudaGPUOnly; } set { flaCudaGPUOnly = value; } }
public bool FlaCudaVerify { get { return flaCudaVerify; } set { flaCudaVerify = value; } }
public string ArLogFilenameFormat { get { return arLogFilenameFormat; } set { arLogFilenameFormat = value; } }
public string AlArtFilenameFormat { get { return alArtFilenameFormat; } set { alArtFilenameFormat = value; } }
public CUEToolsUDCList Encoders
{
get { return encoders; }
}
public CUEConfig()
{
fixOffsetMinimumConfidence = 2;
fixOffsetMinimumTracksPercent = 51;
encodeWhenConfidence = 2;
encodeWhenPercent = 100;
encodeWhenZeroOffset = false;
fixOffset = false;
noUnverifiedOutput = false;
writeArTagsOnEncode = true;
writeArLogOnConvert = true;
writeArTagsOnVerify = false;
writeArLogOnVerify = true;
autoCorrectFilenames = true;
flacVerify = false;
flaCudaVerify = false;
flaCudaGPUOnly = false;
flaCudaThreads = true;
preserveHTOA = true;
wvExtraMode = 0;
wvStoreMD5 = false;
keepOriginalFilenames = false;
trackFilenameFormat = "%tracknumber%. %title%";
singleFilenameFormat = "%filename%";
removeSpecial = false;
specialExceptions = "-()";
replaceSpaces = false;
embedLog = true;
extractLog = true;
fillUpCUE = true;
overwriteCUEData = false;
filenamesANSISafe = true;
bruteForceDTL = false;
createEACLOG = false;
detectHDCD = true;
wait750FramesForHDCD = true;
decodeHDCD = false;
createM3U = false;
createTOC = false;
createCUEFileWhenEmbedded = true;
truncate4608ExtraSamples = true;
lossyWAVQuality = 5;
decodeHDCDtoLW16 = false;
decodeHDCDto24bit = true;
disableAsm = false;
oneInstance = true;
checkForUpdates = true;
writeBasicTagsFromCUEData = true;
copyBasicTags = true;
copyUnknownTags = true;
copyAlbumArt = true;
embedAlbumArt = true;
extractAlbumArt = true;
maxAlbumArtSize = 300;
arLogToSourceFolder = false;
arLogVerbose = true;
fixOffsetToNearest = true;
arLogFilenameFormat = "%filename%.accurip";
alArtFilenameFormat = "folder.jpg";
separateDecodingThread = true;
useSystemProxySettings = true;
gapsHandling = CUEStyle.GapsAppended;
language = Thread.CurrentThread.CurrentUICulture.Name;
encoders = new CUEToolsUDCList();
foreach (Type type in CUEProcessorPlugins.encs)
{
AudioEncoderClass enc = Attribute.GetCustomAttribute(type, typeof(AudioEncoderClass)) as AudioEncoderClass;
//if (!encoders.TryGetValue(enc.EncoderName))
encoders.Add(new CUEToolsUDC(enc, type));
}
decoders = new Dictionary();
foreach (Type type in CUEProcessorPlugins.decs)
{
AudioDecoderClass dec = Attribute.GetCustomAttribute(type, typeof(AudioDecoderClass)) as AudioDecoderClass;
decoders.Add(dec.DecoderName, new CUEToolsUDC(dec, type));
}
if (Type.GetType("Mono.Runtime", false) == null)
{
encoders.Add(new CUEToolsUDC("flake", "flac", true, "0 1 2 3 4 5 6 7 8 9 10 11", "10", "flake.exe", "-%M - -o %O -p %P"));
encoders.Add(new CUEToolsUDC("takc", "tak", true, "0 1 2 2e 2m 3 3e 3m 4 4e 4m", "2", "takc.exe", "-e -p%M -overwrite - %O"));
encoders.Add(new CUEToolsUDC("ffmpeg alac", "m4a", true, "", "", "ffmpeg.exe", "-i - -f ipod -acodec alac -y %O"));
encoders.Add(new CUEToolsUDC("lame vbr", "mp3", false, "V9 V8 V7 V6 V5 V4 V3 V2 V1 V0", "V2", "lame.exe", "--vbr-new -%M - %O"));
encoders.Add(new CUEToolsUDC("lame cbr", "mp3", false, "96 128 192 256 320", "256", "lame.exe", "-m s -q 0 -b %M --noreplaygain - %O"));
encoders.Add(new CUEToolsUDC("oggenc", "ogg", false, "-1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8", "3", "oggenc.exe", "-q %M - -o %O"));
encoders.Add(new CUEToolsUDC("nero aac", "m4a", false, "0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9", "0.4", "neroAacEnc.exe", "-q %M -if - -of %O"));
decoders.Add("takc", new CUEToolsUDC("takc", "tak", true, "", "", "takc.exe", "-d %I -"));
decoders.Add("ffmpeg alac", new CUEToolsUDC("ffmpeg alac", "m4a", true, "", "", "ffmpeg.exe", "%I -f wav -"));
}
else
{
// !!!
}
formats = new Dictionary();
formats.Add("flac", new CUEToolsFormat("flac", CUEToolsTagger.TagLibSharp, true, false, true, true, true, encoders.GetDefault("flac", true), null, GetDefaultDecoder("flac")));
formats.Add("wv", new CUEToolsFormat("wv", CUEToolsTagger.TagLibSharp, true, false, true, true, true, encoders.GetDefault("wv", true), null, GetDefaultDecoder("wv")));
formats.Add("ape", new CUEToolsFormat("ape", CUEToolsTagger.TagLibSharp, true, false, false, true, true, encoders.GetDefault("ape", true), null, GetDefaultDecoder("ape")));
formats.Add("tta", new CUEToolsFormat("tta", CUEToolsTagger.APEv2, true, false, false, false, true, encoders.GetDefault("tta", true), null, GetDefaultDecoder("tta")));
formats.Add("wav", new CUEToolsFormat("wav", CUEToolsTagger.TagLibSharp, true, false, true, false, true, encoders.GetDefault("wav", true), null, GetDefaultDecoder("wav")));
formats.Add("m4a", new CUEToolsFormat("m4a", CUEToolsTagger.TagLibSharp, true, true, false, false, true, encoders.GetDefault("m4a", true), encoders.GetDefault("m4a", false), GetDefaultDecoder("m4a")));
formats.Add("tak", new CUEToolsFormat("tak", CUEToolsTagger.APEv2, true, false, true, true, true, encoders.GetDefault("tak", true), null, "takc"));
formats.Add("mp3", new CUEToolsFormat("mp3", CUEToolsTagger.TagLibSharp, false, true, false, false, true, null, encoders.GetDefault("mp3", false), null));
formats.Add("ogg", new CUEToolsFormat("ogg", CUEToolsTagger.TagLibSharp, false, true, false, false, true, null, encoders.GetDefault("ogg", false), null));
scripts = new Dictionary();
scripts.Add("default", new CUEToolsScript("default", true,
new CUEAction[] { CUEAction.Verify, CUEAction.Encode },
"return processor.Go();"));
scripts.Add("only if found", new CUEToolsScript("only if found", true,
new CUEAction[] { CUEAction.Verify },
@"if (processor.ArVerify.AccResult != HttpStatusCode.OK)
return processor.WriteReport();
return processor.Go();"));
scripts.Add("fix offset", new CUEToolsScript("fix offset", true,
new CUEAction[] { CUEAction.Encode },
@"if (processor.ArVerify.AccResult != HttpStatusCode.OK)
return processor.WriteReport();
processor.WriteOffset = 0;
processor.Action = CUEAction.Verify;
string status = processor.Go();
uint tracksMatch;
int bestOffset;
processor.FindBestOffset(processor.Config.fixOffsetMinimumConfidence, !processor.Config.fixOffsetToNearest, out tracksMatch, out bestOffset);
if (tracksMatch * 100 < processor.Config.fixOffsetMinimumTracksPercent * processor.TrackCount)
return status;
processor.WriteOffset = bestOffset;
processor.Action = CUEAction.Encode;
//MessageBox.Show(null, processor.AccurateRipLog, " + "\"Done\"" + @"MessageBoxButtons.OK, MessageBoxIcon.Information);
return processor.Go();
"));
scripts.Add("encode if verified", new CUEToolsScript("encode if verified", true,
new CUEAction[] { CUEAction.Encode },
@"if (processor.ArVerify.AccResult != HttpStatusCode.OK)
return processor.WriteReport();
processor.Action = CUEAction.Verify;
string status = processor.Go();
uint tracksMatch;
int bestOffset;
processor.FindBestOffset(processor.Config.encodeWhenConfidence, false, out tracksMatch, out bestOffset);
if (tracksMatch * 100 < processor.Config.encodeWhenPercent * processor.TrackCount || (processor.Config.encodeWhenZeroOffset && bestOffset != 0))
return status;
processor.Action = CUEAction.Encode;
return processor.Go();
"));
scripts.Add("repair", new CUEToolsScript("repair", true,
new CUEAction[] { CUEAction.Encode },
@"
processor.UseCUEToolsDB();
processor.Action = CUEAction.Verify;
if (processor.CTDB.DBStatus != null)
return CTDB.DBStatus;
processor.Go();
processor.CTDB.DoVerify();
if (!processor.CTDB.Verify.HasErrors)
return ""nothing to fix"";
if (!processor.CTDB.Verify.CanRecover)
return ""cannot fix"";
processor._useCUEToolsDBFix = true;
processor.Action = CUEAction.Encode;
return processor.Go();
"));
scripts.Add("submit", new CUEToolsScript("submit", true,
new CUEAction[] { CUEAction.Verify },
@"
string status = processor.Go();
"));
defaultVerifyScript = "default";
defaultEncodeScript = "default";
}
public void Save (SettingsWriter sw)
{
sw.Save("Version", 203);
sw.Save("ArFixWhenConfidence", fixOffsetMinimumConfidence);
sw.Save("ArFixWhenPercent", fixOffsetMinimumTracksPercent);
sw.Save("ArEncodeWhenConfidence", encodeWhenConfidence);
sw.Save("ArEncodeWhenPercent", encodeWhenPercent);
sw.Save("ArEncodeWhenZeroOffset", encodeWhenZeroOffset);
sw.Save("ArNoUnverifiedOutput", noUnverifiedOutput);
sw.Save("ArFixOffset", fixOffset);
sw.Save("ArWriteCRC", writeArTagsOnEncode);
sw.Save("ArWriteLog", writeArLogOnConvert);
sw.Save("ArWriteTagsOnVerify", writeArTagsOnVerify);
sw.Save("ArWriteLogOnVerify", writeArLogOnVerify);
sw.Save("PreserveHTOA", preserveHTOA);
sw.Save("AutoCorrectFilenames", autoCorrectFilenames);
sw.Save("FLACVerify", flacVerify);
sw.Save("FlaCudaVerify", flaCudaVerify);
sw.Save("FlaCudaGPUOnly", flaCudaGPUOnly);
sw.Save("FlaCudaThreads", flaCudaThreads);
sw.Save("WVExtraMode", wvExtraMode);
sw.Save("WVStoreMD5", wvStoreMD5);
sw.Save("KeepOriginalFilenames", keepOriginalFilenames);
sw.Save("SingleFilenameFormat", singleFilenameFormat);
sw.Save("TrackFilenameFormat", trackFilenameFormat);
sw.Save("RemoveSpecialCharacters", removeSpecial);
sw.Save("SpecialCharactersExceptions", specialExceptions);
sw.Save("ReplaceSpaces", replaceSpaces);
sw.Save("EmbedLog", embedLog);
sw.Save("ExtractLog", extractLog);
sw.Save("FillUpCUE", fillUpCUE);
sw.Save("OverwriteCUEData", overwriteCUEData);
sw.Save("FilenamesANSISafe", filenamesANSISafe);
if (bruteForceDTL) sw.Save("BruteForceDTL", bruteForceDTL);
if (createEACLOG) sw.Save("CreateEACLOG", createEACLOG);
sw.Save("DetectHDCD", detectHDCD);
sw.Save("Wait750FramesForHDCD", wait750FramesForHDCD);
sw.Save("DecodeHDCD", decodeHDCD);
sw.Save("CreateM3U", createM3U);
sw.Save("CreateTOC", createTOC);
sw.Save("CreateCUEFileWhenEmbedded", createCUEFileWhenEmbedded);
sw.Save("Truncate4608ExtraSamples", truncate4608ExtraSamples);
sw.Save("LossyWAVQuality", lossyWAVQuality);
sw.Save("DecodeHDCDToLossyWAV16", decodeHDCDtoLW16);
sw.Save("DecodeHDCDTo24bit", decodeHDCDto24bit);
sw.Save("DisableAsm", disableAsm);
sw.Save("OneInstance", oneInstance);
sw.Save("CheckForUpdates", checkForUpdates);
sw.Save("Language", language);
sw.Save("SeparateDecodingThread", separateDecodingThread);
sw.Save("UseSystemProxySettings", useSystemProxySettings);
sw.Save("WriteBasicTagsFromCUEData", writeBasicTagsFromCUEData);
sw.Save("CopyBasicTags", copyBasicTags);
sw.Save("CopyUnknownTags", copyUnknownTags);
sw.Save("CopyAlbumArt", copyAlbumArt);
sw.Save("EmbedAlbumArt", embedAlbumArt);
sw.Save("ExtractAlbumArt", extractAlbumArt);
sw.Save("MaxAlbumArtSize", maxAlbumArtSize);
sw.Save("ArLogToSourceFolder", arLogToSourceFolder);
sw.Save("ArLogVerbose", arLogVerbose);
sw.Save("FixOffsetToNearest", fixOffsetToNearest);
sw.Save("ArLogFilenameFormat", arLogFilenameFormat);
sw.Save("AlArtFilenameFormat", alArtFilenameFormat);
int nEncoders = 0;
foreach (CUEToolsUDC encoder in encoders)
{
sw.Save(string.Format("ExternalEncoder{0}Name", nEncoders), encoder.name);
sw.Save(string.Format("ExternalEncoder{0}Modes", nEncoders), encoder.supported_modes);
sw.Save(string.Format("ExternalEncoder{0}Mode", nEncoders), encoder.default_mode);
if (encoder.path != null)
{
sw.Save(string.Format("ExternalEncoder{0}Extension", nEncoders), encoder.extension);
sw.Save(string.Format("ExternalEncoder{0}Path", nEncoders), encoder.path);
sw.Save(string.Format("ExternalEncoder{0}Parameters", nEncoders), encoder.parameters);
sw.Save(string.Format("ExternalEncoder{0}Lossless", nEncoders), encoder.lossless);
}
nEncoders++;
}
sw.Save("ExternalEncoders", nEncoders);
int nDecoders = 0;
foreach (KeyValuePair decoder in decoders)
if (decoder.Value.path != null)
{
sw.Save(string.Format("ExternalDecoder{0}Name", nDecoders), decoder.Key);
sw.Save(string.Format("ExternalDecoder{0}Extension", nDecoders), decoder.Value.extension);
sw.Save(string.Format("ExternalDecoder{0}Path", nDecoders), decoder.Value.path);
sw.Save(string.Format("ExternalDecoder{0}Parameters", nDecoders), decoder.Value.parameters);
nDecoders++;
}
sw.Save("ExternalDecoders", nDecoders);
int nFormats = 0;
foreach (KeyValuePair format in formats)
{
sw.Save(string.Format("CustomFormat{0}Name", nFormats), format.Key);
sw.Save(string.Format("CustomFormat{0}EncoderLossless", nFormats), format.Value.encoderLossless == null ? "" : format.Value.encoderLossless.Name);
sw.Save(string.Format("CustomFormat{0}EncoderLossy", nFormats), format.Value.encoderLossy == null ? "" : format.Value.encoderLossy.Name);
sw.Save(string.Format("CustomFormat{0}Decoder", nFormats), format.Value.decoder);
sw.Save(string.Format("CustomFormat{0}Tagger", nFormats), (int)format.Value.tagger);
sw.Save(string.Format("CustomFormat{0}AllowLossless", nFormats), format.Value.allowLossless);
sw.Save(string.Format("CustomFormat{0}AllowLossy", nFormats), format.Value.allowLossy);
sw.Save(string.Format("CustomFormat{0}AllowLossyWAV", nFormats), format.Value.allowLossyWAV);
sw.Save(string.Format("CustomFormat{0}AllowEmbed", nFormats), format.Value.allowEmbed);
nFormats++;
}
sw.Save("CustomFormats", nFormats);
int nScripts = 0;
foreach (KeyValuePair script in scripts)
{
sw.Save(string.Format("CustomScript{0}Name", nScripts), script.Key);
sw.SaveText(string.Format("CustomScript{0}Code", nScripts), script.Value.code);
int nCondition = 0;
foreach (CUEAction action in script.Value.conditions)
sw.Save(string.Format("CustomScript{0}Condition{1}", nScripts, nCondition++), (int)action);
sw.Save(string.Format("CustomScript{0}Conditions", nScripts), nCondition);
nScripts++;
}
sw.Save("CustomScripts", nScripts);
sw.Save("DefaultVerifyScript", defaultVerifyScript);
sw.Save("DefaultVerifyAndConvertScript", defaultEncodeScript);
sw.Save("GapsHandling", (int)gapsHandling);
}
public void Load(SettingsReader sr)
{
int version = sr.LoadInt32("Version", null, null) ?? 202;
fixOffsetMinimumConfidence = sr.LoadUInt32("ArFixWhenConfidence", 1, 1000) ?? 2;
fixOffsetMinimumTracksPercent = sr.LoadUInt32("ArFixWhenPercent", 1, 100) ?? 51;
encodeWhenConfidence = sr.LoadUInt32("ArEncodeWhenConfidence", 1, 1000) ?? 2;
encodeWhenPercent = sr.LoadUInt32("ArEncodeWhenPercent", 1, 100) ?? 100;
encodeWhenZeroOffset = sr.LoadBoolean("ArEncodeWhenZeroOffset") ?? false;
noUnverifiedOutput = sr.LoadBoolean("ArNoUnverifiedOutput") ?? false;
fixOffset = sr.LoadBoolean("ArFixOffset") ?? false;
writeArTagsOnEncode = sr.LoadBoolean("ArWriteCRC") ?? true;
writeArLogOnConvert = sr.LoadBoolean("ArWriteLog") ?? true;
writeArTagsOnVerify = sr.LoadBoolean("ArWriteTagsOnVerify") ?? false;
writeArLogOnVerify = sr.LoadBoolean("ArWriteLogOnVerify") ?? true;
preserveHTOA = sr.LoadBoolean("PreserveHTOA") ?? true;
autoCorrectFilenames = sr.LoadBoolean("AutoCorrectFilenames") ?? true;
flacVerify = sr.LoadBoolean("FLACVerify") ?? false;
flaCudaVerify = sr.LoadBoolean("FlaCudaVerify") ?? false;
flaCudaGPUOnly = sr.LoadBoolean("FlaCudaGPUOnly") ?? false;
flaCudaThreads = sr.LoadBoolean("FlaCudaThreads") ?? true;
wvExtraMode = sr.LoadInt32("WVExtraMode", 0, 6) ?? 0;
wvStoreMD5 = sr.LoadBoolean("WVStoreMD5") ?? false;
keepOriginalFilenames = sr.LoadBoolean("KeepOriginalFilenames") ?? false;
singleFilenameFormat = sr.Load("SingleFilenameFormat") ?? singleFilenameFormat;
trackFilenameFormat = sr.Load("TrackFilenameFormat") ?? trackFilenameFormat;
removeSpecial = sr.LoadBoolean("RemoveSpecialCharacters") ?? false;
specialExceptions = sr.Load("SpecialCharactersExceptions") ?? "-()";
replaceSpaces = sr.LoadBoolean("ReplaceSpaces") ?? false;
embedLog = sr.LoadBoolean("EmbedLog") ?? true;
extractLog = sr.LoadBoolean("ExtractLog") ?? true;
fillUpCUE = sr.LoadBoolean("FillUpCUE") ?? true;
overwriteCUEData = sr.LoadBoolean("OverwriteCUEData") ?? false;
filenamesANSISafe = sr.LoadBoolean("FilenamesANSISafe") ?? true;
bruteForceDTL = sr.LoadBoolean("BruteForceDTL") ?? false;
createEACLOG = sr.LoadBoolean("createEACLOG") ?? false;
detectHDCD = sr.LoadBoolean("DetectHDCD") ?? true;
wait750FramesForHDCD = sr.LoadBoolean("Wait750FramesForHDCD") ?? true;
decodeHDCD = sr.LoadBoolean("DecodeHDCD") ?? false;
createM3U = sr.LoadBoolean("CreateM3U") ?? false;
createTOC = sr.LoadBoolean("CreateTOC") ?? false;
createCUEFileWhenEmbedded = sr.LoadBoolean("CreateCUEFileWhenEmbedded") ?? true;
truncate4608ExtraSamples = sr.LoadBoolean("Truncate4608ExtraSamples") ?? true;
lossyWAVQuality = sr.LoadInt32("LossyWAVQuality", 0, 10) ?? 5;
decodeHDCDtoLW16 = sr.LoadBoolean("DecodeHDCDToLossyWAV16") ?? false;
decodeHDCDto24bit = sr.LoadBoolean("DecodeHDCDTo24bit") ?? true;
disableAsm = sr.LoadBoolean("DisableAsm") ?? false;
oneInstance = sr.LoadBoolean("OneInstance") ?? true;
checkForUpdates = sr.LoadBoolean("CheckForUpdates") ?? true;
writeBasicTagsFromCUEData = sr.LoadBoolean("WriteBasicTagsFromCUEData") ?? true;
copyBasicTags = sr.LoadBoolean("CopyBasicTags") ?? true;
copyUnknownTags = sr.LoadBoolean("CopyUnknownTags") ?? true;
copyAlbumArt = sr.LoadBoolean("CopyAlbumArt") ?? true;
embedAlbumArt = sr.LoadBoolean("EmbedAlbumArt") ?? true;
extractAlbumArt = sr.LoadBoolean("ExtractAlbumArt") ?? true;
maxAlbumArtSize = sr.LoadInt32("MaxAlbumArtSize", 100, 10000) ?? maxAlbumArtSize;
arLogToSourceFolder = sr.LoadBoolean("ArLogToSourceFolder") ?? arLogToSourceFolder;
arLogVerbose = sr.LoadBoolean("ArLogVerbose") ?? arLogVerbose;
fixOffsetToNearest = sr.LoadBoolean("FixOffsetToNearest") ?? fixOffsetToNearest;
arLogFilenameFormat = sr.Load("ArLogFilenameFormat") ?? arLogFilenameFormat;
alArtFilenameFormat = sr.Load("AlArtFilenameFormat") ?? alArtFilenameFormat;
separateDecodingThread = sr.LoadBoolean("SeparateDecodingThread") ?? separateDecodingThread;
useSystemProxySettings = sr.LoadBoolean("UseSystemProxySettings") ?? useSystemProxySettings;
int totalEncoders = sr.LoadInt32("ExternalEncoders", 0, null) ?? 0;
for (int nEncoders = 0; nEncoders < totalEncoders; nEncoders++)
{
string name = sr.Load(string.Format("ExternalEncoder{0}Name", nEncoders));
string extension = sr.Load(string.Format("ExternalEncoder{0}Extension", nEncoders));
string path = sr.Load(string.Format("ExternalEncoder{0}Path", nEncoders));
string parameters = sr.Load(string.Format("ExternalEncoder{0}Parameters", nEncoders));
bool lossless = sr.LoadBoolean(string.Format("ExternalEncoder{0}Lossless", nEncoders)) ?? true;
string supported_modes = sr.Load(string.Format("ExternalEncoder{0}Modes", nEncoders)) ?? "";
string default_mode = sr.Load(string.Format("ExternalEncoder{0}Mode", nEncoders)) ?? "";
CUEToolsUDC encoder;
if (name == null) continue;
if (!encoders.TryGetValue(name, out encoder))
{
if (path == null || parameters == null || extension == null) continue;
encoders.Add(new CUEToolsUDC(name, extension, lossless, supported_modes, default_mode, path, parameters));
}
else if (version == 203)
{
if (encoder.path != null)
{
if (path == null || parameters == null || extension == null) continue;
encoder.extension = extension;
encoder.path = path;
encoder.parameters = parameters;
encoder.lossless = lossless;
}
encoder.supported_modes = supported_modes;
encoder.default_mode = default_mode;
}
}
int totalDecoders = sr.LoadInt32("ExternalDecoders", 0, null) ?? 0;
for (int nDecoders = 0; nDecoders < totalDecoders; nDecoders++)
{
string name = sr.Load(string.Format("ExternalDecoder{0}Name", nDecoders));
string extension = sr.Load(string.Format("ExternalDecoder{0}Extension", nDecoders));
string path = sr.Load(string.Format("ExternalDecoder{0}Path", nDecoders));
string parameters = sr.Load(string.Format("ExternalDecoder{0}Parameters", nDecoders));
CUEToolsUDC decoder;
if (!decoders.TryGetValue(name, out decoder))
decoders.Add(name, new CUEToolsUDC(name, extension, true, "", "", path, parameters));
else
{
decoder.extension = extension;
decoder.path = path;
decoder.parameters = parameters;
}
}
int totalFormats = sr.LoadInt32("CustomFormats", 0, null) ?? 0;
for (int nFormats = 0; nFormats < totalFormats; nFormats++)
{
string extension = sr.Load(string.Format("CustomFormat{0}Name", nFormats));
string encoderLossless = sr.Load(string.Format("CustomFormat{0}EncoderLossless", nFormats)) ?? "";
string encoderLossy = sr.Load(string.Format("CustomFormat{0}EncoderLossy", nFormats)) ?? "";
string decoder = sr.Load(string.Format("CustomFormat{0}Decoder", nFormats));
CUEToolsTagger tagger = (CUEToolsTagger) (sr.LoadInt32(string.Format("CustomFormat{0}Tagger", nFormats), 0, 2) ?? 0);
bool allowLossless = sr.LoadBoolean(string.Format("CustomFormat{0}AllowLossless", nFormats)) ?? false;
bool allowLossy = sr.LoadBoolean(string.Format("CustomFormat{0}AllowLossy", nFormats)) ?? false;
bool allowLossyWav = sr.LoadBoolean(string.Format("CustomFormat{0}AllowLossyWAV", nFormats)) ?? false;
bool allowEmbed = sr.LoadBoolean(string.Format("CustomFormat{0}AllowEmbed", nFormats)) ?? false;
CUEToolsFormat format;
CUEToolsUDC udcLossless, udcLossy;
if (encoderLossless == "" || !encoders.TryGetValue(encoderLossless, out udcLossless))
udcLossless = null;
if (encoderLossy == "" || !encoders.TryGetValue(encoderLossy, out udcLossy))
udcLossy = null;
if (!formats.TryGetValue(extension, out format))
formats.Add(extension, new CUEToolsFormat(extension, tagger, allowLossless, allowLossy, allowLossyWav, allowEmbed, false, udcLossless, udcLossy, decoder));
else
{
format.encoderLossless = udcLossless;
format.encoderLossy = udcLossy;
format.decoder = decoder;
if (!format.builtin)
{
format.tagger = tagger;
format.allowLossless = allowLossless;
format.allowLossy = allowLossy;
format.allowLossyWAV = allowLossyWav;
format.allowEmbed = allowEmbed;
}
}
}
int totalScripts = sr.LoadInt32("CustomScripts", 0, null) ?? 0;
for (int nScripts = 0; nScripts < totalScripts; nScripts++)
{
string name = sr.Load(string.Format("CustomScript{0}Name", nScripts));
string code = sr.Load(string.Format("CustomScript{0}Code", nScripts));
List conditions = new List();
int totalConditions = sr.LoadInt32(string.Format("CustomScript{0}Conditions", nScripts), 0, null) ?? 0;
for (int nCondition = 0; nCondition < totalConditions; nCondition++)
conditions.Add((CUEAction)sr.LoadInt32(string.Format("CustomScript{0}Condition{1}", nScripts, nCondition), 0, null));
CUEToolsScript script;
if (!scripts.TryGetValue(name, out script))
scripts.Add(name, new CUEToolsScript(name, false, conditions, code));
else
{
if (!script.builtin)
{
script.code = code;
script.conditions = conditions;
}
}
}
defaultVerifyScript = sr.Load("DefaultVerifyScript") ?? "default";
defaultEncodeScript = sr.Load("DefaultVerifyAndConvertScript") ?? "default";
gapsHandling = (CUEStyle?)sr.LoadInt32("GapsHandling", null, null) ?? gapsHandling;
language = sr.Load("Language") ?? Thread.CurrentThread.CurrentUICulture.Name;
if (arLogFilenameFormat.Contains("%F"))
arLogFilenameFormat = "%filename%.accurip";
if (singleFilenameFormat.Contains("%F"))
singleFilenameFormat = "%filename%";
if (trackFilenameFormat.Contains("%N"))
trackFilenameFormat = "%tracknumber%. %title%";
}
public string GetDefaultDecoder(string extension)
{
CUEToolsUDC result = null;
foreach (KeyValuePair decoder in decoders)
if (decoder.Value.Extension == extension && (result == null || result.priority < decoder.Value.priority))
result = decoder.Value;
return result == null ? null : result.Name;
}
public string CleanseString (string s)
{
StringBuilder sb = new StringBuilder();
char[] invalid = Path.GetInvalidFileNameChars();
if (filenamesANSISafe)
s = Encoding.Default.GetString(Encoding.Default.GetBytes(s));
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (filenamesANSISafe && removeSpecial && specialExceptions.IndexOf(ch) < 0 && !(
((ch >= 'a') && (ch <= 'z')) ||
((ch >= 'A') && (ch <= 'Z')) ||
((ch >= '0') && (ch <= '9')) ||
(ch == ' ') || (ch == '_')))
ch = '_';
if ((Array.IndexOf(invalid, ch) >= 0) || (replaceSpaces && ch == ' '))
sb.Append("_");
else
sb.Append(ch);
}
return sb.ToString();
}
}
public class CUEToolsProfile
{
public CUEToolsProfile(string name)
{
_config = new CUEConfig();
_name = name;
switch (name)
{
case "verify":
_action = CUEAction.Verify;
_script = "only if found";
break;
case "convert":
_action = CUEAction.Encode;
break;
case "fix":
_action = CUEAction.Encode;
_script = "fix offset";
break;
}
}
public void Load(SettingsReader sr)
{
_config.Load(sr);
_useFreeDb = sr.LoadBoolean("FreedbLookup") ?? _useFreeDb;
_useMusicBrainz = sr.LoadBoolean("MusicBrainzLookup") ?? _useMusicBrainz;
_useAccurateRip = sr.LoadBoolean("AccurateRipLookup") ?? _useAccurateRip;
_useCUEToolsDB = sr.LoadBoolean("CUEToolsDBLookup") ?? _useCUEToolsDB;
_outputAudioType = (AudioEncoderType?)sr.LoadInt32("OutputAudioType", null, null) ?? _outputAudioType;
_outputAudioFormat = sr.Load("OutputAudioFmt") ?? _outputAudioFormat;
_action = (CUEAction?)sr.LoadInt32("AccurateRipMode", (int)CUEAction.Encode, (int)CUEAction.CorrectFilenames) ?? _action;
_CUEStyle = (CUEStyle?)sr.LoadInt32("CUEStyle", null, null) ?? _CUEStyle;
_writeOffset = sr.LoadInt32("WriteOffset", null, null) ?? 0;
_outputTemplate = sr.Load("OutputPathTemplate") ?? _outputTemplate;
_script = sr.Load("Script") ?? _script;
}
public void Save(SettingsWriter sw)
{
_config.Save(sw);
sw.Save("FreedbLookup", _useFreeDb);
sw.Save("MusicBrainzLookup", _useMusicBrainz);
sw.Save("AccurateRipLookup", _useAccurateRip);
sw.Save("CUEToolsDBLookup", _useCUEToolsDB);
sw.Save("OutputAudioType", (int)_outputAudioType);
sw.Save("OutputAudioFmt", _outputAudioFormat);
sw.Save("AccurateRipMode", (int)_action);
sw.Save("CUEStyle", (int)_CUEStyle);
sw.Save("WriteOffset", (int)_writeOffset);
sw.Save("OutputPathTemplate", _outputTemplate);
sw.Save("Script", _script);
}
public CUEConfig _config;
public AudioEncoderType _outputAudioType = AudioEncoderType.Lossless;
public string _outputAudioFormat = "flac", _outputTemplate = null, _script = "default";
public CUEAction _action = CUEAction.Encode;
public CUEStyle _CUEStyle = CUEStyle.SingleFileWithCUE;
public int _writeOffset = 0;
public bool _useFreeDb = true, _useMusicBrainz = true, _useAccurateRip = true, _useCUEToolsDB = true;
public string _name;
}
public class CUEToolsProgressEventArgs : EventArgs
{
public string status = string.Empty;
public double percentTrck = 0;
public double percentDisk = 0.0;
public int offset = 0;
public string input = string.Empty;
public string output = string.Empty;
}
public class CUEToolsSelectionEventArgs : EventArgs
{
public object[] choices;
public int selection = -1;
}
public class CUEToolsSourceFile
{
public string path;
public string contents;
public object data;
public CUEToolsSourceFile(string _path, TextReader reader)
{
path = _path;
contents = reader.ReadToEnd();
reader.Close();
}
}
public class CUESheet {
private bool _stop, _pause;
private List _attributes;
private List _tracks;
private List _sources;
private List _sourcePaths, _trackFilenames;
private string _htoaFilename, _singleFilename;
private bool _hasHTOAFilename = false, _hasTrackFilenames = false, _hasSingleFilename = false, _appliedWriteOffset;
private bool _hasEmbeddedCUESheet;
private bool _paddedToFrame, _truncated4608, _usePregapForFirstTrackInSingleFile;
private int _writeOffset;
private CUEAction _action;
private bool _useAccurateRip = false;
private bool _useCUEToolsDB = false;
private bool _useCUEToolsDBFix = false;
private bool _useCUEToolsDBSibmit = false;
private bool _processed = false;
private uint? _minDataTrackLength;
private string _accurateRipId;
private string _eacLog;
private string _inputPath, _inputDir;
private string _outputPath;
private string[] _destPaths;
private TagLib.File _fileInfo;
private const int _arOffsetRange = 5 * 588 - 1;
private IAudioDest hdcdDecoder;
private AudioEncoderType _audioEncoderType = AudioEncoderType.Lossless;
private bool _outputLossyWAV = false;
private string _outputFormat = "wav";
private CUEStyle _outputStyle = CUEStyle.SingleFile;
private CUEConfig _config;
private string _cddbDiscIdTag;
private bool _isCD;
private string _ripperLog;
private ICDRipper _ripper;
private bool _isArchive;
private List _archiveContents;
private string _archiveCUEpath;
private ICompressionProvider _archive;
private string _archivePassword;
private CUEToolsProgressEventArgs _progress;
private AccurateRipVerify _arVerify;
private CUEToolsDB _CUEToolsDB;
private CDImageLayout _toc;
private string _arLogFileName, _alArtFileName;
private TagLib.IPicture[] _albumArt;
private int _padding = 8192;
private IWebProxy proxy;
public event EventHandler PasswordRequired;
public event EventHandler CUEToolsProgress;
public event EventHandler CUEToolsSelection;
public CUESheet(CUEConfig config)
{
_config = config;
_progress = new CUEToolsProgressEventArgs();
_attributes = new List();
_tracks = new List();
_trackFilenames = new List();
_toc = new CDImageLayout();
_sources = new List();
_sourcePaths = new List();
_stop = false;
_pause = false;
_outputPath = null;
_paddedToFrame = false;
_truncated4608 = false;
_usePregapForFirstTrackInSingleFile = false;
_action = CUEAction.Encode;
_appliedWriteOffset = false;
_minDataTrackLength = null;
hdcdDecoder = null;
_hasEmbeddedCUESheet = false;
_isArchive = false;
_isCD = false;
_albumArt = null;
proxy = _config.useSystemProxySettings ? WebRequest.GetSystemWebProxy() : null;
}
public void OpenCD(ICDRipper ripper)
{
_ripper = ripper;
_toc = (CDImageLayout)_ripper.TOC.Clone();
for (int iTrack = 0; iTrack < _toc.AudioTracks; iTrack++)
{
_trackFilenames.Add(string.Format("{0:00}.wav", iTrack + 1));
_tracks.Add(new TrackInfo());
}
_arVerify = new AccurateRipVerify(_toc, proxy);
_CUEToolsDB = new CUEToolsDB(_toc, proxy);
_CUEToolsDB.UploadHelper.onProgress += new EventHandler(UploadProgress);
_isCD = true;
SourceInfo cdInfo;
cdInfo.Path = _ripper.ARName;
cdInfo.Offset = 0;
cdInfo.Length = _toc.AudioLength * 588;
_sources.Add(cdInfo);
_ripper.ReadProgress += new EventHandler(CDReadProgress);
}
public void Close()
{
if (_archive != null)
_archive.Close();
_archive = null;
if (_ripper != null)
_ripper.Close();
_ripper = null;
}
public AccurateRipVerify ArVerify
{
get
{
return _arVerify;
}
}
public CUEToolsDB CTDB
{
get
{
return _CUEToolsDB;
}
}
public ICDRipper CDRipper
{
get
{
return _ripper;
}
set
{
_ripper = value;
}
}
public void CopyMetadata(CUESheet metadata)
{
TotalDiscs = metadata.TotalDiscs;
DiscNumber = metadata.DiscNumber;
Year = metadata.Year;
Genre = metadata.Genre;
Artist = metadata.Artist;
Title = metadata.Title;
for (int i = 0; i < Tracks.Count; i++)
{
Tracks[i].Title = metadata.Tracks[i].Title;
Tracks[i].Artist = metadata.Tracks[i].Artist;
}
}
public void FillFromMusicBrainz(MusicBrainz.Release release)
{
Year = release.GetEvents().Count > 0 ? release.GetEvents()[0].Date.Substring(0, 4) : "";
Artist = release.GetArtist();
Title = release.GetTitle();
// How to get Genre: http://mm.musicbrainz.org/ws/1/release/6fe1e218-2aee-49ac-94f0-7910ba2151df.html?type=xml&inc=tags
//Catalog = release.GetEvents().Count > 0 ? release.GetEvents()[0].Barcode : "";
for (int i = 1; i <= _toc.AudioTracks; i++)
{
MusicBrainz.Track track = release.GetTracks()[(int)_toc[i].Number - 1]; // !!!!!! - _toc.FirstAudio
Tracks[i - 1].Title = track.GetTitle();
Tracks[i - 1].Artist = track.GetArtist();
}
}
public void FillFromFreedb(Freedb.CDEntry cdEntry)
{
Year = cdEntry.Year;
Genre = cdEntry.Genre;
Artist = cdEntry.Artist;
Title = cdEntry.Title;
for (int i = 0; i < _toc.AudioTracks; i++)
{
Tracks[i].Title = cdEntry.Tracks[i].Title;
Tracks[i].Artist = cdEntry.Artist;
}
}
public List