public void OpenCDExtra()
		{
			// test playstation-type CD-Extra
			CUESheet target = new CUESheet(new CUEConfig());
			target.Open("Circuitry\\1.cue");
			Assert.AreEqual<string>("-0:37001:70001:99814:126819:160976", target.TOC.ToString(), "Wrong TOC");

			// test playstation-type CD-Extra with nonstandard pregap
			target = new CUESheet(new CUEConfig());
			target.Open("Headcandy\\Headcandy.cue");
			Assert.AreEqual<string>("-0:141942:168581:223645:248699:279575:312824", target.TOC.ToString(), "Wrong TOC");

			// test playstation-type CD-Extra with no info in cuesheet
			target = new CUESheet(new CUEConfig());
			target.Open("Anatomy\\Anatomy.cue");
			Assert.AreEqual<string>("-0:19687:33144:50680:69872:89822:108084:132098:150625:166271:194882:200172:215884:236046:242815:269518:282018:293416", target.TOC.ToString(), "Wrong TOC");

			// test playstation-type CD-Extra with two data tracks
			target = new CUESheet(new CUEConfig());
			target.Open("Les Mysterieuses Cites d'Or\\Les Mysterieuses Cites d'Or.cue");
			Assert.AreEqual<string>("-0:-31952:127883:137816:149173:160223:171479:180777:186738:196134:205613:214526:221674:227031:232824:239376:249495:259604:266115:267080:275100:281599:284452:291422:295511:297642:302114:309263:312269:320051:326235:333841", target.TOC.ToString(), "Wrong TOC");

			// test playstation-type CD-Extra with two data tracks and no info in cuesheet
			target = new CUESheet(new CUEConfig());
			target.Open("Les Mysterieuses Cites d'Or\\2.cue");
			Assert.AreEqual<string>("-0:-31952:127883:137816:149173:160223:171479:180777:186738:196134:205613:214526:221674:227031:232824:239376:249495:259604:266115:267080:275100:281599:284452:291422:295511:297642:302114:309263:312269:320051:326235:333841", target.TOC.ToString(), "Wrong TOC");
		}
 public static string GetAccurateRipLog(CUESheet sheet)
 {
     using (StringWriter stringWriter = new StringWriter())
     {
         WriteAccurateRipLog(sheet, stringWriter);
         return stringWriter.ToString();
     }
 }
 public CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar)
     : this(cueSheet, start, end, ar, null)
 {
     if (cueSheet.Config.detectHDCD && CUEProcessorPlugins.hdcd != null)
     {
         try { this.hdcd = Activator.CreateInstance(CUEProcessorPlugins.hdcd, 2, 44100, 20, false) as IAudioDest; }
         catch { this.hdcd = null; }
     }
 }
 public CUESheetAudio(CUESheet cueSheet)
 {
     this.cueSheet = cueSheet;
     this.currentAudio = null;
     this._samplePos = 0;
     this._sampleLen = 0;
     this.currentSource = -1;
     this.nextPos = 0;
     cueSheet._sources.ForEach(s => this._sampleLen += s.Length);
 }
 private CUEToolsVerifyTask(CUESheet cueSheet, int start, int end, AccurateRipVerify ar, IAudioDest hdcd)
 {
     this.cueSheet = cueSheet;
     this.start = start;
     this.end = end;
     this.source = new CUESheetAudio(cueSheet);
     if (cueSheet.IsCD || cueSheet.Config.separateDecodingThread)
         this.source = new AudioPipe(this.source, 0x10000);
     this.source.Position = start;
     this.ar = cueSheet.IsUsingAccurateRip ? ar : null;
     this.hdcd = hdcd;
     if (this.ar != null)
         this.ar.Position = start;
 }
 public static string GetTOCContents(CUESheet sheet)
 {
     StringWriter sw = new StringWriter();
     sw.WriteLine("     Track |   Start  |  Length  | Start sector | End sector ");
     sw.WriteLine("    ---------------------------------------------------------");
     for (int track = 1; track <= sheet.TOC.TrackCount; track++)
     {
         sw.WriteLine("{0,9}  | {1,8} | {2,8} |  {3,8}    | {4,8}   ",
             track, // sheet.TOC[track].Number,
             CDImageLayout.TimeToString("{0,2}:{1:00}.{2:00}", sheet.TOC[track].Start),
             CDImageLayout.TimeToString("{0,2}:{1:00}.{2:00}", sheet.TOC[track].Length),
             sheet.TOC[track].Start,
             sheet.TOC[track].End);
     }
     return sw.ToString();
 }
示例#7
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);
        }
        public static void WriteAccurateRipLog(CUESheet sheet, TextWriter writer)
        {
            writer.WriteLine("[CUETools log; Date: {0}; Version: {1}]", DateTime.Now, CUESheet.CUEToolsVersion);
            if (sheet.PreGapLength != 0)
                writer.WriteLine("Pregap length {0}.", sheet.PreGapLengthMSF);
            if (!sheet.TOC[1].IsAudio)
                writer.WriteLine("Playstation type data track length {0}.", sheet.TOC[sheet.TOC.FirstAudio].StartMSF);
            if (!sheet.TOC[sheet.TOC.TrackCount].IsAudio)
                writer.WriteLine("CD-Extra data track length {0}.",
                    sheet.TOC[sheet.TOC.TrackCount].Length == 0 && sheet.MinDataTrackLength.HasValue ?
                        CDImageLayout.TimeToString(sheet.MinDataTrackLength.Value) + " - " + CDImageLayout.TimeToString(sheet.MinDataTrackLength.Value + 74) :
                        sheet.TOC[sheet.TOC.TrackCount].LengthMSF);
            if (sheet.CDDBDiscIdTag != null && AccurateRipVerify.CalculateCDDBId(sheet.TOC).ToUpper() != sheet.CDDBDiscIdTag.ToUpper() && !sheet.MinDataTrackLength.HasValue)
                writer.WriteLine("CDDBId mismatch: {0} vs {1}", sheet.CDDBDiscIdTag.ToUpper(), AccurateRipVerify.CalculateCDDBId(sheet.TOC).ToUpper());
            if (sheet.AccurateRipId != null && AccurateRipVerify.CalculateAccurateRipId(sheet.TOC) != sheet.AccurateRipId)
                writer.WriteLine("Using preserved id, actual id is {0}.", AccurateRipVerify.CalculateAccurateRipId(sheet.TOC));
            if (sheet.Truncated4608)
                writer.WriteLine("Truncated 4608 extra samples in some input files.");
            if (sheet.PaddedToFrame)
                writer.WriteLine("Padded some input files to a frame boundary.");

            if (!sheet.Processed)
            {
                if (sheet.IsUsingCUEToolsDB) sheet.GenerateCTDBLog(writer);
                writer.WriteLine("[AccurateRip ID: {0}] {1}.", sheet.AccurateRipId ?? AccurateRipVerify.CalculateAccurateRipId(sheet.TOC), sheet.ArVerify.ARStatus ?? "found");
                return;
            }

            if (sheet.HDCDDecoder != null && string.Format("{0:s}", sheet.HDCDDecoder) != "")
                writer.WriteLine("HDCD: {0:f}", sheet.HDCDDecoder);
            if (0 != sheet.WriteOffset)
                writer.WriteLine("Offset applied: {0}", sheet.WriteOffset);
            if (sheet.IsUsingCUEToolsDBFix)// && _CUEToolsDB.SelectedEntry != null)
                writer.WriteLine("CUETools DB: corrected {0} errors.", sheet.CTDB.SelectedEntry.repair.CorrectableErrors);
            else if (sheet.IsUsingCUEToolsDB)
                sheet.GenerateCTDBLog(writer);
            sheet.ArVerify.GenerateFullLog(writer, sheet.Config.arLogVerbose, sheet.AccurateRipId ?? AccurateRipVerify.CalculateAccurateRipId(sheet.TOC));
        }
