Пример #1
0
		public static IAudioDest GetAudioDest(AudioEncoderType audioEncoderType, string path, AudioPCMConfig pcm, long finalSampleCount, int padding, string extension, CUEConfig config)
		{
			IAudioDest dest;
			if (audioEncoderType == AudioEncoderType.NoAudio || extension == ".dummy")
			{
				dest = new DummyWriter(path, pcm);
				dest.FinalSampleCount = finalSampleCount;
				return dest;
			}
			CUEToolsFormat fmt;
			if (!extension.StartsWith(".") || !config.formats.TryGetValue(extension.Substring(1), out fmt))
				throw new Exception("Unsupported audio type: " + path);
			CUEToolsUDC encoder = audioEncoderType == AudioEncoderType.Lossless ? fmt.encoderLossless :
				audioEncoderType == AudioEncoderType.Lossy ? fmt.encoderLossy :
				null;
			if (encoder == null)
				throw new Exception("Unsupported audio type: " + path);
			if (encoder.path != null)
				dest = new UserDefinedWriter(path, null, pcm, encoder.path, encoder.parameters, encoder.default_mode, padding);
			else if (encoder.type != null)
			{
				object o = Activator.CreateInstance(encoder.type, path, pcm);
				if (o == null || !(o is IAudioDest))
					throw new Exception("Unsupported audio type: " + path + ": " + encoder.type.FullName);
				dest = o as IAudioDest;
			}
			else
				throw new Exception("Unsupported audio type: " + path);
			dest.CompressionLevel = encoder.DefaultModeIndex;
			dest.FinalSampleCount = finalSampleCount;
			dest.Padding = padding;
			dest.Settings = encoder.settings;
			return dest;
		}
Пример #2
0
		public frmCUEPlayer()
		{
			InitializeComponent();
			_icon_mgr = new ShellIconMgr();
			_config = new CUEConfig();
			_config.separateDecodingThread = false;
		}
Пример #3
0
		public void Init(frmCUEPlayer parent)
		{
			_config = parent.Config;
			MdiParent = parent;
			Show();
			fileSystemTreeView1.IconManager = parent.IconMgr;
			fileSystemTreeView1.SelectedFolder = ExtraSpecialFolder.MyMusic;
		}
Пример #4
0
		static void Main(string[] args)
		{
			if (args.Length > 1 && args[0].Length > 1 && args[0][0] == '/')
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				frmBatch batch = new frmBatch();
				batch.Profile = args[0].Substring(1);

				if (args.Length == 2 && args[1][0] != '@')
					batch.InputPath = args[1];
				else for (int i = 1; i < args.Length; i++)
				{
					if (args[i][0] == '@')
					{
						string lineStr;
						StreamReader sr;
						try
						{
							sr = new StreamReader(args[i].Substring(1), Encoding.Default);
							while ((lineStr = sr.ReadLine()) != null)
								batch.AddInputPath(lineStr);
						}
						catch
						{
							batch.AddInputPath(args[i]);
						}
					} else
						batch.AddInputPath(args[i]);
				}
				Application.Run(batch);
				return;
			}

			string myId = "BZ92759C-63Q7-444e-ADA6-E495634A493D";
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			CUEConfig config = new CUEConfig();
			config.Load(new SettingsReader("CUE Tools", "settings.txt", Application.ExecutablePath));
			try { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(config.language); }
			catch { }
			frmCUETools form = new frmCUETools();
			if (!config.oneInstance || SingletonController.IamFirst(myId, new SingletonController.ReceiveDelegate(form.OnSecondCall)))
			{
				if (args.Length == 1)
					form.InputPath = args[0];
				Application.Run(form);
			}
			else
			{
				List<string> newArgs = new List<string>();
				foreach (string arg in args)
					newArgs.Add(Path.GetFullPath(arg));
				SingletonController.Send(myId, newArgs.ToArray());
			}
			SingletonController.Cleanup();
		}
Пример #5
0
 public static void UpdateTags(string path, NameValueCollection tags, CUEConfig config)
 {
     TagLib.UserDefined.AdditionalFileTypes.Config = config;
     TagLib.File fileInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(path));
     if (UpdateTags(fileInfo, tags, config))
         fileInfo.Save();
     //IAudioSource audioSource = AudioReadWrite.GetAudioSource(path, null, config);
     //audioSource.Tags = tags;
     //audioSource.UpdateTags(false);
     //audioSource.Close();
     //audioSource = null;
 }
Пример #6
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			string arch = Marshal.SizeOf(typeof(IntPtr)) == 8 ? "x64" : "Win32";
			GetSatelliteAssemblies("Plugins (" + arch + ")");

			CUEConfig config = new CUEConfig();
			config.Load(new SettingsReader("CUERipper", "settings.txt", Application.ExecutablePath));
			try { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(config.language); }
			catch { }

			Application.Run(new frmCUERipper());
		}
Пример #7
0
		public frmCUERipper()
		{
			InitializeComponent();
			_config = new CUEConfig();
			_startStop = new StartStop();
			m_icon_mgr = new CUEControls.ShellIconMgr();
			m_icon_mgr.SetExtensionIcon(".flac", Properties.Resources.flac);
			m_icon_mgr.SetExtensionIcon(".wv", Properties.Resources.wv);
			m_icon_mgr.SetExtensionIcon(".ape", Properties.Resources.ape);
			m_icon_mgr.SetExtensionIcon(".tta", Properties.Resources.tta);
			m_icon_mgr.SetExtensionIcon(".wav", Properties.Resources.wave);
			m_icon_mgr.SetExtensionIcon(".mp3", Properties.Resources.mp3);
			m_icon_mgr.SetExtensionIcon(".m4a", Properties.Resources.ipod_sound);
			m_icon_mgr.SetExtensionIcon(".ogg", Properties.Resources.ogg);
		}