示例#9
0
 private void backgroundWorkerAddToLocalDB_DoWork(object sender, DoWorkEventArgs e)
 {
     var folder = e.Argument as string;
     CUESheet cueSheet = new CUESheet(_profile._config);
     cueSheet.CUEToolsProgress += new EventHandler<CUEToolsProgressEventArgs>(SetStatus);
     cueSheet.UseLocalDB(_localDB);
     _workThread = null;
     _workClass = cueSheet;
     cueSheet.ScanLocalDB(folder);
 }
示例#10
0
 private void editMetadataToolStripMenuItem_Click(object sender, EventArgs e)
 {
     var node = contextMenuStripFileTree.Tag as CUEControls.FileSystemTreeNode;
     string path = null;
     if (node != null && node is FileSystemTreeNodeLocalDBEntry)
         path = node.Path;
     if (node != null && node is FileSystemTreeNodeLocalDBCollision)
         path = (node as FileSystemTreeNodeLocalDBCollision).Group[0].Path;
     if (path == null)
         return;
     var CueSheet = new CUESheet(_profile._config);
     CueSheet.PasswordRequired += new EventHandler<CompressionPasswordRequiredEventArgs>(PasswordRequired);
     CueSheet.CUEToolsProgress += new EventHandler<CUEToolsProgressEventArgs>(SetStatus);
     //cueSheet.CUEToolsSelection += new EventHandler<CUEToolsSelectionEventArgs>(MakeSelection);
     try
     {
         CueSheet.Open(path);
     }
     catch (Exception ex)
     {
         ShowErrorMessage(ex);
         return;
     }
     CueSheet.UseLocalDB(_localDB);
     frmChoice dlg = new frmChoice();
     if (_choiceWidth != 0 && _choiceHeight != 0)
         dlg.Size = new Size(_choiceWidth, _choiceHeight);
     if (_choiceMaxed)
         dlg.WindowState = FormWindowState.Maximized;
     dlg.CUE = CueSheet;
     dlg.LookupAlbumInfo(true, node is FileSystemTreeNodeLocalDBEntry, true, CTDBMetadataSearch.Default);
     var dlgRes = dlg.ShowDialog(this);
     _choiceMaxed = dlg.WindowState == FormWindowState.Maximized;
     if (!_choiceMaxed)
     {
         _choiceHeight = dlg.Height;
         _choiceWidth = dlg.Width;
     }
     if (dlgRes == DialogResult.OK && dlg.ChosenRelease != null)
     {
         if (node is FileSystemTreeNodeLocalDBCollision)
         {
             var group = (node as FileSystemTreeNodeLocalDBCollision).Group;
             foreach (var item in group)
                 item.Metadata.CopyMetadata(dlg.ChosenRelease.metadata);
         }
         else if (node is FileSystemTreeNodeLocalDBEntry)
         {
             var item = (node as FileSystemTreeNodeLocalDBEntry).Item;
             item.Metadata.CopyMetadata(dlg.ChosenRelease.metadata);
         }
         node.Text = node.DisplayName;
         _localDB.Dirty = true;
         SaveDatabase();
     }
     CueSheet.Close();
 }
示例#11
0
        private void UpdateOutputPath(string pathIn, CUESheet cueSheet)
        {
            if (!OutputPathUseTemplate)
            {
                txtOutputPath.ReadOnly = false;
                comboBoxOutputFormat.Enabled = false;
            }
            else
            {
                txtOutputPath.ReadOnly = true;
                comboBoxOutputFormat.Enabled =
                    SelectedAction != CUEAction.CorrectFilenames &&
                    SelectedAction != CUEAction.CreateDummyCUE &&
                    (SelectedAction != CUEAction.Verify || !_profile._config.arLogToSourceFolder);

                txtOutputPath.Text = CUESheet.GenerateUniqueOutputPath(
                    _profile._config,
                    comboBoxOutputFormat.Text,
                    SelectedCUEStyle == CUEStyle.SingleFileWithCUE ? "." + SelectedOutputAudioFormat : ".cue",
                    SelectedAction,
                    new NameValueCollection(),
                    pathIn,
                    cueSheet);
            }
        }
示例#12
0
		public void StartConvert()
		{
			try
			{
				CUESheet cueSheet = new CUESheet(_profile._config);
				cueSheet.PasswordRequired += new EventHandler<CompressionPasswordRequiredEventArgs>(PasswordRequired);
				cueSheet.CUEToolsProgress += new EventHandler<CUEToolsProgressEventArgs>(SetStatus);

				_workThread = new Thread(WriteAudioFilesThread);
				_workClass = cueSheet;
				_workThread.Priority = ThreadPriority.BelowNormal;
				_workThread.IsBackground = true;
				_workThread.Start(cueSheet);
			}
			catch (Exception ex)
			{
				Text = "Error: " + ex.Message;
				textBox1.Show();
				textBox1.Text += "Error: " + ex.Message + "\r\n";
				textBox1.Text += "----------------------------------------------------------\r\n";
				textBox1.Select(0, 0);
			}
		}
示例#13
0
		private void UpdateOutputPath()
		{
			if (selectedFormat == null) return;
			if (data.selectedRelease == null)
			{
				txtOutputPath.Text = "";
				return;
			}
			CUEStyle style = bnComboBoxImage.SelectedIndex == 0 ? CUEStyle.SingleFileWithCUE : CUEStyle.GapsAppended;
			CUESheet sheet = new CUESheet(_config);
			sheet.TOC = selectedDriveInfo.drive.TOC;
			sheet.CopyMetadata(data.selectedRelease.metadata);
			txtOutputPath.Text = sheet.GenerateUniqueOutputPath(bnComboBoxOutputFormat.Text,
					style == CUEStyle.SingleFileWithCUE ? "." + selectedFormat.ToString() : ".cue", CUEAction.Encode, null);
		}
示例#14
0
        private void Lookup(object o)
        {
            ICDRipper audioSource = o as ICDRipper;
            int mbresults_count = 0; // have to cache results.Count, because it sometimes hangs in it, and we don't want UI thread to hang.
            string musicbrainzError = "";

            data.Releases.RaiseListChangedEvents = false;

            cueSheet = new CUESheet(_config);
            cueSheet.OpenCD(audioSource);
            cueSheet.Action = CUEAction.Encode;

            this.BeginInvoke((MethodInvoker)delegate() { toolStripStatusLabel1.Text = Properties.Resources.LookingUpVia + " CTDB..."; });
            cueSheet.UseCUEToolsDB("CUERipper " + CUESheet.CUEToolsVersion, selectedDriveInfo.drive.ARName, false, loadAllMetadata ? CTDBMetadataSearch.Extensive : _config.advanced.metadataSearch);
            cueSheet.CTDB.UploadHelper.onProgress += new EventHandler<Krystalware.UploadHelper.UploadProgressEventArgs>(UploadProgress);
            this.BeginInvoke((MethodInvoker)delegate() { toolStripStatusLabel1.Text = Properties.Resources.LookingUpVia + " AccurateRip..."; });
            cueSheet.UseAccurateRip();

            General.SetCUELine(cueSheet.Attributes, "REM", "DISCID", AccurateRipVerify.CalculateCDDBId(audioSource.TOC), false);

            try
            {
                CUEMetadata cache = CUEMetadata.Load(audioSource.TOC.TOCID);
                if (cache != null)
                    data.Releases.Add(new CUEMetadataEntry(cache, audioSource.TOC, "local"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }

            foreach (var ctdbMeta in cueSheet.CTDB.Metadata)
            {
                data.Releases.Add(CreateCUESheet(audioSource, ctdbMeta));
            }

            if (data.Releases.Count == 0 || loadAllMetadata)
            {
                loadAllMetadata = false;

                //this.BeginInvoke((MethodInvoker)delegate() { toolStripStatusLabel1.Text = Properties.Resources.LookingUpVia + " MusicBrainz..."; });

                //ReleaseQueryParameters p = new ReleaseQueryParameters();
                //p.DiscId = audioSource.TOC.MusicBrainzId;
                //Query<Release> results = Release.Query(p);
                //MusicBrainzService.Proxy = _config.GetProxy();
                //MusicBrainzService.XmlRequest += new EventHandler<XmlRequestEventArgs>(MusicBrainz_LookupProgress);

                //try
                //{
                //    foreach (Release release in results)
                //    {
                //        release.GetEvents();
                //        release.GetTracks();
                //        data.Releases.Add(CreateCUESheet(audioSource, release));
                //    }
                //    mbresults_count = results.Count;
                //}
                //catch (Exception ex)
                //{
                //    System.Diagnostics.Trace.WriteLine(ex.Message);
                //    if (!(ex is MusicBrainzNotFoundException))
                //        musicbrainzError = ex.Message;
                //}
                //MusicBrainzService.Proxy = null;
                //MusicBrainzService.XmlRequest -= new EventHandler<XmlRequestEventArgs>(MusicBrainz_LookupProgress);

                this.BeginInvoke((MethodInvoker)delegate() { toolStripStatusLabel1.Text = Properties.Resources.LookingUpVia + " Freedb..."; });

                FreedbHelper m_freedb = new FreedbHelper();
                m_freedb.Proxy = _config.GetProxy();
                m_freedb.UserName = _config.advanced.FreedbUser;
                m_freedb.Hostname = _config.advanced.FreedbDomain;
                m_freedb.ClientName = "CUERipper";
                m_freedb.Version = CUESheet.CUEToolsVersion;
                m_freedb.SetDefaultSiteAddress(Properties.Settings.Default.MAIN_FREEDB_SITEADDRESS);

                QueryResult queryResult;
                QueryResultCollection coll;
                string code = string.Empty;
                try
                {
                    FreeDB_LookupProgress(this);
                    code = m_freedb.Query(AccurateRipVerify.CalculateCDDBQuery(audioSource.TOC), out queryResult, out coll);
                    if (code == FreedbHelper.ResponseCodes.CODE_200)
                    {
                        bool duplicate = false;
                        foreach (var ctdbMeta in cueSheet.CTDB.Metadata)
                            if (ctdbMeta.source == "freedb" && ctdbMeta.id == queryResult.Category + "/" + queryResult.Discid)
                                duplicate = true;
                        if (!duplicate)
                        {
                            FreeDB_LookupProgress(queryResult.Category + "/" + queryResult.Discid);
                            CDEntry cdEntry;
                            code = m_freedb.Read(queryResult, out cdEntry);
                            if (code == FreedbHelper.ResponseCodes.CODE_210)
                            {
                                CUEMetadataEntry r = CreateCUESheet(audioSource, cdEntry);
                                data.Releases.Add(r);
                            }
                        }
                    }
                    else
                        if (code == FreedbHelper.ResponseCodes.CODE_210 ||
                            code == FreedbHelper.ResponseCodes.CODE_211)
                        {
                            foreach (QueryResult qr in coll)
                            {
                                bool duplicate = false;
                                foreach (var ctdbMeta in cueSheet.CTDB.Metadata)
                                    if (ctdbMeta.source == "freedb" && ctdbMeta.id == qr.Category + "/" + qr.Discid)
                                        duplicate = true;
                                if (!duplicate)
                                {
                                    CDEntry cdEntry;
                                    FreeDB_LookupProgress(qr.Category + "/" + qr.Discid);
                                    code = m_freedb.Read(qr, out cdEntry);
                                    if (code == FreedbHelper.ResponseCodes.CODE_210)
                                    {
                                        CUEMetadataEntry r = CreateCUESheet(audioSource, cdEntry);
                                        data.Releases.Add(r);
                                    }
                                }
                            }
                        }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
            }

            if (data.Releases.Count == 0)
            {
                data.Releases.Add(CreateCUESheet(audioSource));
            }
            _workThread = null;
            if (musicbrainzError != "")
                musicbrainzError = musicbrainzError + ": ";
            while (backgroundWorkerArtwork.IsBusy)
            {
                Thread.Sleep(100);
            }
            this.BeginInvoke((MethodInvoker)delegate()
            {
                SetupControls();
                data.Releases.RaiseListChangedEvents = true;
                data.Releases.ResetBindings();
                //bnComboBoxRelease.SelectedIndex = 0;
                toolStripStatusAr.Enabled = cueSheet.ArVerify.ARStatus == null;
                toolStripStatusAr.Text = cueSheet.ArVerify.ARStatus == null ? cueSheet.ArVerify.WorstTotal().ToString() : "";
                toolStripStatusAr.ToolTipText = "AccurateRip: " + (cueSheet.ArVerify.ARStatus ?? "found") + ".";
                toolStripStatusCTDB.Enabled = cueSheet.CTDB.DBStatus == null;
                toolStripStatusCTDB.Text = cueSheet.CTDB.DBStatus == null ? cueSheet.CTDB.Total.ToString() : "";
                toolStripStatusCTDB.ToolTipText = "CUETools DB: " + (cueSheet.CTDB.DBStatus ?? "found") + ".";
                toolStripStatusLabelMusicBrainz.Enabled = true;
                toolStripStatusLabelMusicBrainz.BorderStyle = mbresults_count > 0 ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner;
                toolStripStatusLabelMusicBrainz.Text = mbresults_count > 0 ? mbresults_count.ToString() : "";
                toolStripStatusLabelMusicBrainz.ToolTipText = "Musicbrainz: " + (mbresults_count > 0 ? mbresults_count.ToString() + " entries found." : (musicbrainzError + "click to submit."));
                if (_config.advanced.coversSearch != CUEConfigAdvanced.CTDBCoversSearch.None)
                    backgroundWorkerArtwork.RunWorkerAsync(new BackgroundWorkerArtworkArgs() { cueSheet = cueSheet, meta = data.selectedRelease });
            });
        }
示例#15
0
		public void OpenOneTrackCD()
		{
			// test one-track CD
			CUESheet target = new CUESheet(new CUEConfig());
			target.Open("Amarok\\Amarok.cue");
			Assert.AreEqual<string>("00041f6d-00083ece-020e1201", AccurateRipVerify.CalculateAccurateRipId(target.TOC), "Wrong TOC");
		}
示例#16
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;
        }
示例#17
0
		internal void LoadDeck(int row)
		{
			CUEConfig _config = (MdiParent as frmCUEPlayer).Config;
			DataSet1 dataSet = (MdiParent as frmCUEPlayer).DataSet;
			Playlist playlist = (MdiParent as frmCUEPlayer).wndPlaylist;
			string path = dataSet.Playlist[row].path;
			int track = dataSet.Playlist[row].track;

			try
			{
				playingCue = new CUESheet(_config);
				playingCue.Open(path);
				playingSource = new CUESheetAudio(playingCue);
				playingSource.Position = (long)playingCue.TOC[track].Start * 588;
				playingSource = new AudioPipe(playingSource, 0x2000);
				playingStart = playingSource.Position;
				playingFinish = playingStart + (long)playingCue.TOC[track].Length * 588;
				playingRow = row;
				//playlist.List.Items[playingRow].BackColor = Color.AliceBlue;
				needUpdate = true;
				UpdateDeck();
			}
			catch (Exception ex)
			{
				playingStart = playingFinish = 0;
				playingCue = null;
				playingSource = null;
				return;
			}
		}
示例#18
0
        private void StartConvert()
        {
            try
            {
                _workThread = null;
                _workClass = null;
                if (_batchPaths.Count != 0)
                {
                    InputPath = _batchPaths[0];
                    txtInputPath.SelectAll();
                }

                string pathIn = InputPath;
                //if (!File.Exists(pathIn) && !Directory.Exists(pathIn) && !IsCDROM(pathIn))
                //    throw new Exception("Invalid input path.");
                //if (Directory.Exists(pathIn) && !pathIn.EndsWith(new string(Path.DirectorySeparatorChar, 1)))
                //{
                //    pathIn = pathIn + Path.DirectorySeparatorChar;
                //    InputPath = pathIn;
                //}

                CUESheet cueSheet = new CUESheet(_profile._config);
                cueSheet.PasswordRequired += new EventHandler<CompressionPasswordRequiredEventArgs>(PasswordRequired);
                cueSheet.CUEToolsProgress += new EventHandler<CUEToolsProgressEventArgs>(SetStatus);
                cueSheet.CUEToolsSelection += new EventHandler<CUEToolsSelectionEventArgs>(MakeSelection);
                cueSheet.WriteOffset = (int)numericWriteOffset.Value;

                object[] p = new object[7];

                _workThread = new Thread(WriteAudioFilesThread);
                _workClass = cueSheet;

                p[0] = cueSheet;
                p[1] = pathIn;
                p[2] = SelectedCUEStyle;
                p[3] = SelectedAction;
                p[4] = SelectedOutputAudioFormat;
                p[5] = SelectedOutputAudioType;
                p[6] = comboBoxScript.SelectedItem;

                SetupControls(true);
                _workThread.Priority = ThreadPriority.BelowNormal;
                _workThread.IsBackground = true;
                _workThread.Start(p);
            }
            catch (Exception ex)
            {
                if (!ShowErrorMessage(ex))
                    _batchPaths.Clear();
                if ((_workThread == null) && (_batchPaths.Count != 0))
                {
                    _batchPaths.RemoveAt(0);
                    if (_batchPaths.Count == 0)
                    {
                        frmReport reportForm = new frmReport();
                        reportForm.Message = _batchReport.ToString();
                        reportForm.ShowDialog(this);
                        //ShowBatchDoneMessage();
                    }
                    else
                        StartConvert();
                }
            }
        }
        public static string GetRipperLog(CUESheet sheet)
        {
            StringWriter logWriter = new StringWriter(CultureInfo.InvariantCulture);
            logWriter.WriteLine("{0}", sheet.CDRipper.RipperVersion);
            logWriter.WriteLine("Extraction logfile from : {0}", DateTime.Now);
            logWriter.WriteLine("Used drive              : {0}", sheet.CDRipper.ARName);
            logWriter.WriteLine("Read offset correction  : {0}", sheet.CDRipper.DriveOffset);
            logWriter.WriteLine("Read command            : {0}", sheet.CDRipper.CurrentReadCommand);
            logWriter.WriteLine("Secure mode             : {0}", sheet.CDRipper.CorrectionQuality);
            logWriter.WriteLine("Disk length             : {0}", CDImageLayout.TimeToString(sheet.TOC.AudioLength));
            logWriter.WriteLine("AccurateRip             : {0}", sheet.ArVerify.ARStatus == null ? "ok" : sheet.ArVerify.ARStatus);
            if (sheet.HDCDDecoder != null && string.Format("{0:s}", sheet.HDCDDecoder) != "")
                logWriter.WriteLine("HDCD                    : {0:f}", sheet.HDCDDecoder);
            logWriter.WriteLine();
            logWriter.WriteLine("TOC of the extracted CD");
            logWriter.WriteLine();
            logWriter.Write(GetTOCContents(sheet));
            logWriter.WriteLine();
            logWriter.WriteLine("     Track |   Pregap  | Indexes");
            logWriter.WriteLine("    ---------------------------------------------------------");
            for (int track = 1; track <= sheet.TOC.TrackCount; track++)
                logWriter.WriteLine("{0,9}  | {1,8} |    {2,2}",
                    sheet.TOC[track].Number,
                    CDImageLayout.TimeToString(sheet.TOC[track].Pregap + (track == 1 ? 150U : 0U)),
                    sheet.TOC[track].LastIndex);
            logWriter.WriteLine();
            logWriter.WriteLine("Destination files");
            foreach (string path in sheet.DestPaths)
                logWriter.WriteLine("    {0}", path);
            bool wereErrors = sheet.PrintErrors(logWriter, sheet.TOC[sheet.TOC.FirstAudio][0].Start, sheet.TOC.AudioLength);
            if (wereErrors)
            {
                logWriter.WriteLine();
                if (wereErrors)
                    logWriter.WriteLine("There were errors");
                else
                    logWriter.WriteLine("No errors occurred");
            }
            if (sheet.IsUsingCUEToolsDB)
            {
                logWriter.WriteLine();
                sheet.GenerateCTDBLog(logWriter);
            }
            if (sheet.IsUsingAccurateRip)
            {
                logWriter.WriteLine();
                logWriter.WriteLine("AccurateRip summary");
                logWriter.WriteLine();
                sheet.ArVerify.GenerateFullLog(logWriter, true, AccurateRipVerify.CalculateAccurateRipId(sheet.TOC));
            }
            logWriter.WriteLine();
            logWriter.WriteLine("End of status report");
            logWriter.Close();

            return logWriter.ToString();
        }
示例#20
0
		private void listViewTracks_DragDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
				if (files.Length == 1)
				{
					string path = files[0];
					try
					{
						CUESheet cue = new CUESheet(_config);
						cue.Open(path);
						for (int iTrack = 0; iTrack < cue.TrackCount; iTrack++)
						{
							DataSet1.PlaylistRow row = dataSet.Playlist.AddPlaylistRow(
								path,
								cue.Metadata.Artist,
								cue.Metadata.Tracks[iTrack].Title,
								cue.Metadata.Title,
								(int)cue.TOC[cue.TOC.FirstAudio + iTrack].Length / 75,
								iTrack + 1);
							listViewTracks.Items.Add(ToItem(row));
						}
						cue.Close();
						return;
					}
					catch (Exception ex)
					{
						Trace.WriteLine(ex.Message);
					}

					FileInfo fi = new FileInfo(path);
					if (fi.Extension != ".cue")
					{
						DataSet1.PlaylistRow row = dataSet.Playlist.AddPlaylistRow(
							path,
							null, // cue.Artist,
							null, // cue.Tracks[iTrack].Title,
							null, // cue.Title,
							0, // (int)cue.TOC[cue.TOC.FirstAudio + iTrack].Length / 75,
							0);
						listViewTracks.Items.Add(ToItem(row));
					}
				}
			}
		}
 public ArchiveFileAbstraction(CUESheet cueSheet, string file)
 {
     name = file;
     _cueSheet = cueSheet;
 }