Пример #8
0
 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;
     }
 }
Пример #9
0
		public void Init(frmCUEPlayer parent)
		{
			_config = parent.Config;
			dataSet = parent.DataSet;
			MdiParent = parent;
			Show();
			_icon_mgr = parent.IconMgr;
			listViewTracks.SmallImageList = _icon_mgr.ImageList;
			foreach (DataSet1.PlaylistRow row in dataSet.Playlist)
			{
				try
				{
					listViewTracks.Items.Add(ToItem(row));
				}
				catch (Exception ex)
				{
					Trace.WriteLine(ex.Message);
				}
			}
		}
Пример #10
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ArCueDotNet <filename>");
                return;
            }
            string pathIn = args[0];
            if (!File.Exists(pathIn))
            {
                Console.WriteLine("Input CUE Sheet not found.");
                return;
            }
            CUEConfig config = new CUEConfig();
            config.writeArLogOnVerify = false;
            config.writeArTagsOnVerify = false;
            config.autoCorrectFilenames = true;
            config.extractAlbumArt = false;
            config.embedAlbumArt = false;

            string accurateRipLog;
            try
            {
                CUESheet cueSheet = new CUESheet(config);
                cueSheet.Action = CUEAction.Verify;
                //cueSheet.OutputStyle = CUEStyle.SingleFile;
                cueSheet.Open(pathIn);
                cueSheet.UseAccurateRip();
                cueSheet.GenerateFilenames(AudioEncoderType.NoAudio, "dummy", pathIn);
                cueSheet.Go();

                accurateRipLog = CUESheetLogWriter.GetAccurateRipLog(cueSheet);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                return;
            }

            Console.Write(accurateRipLog);
        }
Пример #11
0
        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;
            }
        }
Пример #12
0
		public static IAudioSource GetAudioSource(string path, Stream IO, CUEConfig config)
		{
			string extension = Path.GetExtension(path).ToLower();
			string filename = Path.GetFileNameWithoutExtension(path);
			string secondExtension = Path.GetExtension(filename).ToLower();
			if (secondExtension != ".lossy" && secondExtension != ".lwcdf")
				return GetAudioSource(path, IO, extension, config);

			string lossyPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(filename) + ".lossy" + extension);
			string lwcdfPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(filename) + ".lwcdf" + extension);
			IAudioSource lossySource = GetAudioSource(lossyPath, null, extension, config);
			IAudioSource lwcdfSource = null;
			try
			{
				lwcdfSource = GetAudioSource(lwcdfPath, null, extension, config);
			}
			catch
			{
				return lossySource;
			}
			return new LossyWAVReader(lossySource, lwcdfSource);
		}
Пример #13
0
		public static IAudioSource GetAudioSource(string path, Stream IO, string extension, CUEConfig config)
		{
			if (extension == ".dummy")
			{
				using (StreamReader sr = (IO == null ? new StreamReader(path) : new StreamReader(IO))) {
					string slen = sr.ReadLine();
					long len;
					if (!long.TryParse(slen, out len))
						len = CDImageLayout.TimeFromString(slen) * 588;
					return new SilenceGenerator(len);
				}
			}
			if (extension == ".bin")
				return new WAVReader(path, IO, AudioPCMConfig.RedBook);
			CUEToolsFormat fmt;
			if (!extension.StartsWith(".") || !config.formats.TryGetValue(extension.Substring(1), out fmt))
				throw new Exception("Unsupported audio type: " + path);
			CUEToolsUDC decoder;
			if (fmt.decoder == null || !config.decoders.TryGetValue(fmt.decoder, out decoder))
				throw new Exception("Unsupported audio type: " + path);
			if (decoder.path != null)
				return new UserDefinedReader(path, IO, decoder.path, decoder.parameters);
			if (decoder.type == null)
				throw new Exception("Unsupported audio type: " + path);

			try
			{
				object src = Activator.CreateInstance(decoder.type, path, IO);
				if (src == null || !(src is IAudioSource))
					throw new Exception("Unsupported audio type: " + path + ": " + decoder.type.FullName);
				return src as IAudioSource;
			}
			catch (System.Reflection.TargetInvocationException ex)
			{
				if (ex.InnerException == null)
					throw ex;
				throw ex.InnerException;
			}
		}