示例#22
0
		private void UpdateDrive()
		{
			if (bnComboBoxDrives.SelectedItem as DriveInfo == null)
				return;

			if (selectedDriveInfo != null)
				selectedDriveInfo.drive.Close();

			selectedDriveInfo = bnComboBoxDrives.SelectedItem as DriveInfo;
			defaultDrive = selectedDriveInfo.Path;

			toolStripStatusAr.Enabled = false;
			toolStripStatusAr.Text = "";
			toolStripStatusAr.ToolTipText = "";
			toolStripStatusCTDB.Enabled = false;
			toolStripStatusCTDB.Text = "";
			toolStripStatusCTDB.ToolTipText = "";
			toolStripStatusLabelMusicBrainz.Enabled = false;
			toolStripStatusLabelMusicBrainz.Text = "";
			toolStripStatusLabelMusicBrainz.ToolTipText = "";
			listTracks.Items.Clear();
			data.Releases.Clear();
			data.selectedRelease = null;
            ResetAlbumArt();
            bnComboBoxRelease.Enabled = false;
			bnComboBoxRelease.Text = "";
			if (selectedDriveInfo == null)
			{
				SetupControls();
				return;
			}
			if (cueSheet != null)
			{
				cueSheet.Close();
				cueSheet = null;
			}
			numericWriteOffset.Value = selectedDriveInfo.drive.DriveOffset;
			try
			{
				selectedDriveInfo.drive.Open(selectedDriveInfo.drive.Path[0]);
			}
			catch (Exception ex)
			{
				selectedDriveInfo.drive.Close();
				bnComboBoxRelease.Text = ex.Message;
				SetupControls();
				return;
			}
			// cannot use data.Drives.ResetItem(bnComboBoxDrives.SelectedIndex); - causes recursion
			UpdateRelease();
			_workThread = new Thread(Lookup);
			_workThread.Priority = ThreadPriority.BelowNormal;
			_workThread.IsBackground = true;
			SetupControls();
			_workThread.Start(selectedDriveInfo.drive);
		}