Пример #14
0
 public static bool UpdateTags(TagLib.File fileInfo, NameValueCollection tags, CUEConfig config)
 {
     if (fileInfo is TagLib.Riff.File)
         return false;
     TagLib.Ogg.XiphComment xiph = (TagLib.Ogg.XiphComment)fileInfo.GetTag(TagLib.TagTypes.Xiph);
     if (xiph != null)
     {
         foreach (string tag in tags.AllKeys)
             xiph.SetField(tag, tags.GetValues(tag));
         return true;
     }
     if (fileInfo is TagLib.Mpeg4.File)
     {
         var mpeg4 = (TagLib.Mpeg4.AppleTag)fileInfo.GetTag(TagLib.TagTypes.Apple, true);
         foreach (string tag in tags.AllKeys)
         {
             mpeg4.SetDashBox("com.apple.iTunes", tag, string.Join(";", tags.GetValues(tag)));
         }
         return true;
     }
     if (fileInfo is TagLib.Mpeg.AudioFile || (fileInfo is TagLib.UserDefined.File && (fileInfo as TagLib.UserDefined.File).Tagger == CUEToolsTagger.ID3v2))
     {
         var id3v2 = (TagLib.Id3v2.Tag)fileInfo.GetTag(TagLib.TagTypes.Id3v2, true);
         id3v2.Version = (byte) (config.advanced.UseId3v24 ? 4 : 3);
         foreach (string tag in tags.AllKeys)
         {
             var frame = TagLib.Id3v2.UserTextInformationFrame.Get(id3v2, tag, true);
             frame.Text = tags.GetValues(tag);
         }
         return true;
     }
     TagLib.Ape.Tag ape = (TagLib.Ape.Tag)fileInfo.GetTag(TagLib.TagTypes.Ape, true);
     foreach (string tag in tags.AllKeys)
         ape.SetValue(XiphTagNameToApe(tag), tags.GetValues(tag));
     return true;
 }
Пример #15
0
 public static string CreateDummyCUESheet(CUEConfig _config, string pathIn)
 {
     pathIn = Path.GetFullPath(pathIn);
     List<FileGroupInfo> fileGroups = CUESheet.ScanFolder(_config, Path.GetDirectoryName(pathIn));
     FileGroupInfo fileGroup = fileGroups.Find(f => f.type == FileGroupInfoType.TrackFiles && f.Contains(pathIn)) ??
         fileGroups.Find(f => f.type == FileGroupInfoType.FileWithCUE && f.Contains(pathIn)) ??
         fileGroups.Find(f => f.type == FileGroupInfoType.M3UFile && f.Contains(pathIn));
     return fileGroup == null ? null : CreateDummyCUESheet(_config, fileGroup);
 }
Пример #16
0
		public static IAudioDest GetAudioDest(AudioEncoderType audioEncoderType, string path, long finalSampleCount, int bitsPerSample, int sampleRate, int padding, CUEConfig config)
		{
			string extension = Path.GetExtension(path).ToLower();
			string filename = Path.GetFileNameWithoutExtension(path);
			AudioPCMConfig pcm = new AudioPCMConfig(bitsPerSample, 2, sampleRate);
			if (audioEncoderType == AudioEncoderType.NoAudio || audioEncoderType == AudioEncoderType.Lossless || Path.GetExtension(filename).ToLower() != ".lossy")
				return GetAudioDest(audioEncoderType, path, pcm, finalSampleCount, padding, extension, config);

			string lwcdfPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(filename) + ".lwcdf" + extension);
			AudioPCMConfig lossypcm = new AudioPCMConfig((config.detectHDCD && config.decodeHDCD && !config.decodeHDCDtoLW16) ? 24 : 16, 2, sampleRate);
			IAudioDest lossyDest = GetAudioDest(AudioEncoderType.Lossless, path, lossypcm, finalSampleCount, padding, extension, config);
			IAudioDest lwcdfDest = audioEncoderType == AudioEncoderType.Hybrid ? GetAudioDest(AudioEncoderType.Lossless, lwcdfPath, lossypcm, finalSampleCount, padding, extension, config) : null;
			return new LossyWAVWriter(lossyDest, lwcdfDest, config.lossyWAVQuality, pcm);
		}
Пример #17
0
 public CUESheet(CUEConfig config)
 {
     _config = config;
     _progress = new CUEToolsProgressEventArgs();
     _progress.cueSheet = this;
     _attributes = new List<CUELine>();
     _tracks = new List<TrackInfo>();
     _trackFilenames = new List<string>();
     _toc = new CDImageLayout();
     _sources = new List<SourceInfo>();
     _sourcePaths = new List<string>();
     _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;
     _useLocalDB = false;
     proxy = _config.GetProxy();
 }
Пример #18
0
        public static List<FileGroupInfo> ScanFolder(CUEConfig _config, IEnumerable<FileSystemInfo> files)
        {
            List<FileGroupInfo> fileGroups = new List<FileGroupInfo>();
            foreach (FileSystemInfo file in files)
            {
                // file.Refresh();
                // file.Attributes returns -1 for long paths!!!
                if ((file.Attributes & FileAttributes.Hidden) != 0)
                    continue;
                if ((file.Attributes & FileAttributes.Directory) != 0)
                {
                    // foreach (FileSystemInfo subfile in ((DirectoryInfo)e.file).GetFileSystemInfos())
                    // if (IsVisible(subfile))
                    // {
                    //     e.isExpandable = true;
                    //  break;
                    // }
                    fileGroups.Add(new FileGroupInfo(file, FileGroupInfoType.Folder));
                    continue;
                }
                string ext = file.Extension.ToLower();
                if (ext == ".cue")
                {
                    fileGroups.Add(new FileGroupInfo(file, FileGroupInfoType.CUESheetFile));
                    continue;
                }
                if (ext == ".m3u")
                {
                    FileGroupInfo m3uGroup = new FileGroupInfo(file, FileGroupInfoType.M3UFile);
                    using (StreamReader m3u = new StreamReader(file.FullName))
                    {
                        do
                        {
                            string line = m3u.ReadLine();
                            if (line == null) break;
                            if (line == "" || line[0] == '#') continue;
                            //if (line.IndexOfAny(Path.GetInvalidPathChars()) >= 0) 
                            //    continue;
                            try
                            {
                                line = Path.Combine(Path.GetDirectoryName(file.FullName), line);
                                if (File.Exists(line))
                                {
                                    FileInfo f = new FileInfo(line);
                                    CUEToolsFormat fmt1;
                                    if (!f.Extension.StartsWith(".") || !_config.formats.TryGetValue(f.Extension.ToLower().Substring(1), out fmt1) || !fmt1.allowLossless)
                                        throw new Exception("not lossless");
                                    m3uGroup.files.Add(f);
                                    continue;
                                }
                            }
                            catch { }
                            m3uGroup = null;
                            break;
                        } while (true);
                    };
                    if (m3uGroup != null)
                        fileGroups.Add(m3uGroup);
                    continue;
                }
                if (ext == ".zip")
                {
                    fileGroups.Add(new FileGroupInfo(file, FileGroupInfoType.Archive));
                    //try
                    //{
                    //    using (ICSharpCode.SharpZipLib.Zip.ZipFile unzip = new ICSharpCode.SharpZipLib.Zip.ZipFile(file.FullName))
                    //    {
                    //        foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in unzip)
                    //        {
                    //            if (entry.IsFile && Path.GetExtension(entry.Name).ToLower() == ".cue")
                    //            {
                    //                e.node.Nodes.Add(fileSystemTreeView1.NewNode(file, false));
                    //                break;
                    //            }

                    //        }
                    //        unzip.Close();
                    //    }
                    //}
                    //catch
                    //{
                    //}
                    continue;
                }
                if (ext == ".rar")
                {
                    fileGroups.Add(new FileGroupInfo(file, FileGroupInfoType.Archive));
                    continue;
                }
                CUEToolsFormat fmt;
                if (ext.StartsWith(".") && _config.formats.TryGetValue(ext.Substring(1), out fmt) && fmt.allowLossless)
                {
                    uint disc = 0;
                    uint number = 0;
                    string album = null;
                    string cueFound = null;
                    TimeSpan dur = TimeSpan.Zero;
                    TagLib.UserDefined.AdditionalFileTypes.Config = _config;
                    TagLib.File.IFileAbstraction fileAbsraction = new TagLib.File.LocalFileAbstraction(file.FullName);
                    try
                    {
                        TagLib.File fileInfo = TagLib.File.Create(fileAbsraction);
                        disc = fileInfo.Tag.Disc;
                        album = fileInfo.Tag.Album;
                        number = fileInfo.Tag.Track;
                        dur = fileInfo.Properties.Duration;
                        cueFound = fmt.allowEmbed ? Tagging.Analyze(fileInfo).Get("CUESHEET") : null;
                    }
                    catch { }
                    if (cueFound != null)
                    {
                        FileGroupInfo group = new FileGroupInfo(file, FileGroupInfoType.FileWithCUE);
                        if (dur != TimeSpan.Zero)
                            group.TOC = CUE2TOC(cueFound, (int)((dur.TotalMilliseconds * 75 + 500) / 1000));
                        fileGroups.Add(group);
                        continue;
                    }
                    disc = Math.Min(5, Math.Max(1, disc));
                    FileGroupInfo groupFound = null;
                    foreach (FileGroupInfo fileGroup in fileGroups)
                    {
                        if (fileGroup.type == FileGroupInfoType.TrackFiles
                            && fileGroup.discNo == disc
                            && fileGroup.album == album
                            && fileGroup.main.Extension.ToLower() == ext)
                        {
                            groupFound = fileGroup;
                            break;
                        }
                    }
                    if (groupFound == null)
                    {
                        groupFound = new FileGroupInfo(file, FileGroupInfoType.TrackFiles);
                        groupFound.discNo = disc;
                        groupFound.album = album;
                        groupFound.durations = new Dictionary<FileSystemInfo, TimeSpan>();
                        fileGroups.Add(groupFound);
                    }
                    groupFound.files.Add(file);
                    if (number > 0) groupFound.numbers.Add(file, number);
                    if (dur != TimeSpan.Zero) groupFound.durations.Add(file, dur);
                }
            }
            fileGroups.RemoveAll(group => group.type == FileGroupInfoType.TrackFiles && group.files.Count < 2);
            // tracks must be sorted according to tracknumer (or filename if missing)
            foreach (FileGroupInfo group in fileGroups)
                if (group.type == FileGroupInfoType.TrackFiles)
                {
                    group.files.Sort(group.Compare());
                    group.numbers = null;
                    group.TOC = new CDImageLayout();
                    foreach (FileSystemInfo f in group.files)
                    {
                        if (!group.durations.ContainsKey(f))
                        {
                            group.TOC = null;
                            break;
                        }
                        uint len = (uint)((group.durations[f].TotalMilliseconds * 75 + 500) / 1000);
                        group.TOC.AddTrack(new CDTrack((uint)group.TOC.TrackCount + 1, group.TOC.Length, len, true, false));
                    }
                }
            fileGroups.Sort(FileGroupInfo.Compare);
            return fileGroups;
        }
Пример #19
0
 public static List<FileGroupInfo> ScanFolder(CUEConfig _config, string path)
 {
     DirectoryInfo dir = new DirectoryInfo(path);
     return ScanFolder(_config, dir.GetFileSystemInfos());
 }