示例#23
0
		private void PlayThread()
		{
			try
			{
				do
				{
					if (playingSource == null)
						writer.Pause();
					else
					{
						if (seekTo >= 0 && playingStart + seekTo < playingFinish)
						{
							playingSource.Position = playingStart + seekTo;
							seekTo = -1;
						}
						if (playingSource.Position == playingFinish || stopNow || seekTo == (int)(playingFinish - playingStart))
						{
							seekTo = -1;
							playingSource.Close();
							playingSource = null;
							if (playingCue != null)
							{
								playingCue.Close();
								playingCue = null;
							}
							playingFinish = 0;
							playingStart = 0;
							playingRow = -1;
							if (stopNow || nextDeck == null || nextDeck.playingSource == null)
							{
								writer.Flush();
								stopNow = false;
								mixer.BufferPlaying(iSource, false);
								needUpdate = true;
								playThread = null;
								return;
							}
							playingSource = nextDeck.playingSource;
							playingCue = nextDeck.playingCue;
							playingStart = nextDeck.playingStart;
							playingFinish = nextDeck.playingFinish;
							playingRow = nextDeck.playingRow;
							needUpdate = true;
							nextDeck.playingSource = null;
							nextDeck.playingCue = null;
							nextDeck.playingStart = 0;
							nextDeck.playingFinish = 0;
							nextDeck.playingRow = -1;
							nextDeck.needUpdate = true;
						}
						if (buff == null || buff.PCM.SampleRate != playingSource.PCM.SampleRate || buff.PCM.ChannelCount != playingSource.PCM.ChannelCount || buff.PCM.BitsPerSample != playingSource.PCM.BitsPerSample)
							buff = new AudioBuffer(playingSource.PCM, 0x2000);
						playingSource.Read(buff, Math.Min(buff.Size, (int)(playingFinish - playingSource.Position)));
						writer.Write(buff);
					}
				} while (true);
			}
			catch (Exception ex)
			{
			}
			if (playingCue != null)
			{
				playingCue.Close();
				playingCue = null;
			}
			if (playingSource != null)
			{
				playingSource.Close();
				playingSource = null;
			}
			playThread = null;
		}
        public static string GetExactAudioCopyLog(CUESheet sheet)
        {
            StringWriter logWriter = new StringWriter(CultureInfo.InvariantCulture);
            string eacHeader = "{7}\r\n" +
                "\r\n" +
                "EAC extraction logfile from {0:d'.' MMMM yyyy', 'H':'mm}\r\n" +
                "\r\n" +
                "{1} / {2}\r\n" +
                "\r\n" +
                "Used drive  : {3}   Adapter: 1  ID: 0\r\n" +
                "\r\n" +
                "Read mode               : {4}\r\n" +
                "Utilize accurate stream : Yes\r\n" +
                "Defeat audio cache      : Yes\r\n" +
                "Make use of C2 pointers : No\r\n" +
                "\r\n" +
                "Read offset correction                      : {5}\r\n" +
                "Overread into Lead-In and Lead-Out          : No\r\n" +
                "Fill up missing offset samples with silence : Yes\r\n" +
                "Delete leading and trailing silent blocks   : No\r\n" +
                "Null samples used in CRC calculations       : Yes\r\n" +
                "Used interface                              : Native Win32 interface for Win NT & 2000\r\n" +
                "{6}" +
                "\r\n" +
                "Used output format : Internal WAV Routines\r\n" +
                "Sample format      : 44.100 Hz; 16 Bit; Stereo\r\n";

            logWriter.WriteLine(eacHeader,
                DateTime.Now,
                sheet.Metadata.Artist, sheet.Metadata.Title,
                sheet.CDRipper.EACName,
                sheet.CDRipper.CorrectionQuality > 0 ? "Secure" : "Burst",
                sheet.CDRipper.DriveOffset,
                (sheet.OutputStyle == CUEStyle.SingleFile || sheet.OutputStyle == CUEStyle.SingleFileWithCUE) ? "" :
                    "Gap handling                                : " +
                    (sheet.CDRipper.GapsDetected ? "Appended to previous track\r\n" : "Not detected, thus appended to previous track\r\n"),
                sheet.CDRipper.RipperVersion); // "Exact Audio Copy V0.99 prebeta 4 from 23. January 2008"

            logWriter.WriteLine();
            logWriter.WriteLine("TOC of the extracted CD");
            logWriter.WriteLine();
            logWriter.Write(GetTOCContents(sheet));
            logWriter.WriteLine();

            bool htoaToFile = ((sheet.OutputStyle == CUEStyle.GapsAppended) && sheet.Config.preserveHTOA &&
                (sheet.TOC.Pregap != 0));
            int accurateTracks = 0, knownTracks = 0;
            bool wereErrors = false;
            if (sheet.OutputStyle != CUEStyle.SingleFile && sheet.OutputStyle != CUEStyle.SingleFileWithCUE)
            {
                logWriter.WriteLine();
                for (int track = 0; track < sheet.TOC.AudioTracks; track++)
                {
                    logWriter.WriteLine("Track {0,2}", track + 1);
                    logWriter.WriteLine();
                    logWriter.WriteLine("     Filename {0}", Path.ChangeExtension(Path.GetFullPath(sheet.DestPaths[track + (htoaToFile ? 1 : 0)]), ".wav"));
                    if (sheet.TOC[track + sheet.TOC.FirstAudio].Pregap > 0 || track + sheet.TOC.FirstAudio == 1)
                    {
                        logWriter.WriteLine();
                        logWriter.WriteLine("     Pre-gap length  0:{0}.{1:00}", CDImageLayout.TimeToString("{0:00}:{1:00}", sheet.TOC[track + sheet.TOC.FirstAudio].Pregap + (track + sheet.TOC.FirstAudio == 1 ? 150U : 0U)), (sheet.TOC[track + sheet.TOC.FirstAudio].Pregap % 75) * 100 / 75);
                    }

                    wereErrors |= sheet.PrintErrors(logWriter, sheet.TOC[track + sheet.TOC.FirstAudio].Start, sheet.TOC[track + sheet.TOC.FirstAudio].Length);

                    logWriter.WriteLine();
                    logWriter.WriteLine("     Peak level {0:F1} %", (sheet.ArVerify.PeakLevel(track + 1) * 1000 / 65534) * 0.1);
                    logWriter.WriteLine("     Track quality 100.0 %");
                    if (sheet.ArTestVerify != null)
                    logWriter.WriteLine("     Test CRC {0:X8}", sheet.ArTestVerify.CRC32(track + 1));
                    logWriter.WriteLine("     Copy CRC {0:X8}", sheet.ArVerify.CRC32(track + 1));
                    if (sheet.ArVerify.Total(track) == 0)
                        logWriter.WriteLine("     Track not present in AccurateRip database");
                    else
                    {
                        knownTracks++;
                        if (sheet.ArVerify.Confidence(track) == 0)
                            logWriter.WriteLine("     Cannot be verified as accurate (confidence {0})  [{1:X8}], AccurateRip returned [{2:X8}]", sheet.ArVerify.Total(track), sheet.ArVerify.CRC(track), sheet.ArVerify.DBCRC(track));
                        else
                        {
                            logWriter.WriteLine("     Accurately ripped (confidence {0})  [{1:X8}]", sheet.ArVerify.Confidence(track), sheet.ArVerify.CRC(track));
                            accurateTracks++;
                        }
                    }
                    logWriter.WriteLine("     Copy OK");
                    logWriter.WriteLine();
                }
            }
            else
            {
                logWriter.WriteLine();
                logWriter.WriteLine("Range status and errors");
                logWriter.WriteLine();
                logWriter.WriteLine("Selected range");
                logWriter.WriteLine();
                logWriter.WriteLine("     Filename {0}", Path.ChangeExtension(Path.GetFullPath(sheet.DestPaths[0]), ".wav"));
                wereErrors = sheet.PrintErrors(logWriter, sheet.TOC[sheet.TOC.FirstAudio][0].Start, sheet.TOC.AudioLength);
                logWriter.WriteLine();
                logWriter.WriteLine("     Peak level {0:F1} %", (sheet.ArVerify.PeakLevel() * 1000 / 65535) * 0.1);
                logWriter.WriteLine("     Range quality 100.0 %");
                if (sheet.ArTestVerify != null)
                logWriter.WriteLine("     Test CRC {0:X8}", sheet.ArTestVerify.CRC32(0));
                logWriter.WriteLine("     Copy CRC {0:X8}", sheet.ArVerify.CRC32(0));
                logWriter.WriteLine("     Copy OK");
                logWriter.WriteLine();
                if (wereErrors)
                    logWriter.WriteLine("There were errors");
                else
                    logWriter.WriteLine("No errors occurred");
                logWriter.WriteLine();
                logWriter.WriteLine();
                logWriter.WriteLine("AccurateRip summary");
                logWriter.WriteLine();
                for (int track = 0; track < sheet.TOC.AudioTracks; track++)
                {
                    if (sheet.ArVerify.Total(track) == 0)
                        logWriter.WriteLine("Track {0,2}  not present in database", track + 1);
                    else
                    {
                        knownTracks++;
                        if (sheet.ArVerify.Confidence(track) == 0)
                            logWriter.WriteLine("Track {3,2}  cannot be verified as accurate (confidence {0})  [{1:X8}], AccurateRip returned [{2:X8}]", sheet.ArVerify.Total(track), sheet.ArVerify.CRC(track), sheet.ArVerify.DBCRC(track), track + 1);
                        else
                        {
                            logWriter.WriteLine("Track {2,2}  accurately ripped (confidence {0})  [{1:X8}]", sheet.ArVerify.Confidence(track), sheet.ArVerify.CRC(track), track + 1);
                            accurateTracks++;
                        }
                    }
                }
            }
            logWriter.WriteLine();
            if (knownTracks == 0)
                logWriter.WriteLine("None of the tracks are present in the AccurateRip database");
            else if (accurateTracks == 0)
            {
                logWriter.WriteLine("No tracks could be verified as accurate");
                logWriter.WriteLine("You may have a different pressing from the one(s) in the database");
            }
            else if (accurateTracks == sheet.TrackCount)
                logWriter.WriteLine("All tracks accurately ripped");
            else
            {
                logWriter.WriteLine("{0,2} track(s) accurately ripped", accurateTracks);
                if (sheet.TrackCount - knownTracks > 0)
                    logWriter.WriteLine("{0,2} track(s) not present in the AccurateRip database", sheet.TrackCount - knownTracks);
                logWriter.WriteLine();
                logWriter.WriteLine("Some tracks could not be verified as accurate");
            }
            logWriter.WriteLine();
            if (sheet.OutputStyle != CUEStyle.SingleFile && sheet.OutputStyle != CUEStyle.SingleFileWithCUE)
            {
                if (wereErrors)
                    logWriter.WriteLine("There were errors");
                else
                    logWriter.WriteLine("No errors occurred");
                logWriter.WriteLine();
            }
            logWriter.WriteLine("End of status report");
            logWriter.Close();

            return logWriter.ToString();
        }