Пример #20
0
        public static string CorrectAudioFilenames(CUEConfig _config, string dir, string cue, bool always, List<string> files, out string extension)
        {
            List<string> lines = new List<string>();
            List<int> filePos = new List<int>();
            List<string> origFiles = new List<string>();
            bool foundAll = true;
            string[] audioFiles = null;
            string lineStr;
            CUELine line;
            int i;
            string CDDBID = "";
            //bool isBinary = false;

            using (StringReader sr = new StringReader(cue))
            {
                while ((lineStr = sr.ReadLine()) != null)
                {
                    lines.Add(lineStr);
                    line = new CUELine(lineStr);
                    if ((line.Params.Count == 3) && (line.Params[0].ToUpper() == "FILE"))
                    {
                        string fileType = line.Params[2].ToUpper();
                        if (fileType == "MOTOROLA")
                            continue;
                        if (fileType == "BINARY")
                            continue;
                        //{
                        //    if (filePos.Count > 0)
                        //        continue;
                        //    isBinary = true;
                        //}
                        //else
                        //{
                        //    if (isBinary)
                        //    {
                        //        filePos.Clear();
                        //        origFiles.Clear();
                        //        foundAll = false;
                        //        isBinary = false;
                        //    }
                        //}
                        filePos.Add(lines.Count - 1);
                        origFiles.Add(line.Params[1]);
                        foundAll &= (FileLocator.LocateFile(dir, line.Params[1], files) != null);
                    }
                    if (line.Params.Count == 3 && line.Params[0].ToUpper() == "REM" && line.Params[1].ToUpper() == "DISCID")
                        CDDBID = line.Params[2].ToLower();
                }
                sr.Close();
            }


            extension = null;
            if (foundAll && !always)
                return cue;

            foundAll = false;

            foreach (KeyValuePair<string, CUEToolsFormat> format in _config.formats)
            {
                List<string> newFiles = new List<string>();
                for (int j = 0; j < origFiles.Count; j++)
                {
                    string newFilename = Path.ChangeExtension(Path.GetFileName(origFiles[j]), "." + format.Key);
                    string locatedFilename = FileLocator.LocateFile(dir, newFilename, files);
                    if (locatedFilename != null)
                        newFiles.Add(locatedFilename);
                }
                if (newFiles.Count == origFiles.Count)
                {
                    audioFiles = newFiles.ToArray();
                    extension = format.Key;
                    foundAll = true;
                    break;
                }
            }

            if (!foundAll && files == null)
            {
                List<FileGroupInfo> fileGroups = CUESheet.ScanFolder(_config, dir == "" ? "." : dir);

                // Choose filegroup by track count
                List<FileGroupInfo>
                    matching = fileGroups.FindAll(f => f.type == FileGroupInfoType.TrackFiles && f.files.Count == filePos.Count);
                // If ambiguous, use DISCID
                if (matching.Count > 1)
                    matching = fileGroups.FindAll(f => f.type == FileGroupInfoType.TrackFiles && f.files.Count == filePos.Count && f.TOC != null && AccurateRipVerify.CalculateCDDBId(f.TOC).ToLower() == CDDBID);
                if (matching.Count == 1)
                {
                    audioFiles = matching[0].files.ConvertAll<string>(info => info.FullName).ToArray();
                    // No need to sort - hopefully already sorted by ScanFolder
                    extension = matching[0].main.Extension.ToLower().TrimStart('.');
                    foundAll = true;
                }

                if (!foundAll && filePos.Count == 1)
                    foreach (FileGroupInfo fileGroup in fileGroups)
                    {
                        if (fileGroup.type == FileGroupInfoType.FileWithCUE && fileGroup.TOC != null)
                        {
                            CDImageLayout toc = CUE2TOC(cue, (int)fileGroup.TOC.AudioLength);
                            if (toc == null || toc.TrackOffsets != fileGroup.TOC.TrackOffsets)
                                continue;
                            if (foundAll)
                            {
                                foundAll = false;
                                break;
                            }
                            audioFiles = new string[] { fileGroup.main.FullName };
                            extension = fileGroup.main.Extension.ToLower().TrimStart('.');
                            foundAll = true;
                        }
                    }
            }

            // Use old-fashioned way if dealing with archive (files != null)
            // or with single file (filePos.Count == 1).
            // In other cases we use CUESheet.ScanFolder, which
            // is better at sorting and separating albums,
            // but doesn't support archives and single files yet.
            if (!foundAll)// && (files != null || filePos.Count == 1))
                foreach (KeyValuePair<string, CUEToolsFormat> format in _config.formats)
                {
                    if (files == null)
                        audioFiles = Directory.GetFiles(dir == "" ? "." : dir, "*." + format.Key);
                    else
                        audioFiles = files.FindAll(s => Path.GetDirectoryName(s) == dir && Path.GetExtension(s).ToLower() == "." + format.Key).ToArray();
                    if (audioFiles.Length == filePos.Count)
                    {
                        Array.Sort(audioFiles, FileGroupInfo.CompareTrackNames);
                        extension = format.Key;
                        foundAll = true;
                        break;
                    }
                }

            if (!foundAll)
                throw new Exception("unable to locate the audio files");

            for (i = 0; i < filePos.Count; i++)
                lines[filePos[i]] = "FILE \"" + Path.GetFileName(audioFiles[i]) + "\" WAVE";

            using (StringWriter sw = new StringWriter())
            {
                for (i = 0; i < lines.Count; i++)
                {
                    sw.WriteLine(lines[i]);
                }
                return sw.ToString();
            }
        }
Пример #21
0
 public static string CorrectAudioFilenames(CUEConfig _config, string path, bool always)
 {
     StreamReader sr = new StreamReader(path, CUESheet.Encoding);
     string cue = sr.ReadToEnd();
     sr.Close();
     string extension;
     return CorrectAudioFilenames(_config, Path.GetDirectoryName(path), cue, always, null, out extension);
 }
Пример #22
0
        public static IAudioDest GetAudioDest(AudioEncoderType audioEncoderType, string path, AudioPCMConfig pcm, long finalSampleCount, int padding, string extension, CUEConfig config)
        {
            IAudioDest dest;

            if (audioEncoderType == AudioEncoderType.NoAudio || extension == ".dummy")
            {
                return new Codecs.NULL.AudioEncoder(path, new Codecs.WAV.EncoderSettings(pcm))
                       {
                           FinalSampleCount = finalSampleCount
                       }
            }
            ;
            CUEToolsFormat fmt;

            if (!extension.StartsWith(".") || !config.formats.TryGetValue(extension.Substring(1), out fmt))
            {
                throw new Exception("Unsupported audio type: " + path);
            }
            AudioEncoderSettingsViewModel encoder = audioEncoderType == AudioEncoderType.Lossless ? fmt.encoderLossless :
                                                    audioEncoderType == AudioEncoderType.Lossy ? fmt.encoderLossy :
                                                    null;

            if (encoder == null)
            {
                throw new Exception("Unsupported audio type: " + path);
            }
            var settings = encoder.Settings.Clone();

            settings.PCM     = pcm;
            settings.Padding = padding;
            object o;

            try
            {
                o = Activator.CreateInstance(settings.EncoderType, settings, path, null);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
            if (o == null || !(o is IAudioDest))
            {
                throw new Exception("Unsupported audio type: " + path + ": " + settings.EncoderType.FullName);
            }
            dest = o as IAudioDest;
            dest.FinalSampleCount = finalSampleCount;
            return(dest);
        }
    }
Пример #23
0
        public CUEConfig(CUEConfig src)
        {
            fixOffsetMinimumConfidence    = src.fixOffsetMinimumConfidence;
            fixOffsetMinimumTracksPercent = src.fixOffsetMinimumTracksPercent;
            encodeWhenConfidence          = src.encodeWhenConfidence;
            encodeWhenPercent             = src.encodeWhenPercent;
            encodeWhenZeroOffset          = src.encodeWhenZeroOffset;
            fixOffset           = src.fixOffset;
            noUnverifiedOutput  = src.noUnverifiedOutput;
            writeArTagsOnEncode = src.writeArTagsOnEncode;
            writeArLogOnConvert = src.writeArLogOnConvert;
            writeArTagsOnVerify = src.writeArTagsOnVerify;
            writeArLogOnVerify  = src.writeArLogOnVerify;

            autoCorrectFilenames  = src.autoCorrectFilenames;
            preserveHTOA          = src.preserveHTOA;
            detectGaps            = src.detectGaps;
            keepOriginalFilenames = src.keepOriginalFilenames;
            trackFilenameFormat   = src.trackFilenameFormat;
            singleFilenameFormat  = src.singleFilenameFormat;
            removeSpecial         = src.removeSpecial;
            specialExceptions     = src.specialExceptions;
            replaceSpaces         = src.replaceSpaces;
            embedLog                  = src.embedLog;
            extractLog                = src.extractLog;
            fillUpCUE                 = src.fillUpCUE;
            overwriteCUEData          = src.overwriteCUEData;
            filenamesANSISafe         = src.filenamesANSISafe;
            bruteForceDTL             = src.bruteForceDTL;
            createEACLOG              = src.createEACLOG;
            detectHDCD                = src.detectHDCD;
            wait750FramesForHDCD      = src.wait750FramesForHDCD;
            decodeHDCD                = src.decodeHDCD;
            createM3U                 = src.createM3U;
            createCUEFileWhenEmbedded = src.createCUEFileWhenEmbedded;
            truncate4608ExtraSamples  = src.truncate4608ExtraSamples;
            decodeHDCDtoLW16          = src.decodeHDCDtoLW16;
            decodeHDCDto24bit         = src.decodeHDCDto24bit;

            oneInstance     = src.oneInstance;
            checkForUpdates = src.checkForUpdates;

            writeBasicTagsFromCUEData = src.writeBasicTagsFromCUEData;
            copyBasicTags             = src.copyBasicTags;
            copyUnknownTags           = src.copyUnknownTags;
            CopyAlbumArt    = src.CopyAlbumArt;
            embedAlbumArt   = src.embedAlbumArt;
            extractAlbumArt = src.extractAlbumArt;
            maxAlbumArtSize = src.maxAlbumArtSize;

            arLogToSourceFolder = src.arLogToSourceFolder;
            arLogVerbose        = src.arLogVerbose;
            fixOffsetToNearest  = src.fixOffsetToNearest;
            ArLogFilenameFormat = src.ArLogFilenameFormat;
            AlArtFilenameFormat = src.AlArtFilenameFormat;

            separateDecodingThread = src.separateDecodingThread;

            gapsHandling = src.gapsHandling;

            advanced = new CUEConfigAdvanced(src.advanced);

            language = src.language;

            scripts = new Dictionary <string, CUEToolsScript>();
            scripts.Add("default", new CUEToolsScript("default",
                                                      new CUEAction[] { CUEAction.Verify, CUEAction.Encode }));
            scripts.Add("only if found", new CUEToolsScript("only if found",
                                                            new CUEAction[] { CUEAction.Verify }));
            scripts.Add("fix offset", new CUEToolsScript("fix offset",
                                                         new CUEAction[] { CUEAction.Encode }));
            scripts.Add("encode if verified", new CUEToolsScript("encode if verified",
                                                                 new CUEAction[] { CUEAction.Encode }));
            scripts.Add("repair", new CUEToolsScript("repair",
                                                     new CUEAction[] { CUEAction.Encode }));

            defaultVerifyScript = src.defaultVerifyScript;
            defaultEncodeScript = src.defaultEncodeScript;
        }