示例#25
0
		private void buttonStop_Click(object sender, EventArgs e)
		{
			if (playThread != null)
			{
				stopNow = true;
				playThread.Join();
			}
			else
			{
				if (playingSource != null)
				{
					playingSource.Close();
					playingSource = null;
				}
				if (playingCue != null)
				{
					playingCue.Close();
					playingCue = null;
				}
				playingFinish = 0;
				playingStart = 0;
				playingRow = -1;
				needUpdate = true;
				UpdateDeck();
			}
		}
 public CUEToolsVerifyTask(CUESheet cueSheet, int start, int end)
     : this(cueSheet, start, end, cueSheet.IsUsingAccurateRip || cueSheet.IsUsingCUEToolsDB ? new AccurateRipVerify(cueSheet.TOC, null) : null, null)
 {
 }
示例#27
0
        public void ScanLocalDB(string folder)
        {
            // Delete missing files
            string norm = CUEToolsLocalDBEntry.NormalizePath(folder);
            if (norm.Length != 0 && norm[norm.Length - 1] != System.IO.Path.DirectorySeparatorChar) norm = norm + System.IO.Path.DirectorySeparatorChar;

            ReportProgress("Checking known files", 0.0);
            int oldi = 0, oldn = _localDB.Count;
            foreach (var item in _localDB.ToArray())
            {
                bool matches = false;
                oldi++;
                if (item.AudioPaths != null)
                {
                    foreach (var f in item.AudioPaths)
                        if (f.StartsWith(norm))
                        {
                            matches = true;
                            CheckStop();
                            if (!File.Exists(f))
                            {
                                _localDB.Remove(item);
                                _localDB.Dirty = true;
                                continue;
                            }
                        }
                }

                if (item.InputPaths != null)
                {
                    foreach (var f in item.InputPaths.ToArray())
                        if (f.StartsWith(norm))
                        {
                            CheckStop();
                            ReportProgress("Checking " + f, (double)oldi / oldn);
                            matches = true;
                            if (!File.Exists(f))
                            {
                                item.InputPaths.Remove(f);
                                _localDB.Dirty = true;
                            }
                            else
                            {
                                var cueSheet = new CUESheet(_config);
                                cueSheet.UseLocalDB(_localDB);
                                try
                                {
                                    cueSheet.Open(f);
                                    List<string> fullAudioPaths = cueSheet._sourcePaths == null ? null : cueSheet._sourcePaths.ConvertAll(p => CUEToolsLocalDBEntry.NormalizePath(p));
                                    if (!item.Equals(cueSheet._toc, fullAudioPaths))
                                    {
                                        item.InputPaths.Remove(f);
                                        _localDB.Dirty = true;
                                    }
                                }
                                catch (Exception)
                                {
                                    item.InputPaths.Remove(f);
                                    _localDB.Dirty = true;
                                }
                                cueSheet.Close();
                            }
                        }

                    if (matches && item.InputPaths.Count == 0)
                    {
                        _localDB.Remove(item);
                        _localDB.Dirty = true;
                        continue;
                    }
                }
            }

            // Add new files
            ReportProgress("Scanning for new files", 0.0);
            var results = new List<string>();

            int n = 2, j = 0;
            foreach (var fmt in _config.formats)
                if (fmt.Value.allowLossless)
                    n++;

            CheckStop();
            ReportProgress("Scanning *.cue", (double)(j++) / n);
            results.AddRange(Directory.GetFiles(folder, "*.cue", SearchOption.AllDirectories));

            CheckStop();
            ReportProgress("Scanning *.m3u", (double)(j++) / n);
            results.AddRange(Directory.GetFiles(folder, "*.m3u", SearchOption.AllDirectories));

            foreach (var fmt in _config.formats)
                if (fmt.Value.allowLossless)
                {
                    CheckStop();
                    ReportProgress("Scanning *." + fmt.Key, (double)(j++) / n);
                    results.AddRange(Directory.GetFiles(folder, "*." + fmt.Key, SearchOption.AllDirectories));
                }

            ReportProgress("Checking new files", 0.0);
            int i = 0;
            foreach (var result in results)
            {
                CheckStop();

                var path = CUEToolsLocalDBEntry.NormalizePath(result);
                var pathextension = Path.GetExtension(path).ToLower();
                bool skip = false;
                if (_localDB.Find(
                        item => item.HasPath(path) ||
                            (item.AudioPaths != null &&
                            item.AudioPaths.Count > 1 &&
                            item.AudioPaths.Contains(path))
                    ) != null)
                    skip = true;
                if (!skip && pathextension == ".m3u")
                {
                    var contents = new List<string>();
                    using (StreamReader m3u = new StreamReader(path))
                    {
                        do
                        {
                            string line = m3u.ReadLine();
                            if (line == null) break;
                            if (line == "" || line[0] == '#') continue;
                            //if (line.IndexOfAny(Path.GetInvalidPathChars()) >= 0) 
                            //    continue;
                            try
                            {
                                string extension = Path.GetExtension(line);
                                CUEToolsFormat fmt1;
                                if (!extension.StartsWith(".") || !_config.formats.TryGetValue(extension.ToLower().Substring(1), out fmt1) || !fmt1.allowLossless)
                                {
                                    skip = true;
                                    break;
                                }
                                string fullpath = CUEToolsLocalDBEntry.NormalizePath(Path.Combine(Path.GetDirectoryName(path), line));
                                if (!File.Exists(fullpath))
                                {
                                    skip = true;
                                    break;
                                }
                                contents.Add(fullpath);
                            }
                            catch
                            {
                                skip = true;
                                break;
                            }
                        } while (!skip);
                    }
                    if (!skip && _localDB.Find(item => item.EqualAudioPaths(contents)) != null)
                        skip = true;
                }
                if (!skip && pathextension != ".cue" && pathextension != ".m3u")
                {
                    if (_localDB.Find(item =>
                            item.AudioPaths != null &&
                            item.AudioPaths.Count == 1 &&
                            item.AudioPaths[0] == path
                        ) != null)
                    {
                        CUEToolsFormat fmt;
                        if (!pathextension.StartsWith(".") || !_config.formats.TryGetValue(pathextension.Substring(1), out fmt) || !fmt.allowLossless || !fmt.allowEmbed)
                            skip = true;
                        else
                        {
                            TagLib.File fileInfo;
                            TagLib.UserDefined.AdditionalFileTypes.Config = _config;
                            TagLib.File.IFileAbstraction file = new TagLib.File.LocalFileAbstraction(path);
                            fileInfo = TagLib.File.Create(file);
                            NameValueCollection tags = Tagging.Analyze(fileInfo);
                            if (tags.Get("CUESHEET") == null)
                                skip = true;
                        }
                    }
                }
                if (skip)
                {
                    ReportProgress("Skipping " + path, (double)(i++) / results.Count);
                }
                else
                {
                    ReportProgress("Checking " + path, (double)(i++) / results.Count);
                    var cueSheet = new CUESheet(_config);
                    cueSheet.UseLocalDB(_localDB);
                    //cueSheet.PasswordRequired += new EventHandler<CompressionPasswordRequiredEventArgs>(PasswordRequired);
                    //cueSheet.CUEToolsProgress += new EventHandler<CUEToolsProgressEventArgs>(SetStatus);
                    //cueSheet.CUEToolsSelection += new EventHandler<CUEToolsSelectionEventArgs>(MakeSelection);
                    try
                    {
                        cueSheet.Open(path);
                        cueSheet.OpenLocalDBEntry();
                    }
                    catch (Exception)
                    {
                    }
                    cueSheet.Close();
                }
            }
            _localDB.Save();
        }
示例#28
0
		public void OpenEnhancedCD()
		{
			// test Enhanced-CD
			CUESheet target = new CUESheet(new CUEConfig());
			target.Open("No Man's Land\\1.cue");
			Assert.AreEqual<string>("0015c42c-00d1e13f-ba0fe50d", AccurateRipVerify.CalculateAccurateRipId(target.TOC), "Wrong TOC");
		}