Пример #24
0
        public static string GenerateUniqueOutputPath(CUEConfig _config, string format, string ext, CUEAction action, NameValueCollection vars, string pathIn, CUESheet cueSheet)
        {
            if (pathIn == "" || (pathIn == null && action != CUEAction.Encode) || (pathIn != null && !IsCDROM(pathIn) && !File.Exists(pathIn) && !Directory.Exists(pathIn)))
                return String.Empty;
            if (action == CUEAction.Verify && _config.arLogToSourceFolder)
                return Path.ChangeExtension(pathIn, ".cue");
            if (action == CUEAction.CreateDummyCUE)
                return Path.ChangeExtension(pathIn, ".cue");
            if (action == CUEAction.CorrectFilenames)
                return pathIn;

            if (_config.detectHDCD && _config.decodeHDCD && (!ext.StartsWith(".lossy.") || !_config.decodeHDCDtoLW16))
            {
                if (_config.decodeHDCDto24bit)
                    ext = ".24bit" + ext;
                else
                    ext = ".20bit" + ext;
            }

            if (pathIn != null)
            {
                vars.Add("path", pathIn);
                try
                {
                    vars.Add("filename", Path.GetFileNameWithoutExtension(pathIn));
                    vars.Add("filename_ext", Path.GetFileName(pathIn));
                    vars.Add("directoryname", General.EmptyStringToNull(Path.GetDirectoryName(pathIn)));
                }
                catch { }
            }
            vars.Add("music", Environment.GetFolderPath(Environment.SpecialFolder.MyMusic));
            string artist = cueSheet == null ? "Artist" : cueSheet.Metadata.Artist == "" ? "Unknown Artist" : cueSheet.Metadata.Artist;
            string album = cueSheet == null ? "Album" : cueSheet.Metadata.Title == "" ? "Unknown Title" : cueSheet.Metadata.Title;
            vars.Add("artist", General.EmptyStringToNull(_config.CleanseString(artist)));
            vars.Add("album", General.EmptyStringToNull(_config.CleanseString(album)));

            if (cueSheet != null)
            {
                vars.Add("year", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.Year)));
                vars.Add("barcode", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.Barcode)));
                vars.Add("label", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.Label)));
                vars.Add("labelno", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.LabelNo)));
                vars.Add("labelandnumber", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.LabelAndNumber)));
                vars.Add("country", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.Country)));
                vars.Add("releasedate", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.ReleaseDate)));
                vars.Add("discname", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.DiscName)));
                vars.Add("discnumber", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.DiscNumber01)));
                vars.Add("totaldiscs", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.TotalDiscs)));
                vars.Add("releasedateandlabel", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.ReleaseDateAndLabel)));
                vars.Add("discnumberandname", General.EmptyStringToNull(_config.CleanseString(cueSheet.Metadata.DiscNumberAndName.Replace("/", " of "))));
                NameValueCollection tags = cueSheet.Tags;
                if (tags != null)
                    foreach (string tag in tags.AllKeys)
                    {
                        string key = tag.ToLower();
                        string val = tags[tag];
                        if (vars.Get(key) == null && val != null && val != "")
                            vars.Add(key, _config.CleanseString(val));
                    }
            }

            vars.Add("unique", null);

            string outputPath = "";
            for (int maxLen = 255; maxLen >= 8; maxLen--)
            {
                outputPath = General.ReplaceMultiple(format, vars, "unique", pathOut => File.Exists(Path.ChangeExtension(pathOut, ext)), maxLen);
                if (outputPath == "" || outputPath == null)
                    return "";
                try { outputPath = Path.ChangeExtension(outputPath, ext); }
                catch { return ""; }
                if (outputPath.Length < 255)
                    return outputPath;
            }
            return outputPath;
        }
Пример #25
0
		static void Main(string[] args)
		{
			TextWriter stdout = Console.Out;
			Console.SetOut(Console.Error);
			Console.WriteLine("CUETools.Converter, Copyright (C) 2009 Grigory Chudov.");
			Console.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to");
			Console.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details.");
			if (args.Length < 2)
			{
				Usage();
				return;
			}
			string sourceFile = args[0];
			string destFile = args[1];

			DateTime start = DateTime.Now;
			TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
			CUEConfig config = new CUEConfig();

			SettingsReader sr = new SettingsReader("CUE Tools", "settings.txt", null);
			config.Load(sr);
#if !DEBUG
			try
#endif
			{
				IAudioSource audioSource = AudioReadWrite.GetAudioSource(sourceFile, null, config);
				IAudioDest audioDest = AudioReadWrite.GetAudioDest(AudioEncoderType.Lossless, destFile, (long)audioSource.Length, audioSource.PCM.BitsPerSample, audioSource.PCM.SampleRate, 8192, config);
				AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);

				Console.WriteLine("Filename  : {0}", sourceFile);
				Console.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, TimeSpan.FromSeconds(audioSource.Length * 1.0 / audioSource.PCM.SampleRate));

				while (audioSource.Read(buff, -1) != 0)
				{
					audioDest.Write(buff);
					TimeSpan elapsed = DateTime.Now - start;
					if ((elapsed - lastPrint).TotalMilliseconds > 60)
					{
						Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
							100.0 * audioSource.Position / audioSource.Length,
							audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
							elapsed,
							TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * audioSource.Length)
							);
						lastPrint = elapsed;
					}
				}

				TimeSpan totalElapsed = DateTime.Now - start;
				Console.Error.Write("\r                                                                         \r");
				Console.WriteLine("Results   : {0:0.00}x; {1}",
					audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
					totalElapsed
					);
				audioSource.Close();
				audioDest.Close();

				TagLib.UserDefined.AdditionalFileTypes.Config = config;
				TagLib.File sourceInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(sourceFile));
				TagLib.File destInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(destFile));
				if (Tagging.UpdateTags(destInfo, Tagging.Analyze(sourceInfo), config))
				{
					sourceInfo.Tag.CopyTo(destInfo.Tag, true);
					destInfo.Tag.Pictures = sourceInfo.Tag.Pictures;
					destInfo.Save();
				}
			}
#if !DEBUG
			catch (Exception ex)
			{
				Console.WriteLine();
				Console.WriteLine("Error: {0}", ex.Message);
				//Console.WriteLine("{0}", ex.StackTrace);
			}
#endif
		}
Пример #26
0
        public static IAudioSource GetAudioSource(string path, Stream IO, CUEConfig config)
        {
            string extension = Path.GetExtension(path).ToLower();

            return(GetAudioSource(path, IO, extension, config));
        }
Пример #27
0
 public CUERipperSettings(CUEConfig config)
 {
     this.config = config;
 }
Пример #28
0
 public Options(CUEConfig config)
 {
     this.config = config;
     this.InitializeComponent();
 }
Пример #29
0
        public static string CreateDummyCUESheet(CUEConfig _config, FileGroupInfo fileGroup)
        {
            if (fileGroup.type == FileGroupInfoType.FileWithCUE)
            {
                TagLib.UserDefined.AdditionalFileTypes.Config = _config;
                TagLib.File.IFileAbstraction fileAbsraction = new TagLib.File.LocalFileAbstraction(fileGroup.main.FullName);
                TagLib.File fileInfo = TagLib.File.Create(fileAbsraction);
                return Tagging.Analyze(fileInfo).Get("CUESHEET");
            }

            StringWriter sw = new StringWriter();
            sw.WriteLine(String.Format("REM COMMENT \"CUETools generated dummy CUE sheet\""));
            int trackNo = 0;
            foreach (FileSystemInfo file in fileGroup.files)
            {
                string name = file.Name;
                if (fileGroup.type == FileGroupInfoType.M3UFile
                    && Path.GetDirectoryName(file.FullName) != Path.GetDirectoryName(fileGroup.main.FullName)
                    && Path.GetDirectoryName(file.FullName).StartsWith(Path.GetDirectoryName(fileGroup.main.FullName)))
                {
                    name = file.FullName.Substring(Path.GetDirectoryName(fileGroup.main.FullName).Length + 1);
                }
                sw.WriteLine(String.Format("FILE \"{0}\" WAVE", name));
                sw.WriteLine(String.Format("  TRACK {0:00} AUDIO", ++trackNo));
                sw.WriteLine(String.Format("    INDEX 01 00:00:00"));
            }
            sw.Close();
            return sw.ToString();
        }
Пример #30
0
        public static IAudioSource GetAudioSource(string path, Stream IO, string extension, CUEConfig config)
        {
            if (extension == ".dummy")
            {
                using (StreamReader sr = (IO == null ? new StreamReader(path) : new StreamReader(IO))) {
                    string slen = sr.ReadLine();
                    long   len;
                    if (!long.TryParse(slen, out len))
                    {
                        len = CDImageLayout.TimeFromString(slen) * 588;
                    }
                    return(new Codecs.NULL.AudioDecoder(len));
                }
            }
            if (extension == ".bin")
            {
                return(new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings(), path, IO, AudioPCMConfig.RedBook));
            }
            CUEToolsFormat fmt;

            if (!extension.StartsWith(".") || !config.formats.TryGetValue(extension.Substring(1), out fmt))
            {
                throw new Exception("Unsupported audio type: " + path);
            }
            if (fmt.decoder == null)
            {
                throw new Exception("Unsupported audio type: " + path);
            }
            var settings = fmt.decoder.Settings.Clone();

            try
            {
                object src = Activator.CreateInstance(fmt.decoder.Settings.DecoderType, settings, path, IO);
                if (src == null || !(src is IAudioSource))
                {
                    throw new Exception("Unsupported audio type: " + path + ": " + fmt.decoder.Settings.DecoderType.FullName);
                }
                return(src as IAudioSource);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                if (ex.InnerException == null)
                {
                    throw ex;
                }
                throw ex.InnerException;
            }
        }