コード例 #1
0
ファイル: General.cs プロジェクト: androidhacker/DotNetProjs
        //public static CUELine FindCUELine(List<CUELine> list, string [] commands)
        //{
        //    foreach (CUELine line in list)
        //    {
        //        if (line.Params.Count < commands.Length)
        //            continue;
        //        for (int i = 0; i < commands.Length; i++)
        //        {
        //            if (line.Params[i].ToUpper() != commands[i].ToUpper())
        //                break;
        //            if (i == commands.Length - 1)
        //                return line;
        //        }
        //    }
        //    return null;
        //}

        public static void SetCUELine(List<CUELine> list, string command, string value, bool quoted)
        {
            if (value == "")
            {
                General.DelCUELine(list, command);
                return;
            }

            CUELine line = General.FindCUELine(list, command);
            if (line == null)
            {
                line = new CUELine();
                line.Params.Add(command); line.IsQuoted.Add(false);
                line.Params.Add(value); line.IsQuoted.Add(quoted);
                list.Add(line);
            }
            else
            {
                while (line.Params.Count > 1)
                {
                    line.Params.RemoveAt(1);
                    line.IsQuoted.RemoveAt(1);
                }
                line.Params.Add(value); line.IsQuoted.Add(quoted);
            }
        }
コード例 #2
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
        public static CDImageLayout CUE2TOC(string cue, int fileTimeLengthFrames)
        {
            CDImageLayout toc = new CDImageLayout();
            bool seenFirstFileIndex = false;
            int absoluteFileStartTime = 0;
            int trackStart = -1;
            try
            {
                using (TextReader sr = new StringReader(cue))
                {
                    string lineStr;
                    while ((lineStr = sr.ReadLine()) != null)
                    {
                        CUELine line = new CUELine(lineStr);
                        if (line.Params.Count > 0)
                        {
                            string command = line.Params[0].ToUpper();

                            if (command == "TRACK")
                            {
                                if (line.Params[2].ToUpper() != "AUDIO")
                                    return null;
                            }
                            else if (command == "INDEX")
                            {
                                int index = int.Parse(line.Params[1]);
                                int timeRelativeToFileStart = CDImageLayout.TimeFromString(line.Params[2]);
                                if (!seenFirstFileIndex)
                                {
                                    if (timeRelativeToFileStart != 0)
                                        return null;
                                    seenFirstFileIndex = true;
                                }
                                else
                                {
                                    if (timeRelativeToFileStart > fileTimeLengthFrames)
                                        return null;
                                    if (Int32.TryParse(line.Params[1], out index) && index == 1 && trackStart >= 0)
                                        toc.AddTrack(new CDTrack((uint)toc.TrackCount + 1, (uint)trackStart, (uint)(absoluteFileStartTime + timeRelativeToFileStart - trackStart), true, false));
                                }
                                if (index == 1)
                                    trackStart = absoluteFileStartTime + timeRelativeToFileStart;
                            }
                            else if (command == "PREGAP")
                            {
                                if (seenFirstFileIndex)
                                    return null;
                                int pregapLength = CDImageLayout.TimeFromString(line.Params[1]);
                                absoluteFileStartTime += pregapLength;
                            }
                        }
                    }
                    sr.Close();
                }
            }
            catch
            {
                return null;
            }
            toc.AddTrack(new CDTrack((uint)toc.TrackCount + 1, (uint)trackStart, (uint)(absoluteFileStartTime + fileTimeLengthFrames - trackStart), true, false));
            toc[1][0].Start = 0;
            return toc;
        }
コード例 #3
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
 private void WriteLine(TextWriter sw, int level, CUELine line)
 {
     WriteLine(sw, level, line.ToString());
 }
コード例 #4
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
        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();
            }
        }
コード例 #5
0
ファイル: CUESheet.cs プロジェクト: androidhacker/DotNetProjs
        public void OpenCUE(TextReader sr)
        {
            string pathAudio = null;
            string lineStr, command, fileType;
            bool fileIsBinary = false;
            int timeRelativeToFileStart, absoluteFileStartTime = 0;
            int fileTimeLengthSamples = 0, fileTimeLengthFrames = 0, i;
            TagLib.File _trackFileInfo = null;
            bool seenFirstFileIndex = false;
            bool isAudioTrack = true;
            List<IndexInfo> indexes = new List<IndexInfo>();
            IndexInfo indexInfo;
            SourceInfo sourceInfo;
            TrackInfo trackInfo = null;
            int trackNumber = 0;

            using (sr)
            {
                while ((lineStr = sr.ReadLine()) != null)
                {
                    CUELine line = new CUELine(lineStr);
                    if (line.Params.Count > 0)
                    {
                        command = line.Params[0].ToUpper();

                        if (command == "FILE")
                        {
                            fileType = line.Params[2].ToUpper();
                            fileIsBinary = (fileType == "BINARY") || (fileType == "MOTOROLA");
                            if (fileIsBinary)
                            {
                                if (!_hasEmbeddedCUESheet && _sourcePaths.Count == 0)
                                {
                                    try
                                    {
                                        if (_isArchive)
                                            pathAudio = FileLocator.LocateFile(_archiveCUEpath, line.Params[1], _archiveContents);
                                        else
                                            pathAudio = FileLocator.LocateFile(_inputDir, line.Params[1], null);
                                        fileIsBinary = (pathAudio == null);
                                    }
                                    catch { }
                                }
                            }
                            if (!fileIsBinary)
                            {
                                if (_sourcePaths.Count != 0 && !seenFirstFileIndex)
                                    throw new Exception("Double FILE in CUE sheet: \"" + line.Params[1] + "\".");
                                if (!_hasEmbeddedCUESheet)
                                {
                                    if (_isArchive)
                                        pathAudio = FileLocator.LocateFile(_archiveCUEpath, line.Params[1], _archiveContents);
                                    else
                                        pathAudio = FileLocator.LocateFile(_inputDir, line.Params[1], null);
                                }
                                else
                                {
                                    pathAudio = _inputPath;
                                    if (_sourcePaths.Count > 0)
                                        throw new Exception("Extra file in embedded CUE sheet: \"" + line.Params[1] + "\".");
                                }

                                if (pathAudio == null)
                                {
                                    throw new Exception("Unable to locate file \"" + line.Params[1] + "\".");
                                    //fileTimeLengthFrames = 75 * 60 * 70;;
                                    //fileTimeLengthSamples = fileTimeLengthFrames * 588;
                                    //if (_hasEmbeddedCUESheet)
                                    //    _fileInfo = null;
                                    //else
                                    //    _trackFileInfo = null;
                                }
                                else
                                {
                                    // Wierd case: audio file after data track with only index 00 specified.
                                    if (!isAudioTrack && _sourcePaths.Count == 0 && indexes.Count > 0 && indexes[indexes.Count - 1].Index == 0)
                                    {
                                        indexInfo.Track = indexes[indexes.Count - 1].Track;
                                        indexInfo.Index = 1;
                                        indexInfo.Time = indexes[indexes.Count - 1].Time + 150;
                                        indexes.Add(indexInfo);
                                        absoluteFileStartTime += 150;
                                    }

                                    TagLib.File fileInfo;
                                    _sourcePaths.Add(pathAudio);
                                    absoluteFileStartTime += fileTimeLengthFrames;
                                    fileTimeLengthSamples = GetSampleLength(pathAudio, out fileInfo);
                                    if ((fileTimeLengthSamples % 588) == 492 && _config.truncate4608ExtraSamples)
                                    {
                                        _truncated4608 = true;
                                        fileTimeLengthSamples -= 4608;
                                    }
                                    fileTimeLengthFrames = (int)((fileTimeLengthSamples + 587) / 588);
                                    if (_hasEmbeddedCUESheet)
                                        _fileInfo = fileInfo;
                                    else
                                        _trackFileInfo = fileInfo;
                                }
                                seenFirstFileIndex = false;
                            }
                        }
                        else if (command == "TRACK")
                        {
                            isAudioTrack = line.Params[2].ToUpper() == "AUDIO";
                            trackNumber = int.Parse(line.Params[1]);
                            if (trackNumber != _toc.TrackCount + 1)
                                throw new Exception("Invalid track number");
                            // Disabled this check: fails on Headcandy test image
                            //if (isAudioTrack && _sourcePaths.Count == 0)
                            //    throw new Exception("No FILE seen before TRACK");
                            _toc.AddTrack(new CDTrack((uint)trackNumber, 0, 0, isAudioTrack, false));
                            if (isAudioTrack)
                            {
                                trackInfo = new TrackInfo();
                                _tracks.Add(trackInfo);
                            }
                        }
                        else if (command == "INDEX")
                        {
                            timeRelativeToFileStart = CDImageLayout.TimeFromString(line.Params[2]);
                            if (!seenFirstFileIndex)
                            {
                                if (timeRelativeToFileStart != 0)
                                    throw new Exception("First index must start at file beginning.");
                                seenFirstFileIndex = true;
                                if (isAudioTrack)
                                {
                                    if (_tracks.Count > 0 && _trackFileInfo != null)
                                        _tracks[_tracks.Count - 1]._fileInfo = _trackFileInfo;
                                    _trackFileInfo = null;
                                    sourceInfo.Path = pathAudio;
                                    sourceInfo.Offset = 0;
                                    sourceInfo.Length = (uint)fileTimeLengthSamples;
                                    _sources.Add(sourceInfo);
                                    if ((fileTimeLengthSamples % 588) != 0)
                                    {
                                        sourceInfo.Path = null;
                                        sourceInfo.Offset = 0;
                                        sourceInfo.Length = (uint)((fileTimeLengthFrames * 588) - fileTimeLengthSamples);
                                        _sources.Add(sourceInfo);
                                        _paddedToFrame = true;
                                    }
                                }
                            }
                            else
                            {
                                if (fileIsBinary)
                                {
                                    fileTimeLengthFrames = timeRelativeToFileStart + 150;
                                    sourceInfo.Path = null;
                                    sourceInfo.Offset = 0;
                                    sourceInfo.Length = 150 * 588;
                                    _sources.Add(sourceInfo);
                                    //throw new Exception("unexpected BINARY directive");
                                }
                                else
                                {
                                    if (timeRelativeToFileStart > fileTimeLengthFrames)
                                        throw new Exception(string.Format("TRACK {0} INDEX {1} is at {2}, which is past {3} - the end of source file {4}", trackNumber, line.Params[1], CDImageLayout.TimeToString((uint)timeRelativeToFileStart), CDImageLayout.TimeToString((uint)fileTimeLengthFrames), pathAudio));
                                }
                            }
                            indexInfo.Track = trackNumber;
                            indexInfo.Index = Int32.Parse(line.Params[1]);
                            indexInfo.Time = absoluteFileStartTime + timeRelativeToFileStart;
                            indexes.Add(indexInfo);
                        }
                        else if (!isAudioTrack)
                        {
                            // Ignore lines belonging to data tracks
                        }
                        else if (command == "PREGAP")
                        {
                            if (seenFirstFileIndex)
                                throw new Exception("Pregap must occur at the beginning of a file.");
                            int pregapLength = CDImageLayout.TimeFromString(line.Params[1]);
                            indexInfo.Track = trackNumber;
                            indexInfo.Index = 0;
                            indexInfo.Time = absoluteFileStartTime;
                            indexes.Add(indexInfo);
                            sourceInfo.Path = null;
                            sourceInfo.Offset = 0;
                            sourceInfo.Length = (uint)pregapLength * 588;
                            _sources.Add(sourceInfo);
                            absoluteFileStartTime += pregapLength;
                        }
                        else if (command == "POSTGAP")
                        {
                            throw new Exception("POSTGAP command isn't supported.");
                        }
                        //else if ((command == "REM") &&
                        //    (line.Params.Count >= 3) &&
                        //    (line.Params[1].Length >= 10) &&
                        //    (line.Params[1].Substring(0, 10).ToUpper() == "REPLAYGAIN"))
                        //{
                        //    // Remove ReplayGain lines
                        //}
                        else if ((command == "REM") &&
                           (line.Params.Count == 3) &&
                           (line.Params[1].ToUpper() == "ACCURATERIPID"))
                        {
                            _accurateRipId = line.Params[2];
                        }
                        //else if ((command == "REM") &&
                        //   (line.Params.Count == 3) &&
                        //   (line.Params[1].ToUpper() == "SHORTEN"))
                        //{
                        //    fileTimeLengthFrames -= General.TimeFromString(line.Params[2]);
                        //}							
                        //else if ((command == "REM") &&
                        //   (line.Params.Count == 3) &&
                        //   (line.Params[1].ToUpper() == "LENGTHEN"))
                        //{
                        //    fileTimeLengthFrames += General.TimeFromString(line.Params[2]);
                        //}							
                        else
                        {
                            if (trackInfo != null)
                            {
                                trackInfo.Attributes.Add(line);
                            }
                            else
                            {
                                if (line.Params.Count > 2 && !line.IsQuoted[1] &&
                                    (line.Params[0].ToUpper() == "TITLE" || line.Params[0].ToUpper() == "ARTIST" ||
                                    (line.Params[0].ToUpper() == "REM" && (line.Params[1].ToUpper() == "GENRE" || line.Params[1].ToUpper() == "COMMENT") && line.Params.Count > 3 && !line.IsQuoted[2])))
                                {
                                    CUELine modline = new CUELine();
                                    int nParams = line.Params[0].ToUpper() == "REM" ? 2 : 1;
                                    for (int iParam = 0; iParam < nParams; iParam++)
                                    {
                                        modline.Params.Add(line.Params[iParam]);
                                        modline.IsQuoted.Add(false);
                                    }
                                    string s = line.Params[nParams];
                                    for (int iParam = nParams + 1; iParam < line.Params.Count; iParam++)
                                        s += " " + line.Params[iParam];
                                    modline.Params.Add(s);
                                    modline.IsQuoted.Add(true);
                                    line = modline;
                                }
                                _attributes.Add(line);
                            }
                        }
                    }
                }
                sr.Close();
            }

            if (_tracks.Count == 0)
                throw new Exception("File must contain at least one audio track.");

            // Add dummy index 01 for data track
            if (!_toc[_toc.TrackCount].IsAudio && indexes[indexes.Count - 1].Index == 0)
            {
                fileTimeLengthFrames += 152 * 75;
                indexInfo.Track = trackNumber;
                indexInfo.Index = 1;
                indexInfo.Time = absoluteFileStartTime + fileTimeLengthFrames;
                indexes.Add(indexInfo);
            }

            // Add dummy track for calculation purposes
            indexInfo.Track = trackNumber + 1;
            indexInfo.Index = 1;
            indexInfo.Time = absoluteFileStartTime + fileTimeLengthFrames;
            indexes.Add(indexInfo);

            // Calculate the length of each index
            for (i = 0; i < indexes.Count - 1; i++)
            {
                if (indexes[i + 1].Time - indexes[i].Time < 0)
                    throw new Exception("Indexes must be in chronological order.");
                if ((indexes[i + 1].Track != indexes[i].Track || indexes[i + 1].Index != indexes[i].Index + 1) &&
                    (indexes[i + 1].Track != indexes[i].Track + 1 || indexes[i].Index < 1 || indexes[i + 1].Index > 1))
                    throw new Exception("Indexes must be in chronological order.");
                if (indexes[i].Index == 1 && (i == 0 || indexes[i - 1].Index != 0))
                    _toc[indexes[i].Track].AddIndex(new CDTrackIndex(0U, (uint)indexes[i].Time));
                _toc[indexes[i].Track].AddIndex(new CDTrackIndex((uint)indexes[i].Index, (uint)indexes[i].Time));
            }

            // Calculate the length of each track
            for (int iTrack = 1; iTrack <= _toc.TrackCount; iTrack++)
            {
                _toc[iTrack].Start = _toc[iTrack][1].Start;
                _toc[iTrack].Length = iTrack == _toc.TrackCount
                    ? (uint)indexes[indexes.Count - 1].Time - _toc[iTrack].Start
                    : _toc[iTrack + 1].IsAudio
                        ? _toc[iTrack + 1][1].Start - _toc[iTrack].Start
                        : _toc[iTrack + 1][0].Start - _toc[iTrack].Start;

            }

            // Store the audio filenames, generating generic names if necessary
            _hasSingleFilename = _sourcePaths.Count == 1;
            _singleFilename = _hasSingleFilename ? Path.GetFileName(_sourcePaths[0]) :
                "Range.wav";

            _hasHTOAFilename = (_sourcePaths.Count == (TrackCount + 1));
            _htoaFilename = _hasHTOAFilename ? Path.GetFileName(_sourcePaths[0]) : "00.wav";

            _hasTrackFilenames = !_hasEmbeddedCUESheet && !_hasSingleFilename && (_sourcePaths.Count == TrackCount || _hasHTOAFilename);
            for (i = 0; i < TrackCount; i++)
            {
                _trackFilenames.Add(_hasTrackFilenames ? Path.GetFileName(
                    _sourcePaths[i + (_hasHTOAFilename ? 1 : 0)]) : String.Format("{0:00}.wav", i + 1));
            }
            if (!_hasEmbeddedCUESheet && _hasSingleFilename)
            {
                _fileInfo = _tracks[0]._fileInfo;
                _tracks[0]._fileInfo = null;
            }
            taglibMetadata = new CUEMetadata(TOC.TOCID, (int)TOC.AudioTracks);
            taglibMetadata.Artist = GetCommonTag(file => file.Tag.JoinedAlbumArtists) ?? GetCommonTag(file => file.Tag.JoinedPerformers) ?? "";
            taglibMetadata.Title = GetCommonTag(file => file.Tag.Album) ?? "";
            taglibMetadata.Year = GetCommonTag(file => file.Tag.Year != 0 ? file.Tag.Year.ToString() : null) ?? "";
            taglibMetadata.Genre = GetCommonTag(file => file.Tag.JoinedGenres) ?? "";
            taglibMetadata.Comment = GetCommonTag(file => file.Tag.Comment) ?? "";
            taglibMetadata.TotalDiscs = GetCommonTag(file => file.Tag.DiscCount != 0 ? file.Tag.DiscCount.ToString() : null) ?? "";
            taglibMetadata.DiscNumber = GetCommonTag(file => file.Tag.Disc != 0 ? file.Tag.Disc.ToString() : null) ?? "";
			taglibMetadata.ReleaseDate = GetCommonTag(file => file.Tag.ReleaseDate) ?? "";
			taglibMetadata.Country = GetCommonTag(file => file.Tag.MusicBrainzReleaseCountry) ?? "";
			taglibMetadata.Label = GetCommonTag(file => file.Tag.Publisher) ?? "";
			taglibMetadata.LabelNo = GetCommonTag(file => file.Tag.CatalogNo) ?? "";
			taglibMetadata.DiscName = GetCommonTag(file => file.Tag.DiscSubtitle) ?? "";
            for (i = 0; i < TrackCount; i++)
            {
                TrackInfo track = _tracks[i];
                taglibMetadata.Tracks[i].Artist = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.JoinedPerformers :
                    _hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_ARTIST", i + 1))) :
                    null) ?? "";
                taglibMetadata.Tracks[i].Title = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.Title :
                    _hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_TITLE", i + 1))) :
                    null) ?? "";
				taglibMetadata.Tracks[i].Comment = (_hasTrackFilenames && track._fileInfo != null ? track._fileInfo.Tag.Title :
					_hasEmbeddedCUESheet && _fileInfo != null ? Tagging.TagListToSingleValue(Tagging.GetMiscTag(_fileInfo, String.Format("cue_track{0:00}_COMMENT", i + 1))) :
					null) ?? "";
			}

            cueMetadata = new CUEMetadata(TOC.TOCID, (int)TOC.AudioTracks);
            cueMetadata.Artist = General.GetCUELine(_attributes, "PERFORMER");
            cueMetadata.Title = General.GetCUELine(_attributes, "TITLE");
            cueMetadata.Barcode = General.GetCUELine(_attributes, "CATALOG");
            cueMetadata.Year = General.GetCUELine(_attributes, "REM", "DATE");
            cueMetadata.DiscNumber = General.GetCUELine(_attributes, "REM", "DISCNUMBER");
            cueMetadata.TotalDiscs = General.GetCUELine(_attributes, "REM", "TOTALDISCS");
            cueMetadata.Genre = General.GetCUELine(_attributes, "REM", "GENRE");
            cueMetadata.Comment = General.GetCUELine(_attributes, "REM", "COMMENT");
			cueMetadata.ReleaseDate = General.GetCUELine(_attributes, "REM", "RELEASEDATE");
			cueMetadata.Country = General.GetCUELine(_attributes, "REM", "COUNTRY");
			cueMetadata.Label = General.GetCUELine(_attributes, "REM", "LABEL");
			cueMetadata.LabelNo = General.GetCUELine(_attributes, "REM", "CATALOGNUMBER");
			cueMetadata.DiscName = General.GetCUELine(_attributes, "REM", "DISCSUBTITLE");
            for (i = 0; i < Tracks.Count; i++)
            {
                cueMetadata.Tracks[i].Artist = General.GetCUELine(Tracks[i].Attributes, "PERFORMER");
                cueMetadata.Tracks[i].Title = General.GetCUELine(Tracks[i].Attributes, "TITLE");
                cueMetadata.Tracks[i].ISRC = General.GetCUELine(Tracks[i].Attributes, "ISRC");
            }
            // Now, TOC.TOCID might change!!!

            if (_config.fillUpCUE)
            {
                cueMetadata.Merge(taglibMetadata, _config.overwriteCUEData);
                for (i = 0; i < TrackCount; i++)
                {
                    if (cueMetadata.Tracks[i].Title == "" && _hasTrackFilenames)
                        cueMetadata.Tracks[i].Title = Path.GetFileNameWithoutExtension(_trackFilenames[i]).TrimStart(" .-_0123456789".ToCharArray());
                }
            }

            CUELine cddbDiscIdLine = General.FindCUELine(_attributes, "REM", "DISCID");
            _cddbDiscIdTag = cddbDiscIdLine != null && cddbDiscIdLine.Params.Count == 3 ? cddbDiscIdLine.Params[2] : null;
            if (_cddbDiscIdTag == null)
                _cddbDiscIdTag = GetCommonMiscTag("DISCID");

            if (_accurateRipId == null)
                _accurateRipId = GetCommonMiscTag("ACCURATERIPID");

            if (_eacLog == null && _logFiles != null && _logFiles.Count > 0)
            {
                foreach (CUEToolsSourceFile sf in _logFiles)
                {
                    CDImageLayout tocFromLog1 = LogToTocParser.LogToToc(this._toc, sf.contents);
                    if (tocFromLog1 != null && tocFromLog1.TOCID == _toc.TOCID)
                    {
                        if (_eacLog == null)
                            _eacLog = sf.contents;
                        else
                        {
                            _eacLog = null;
                            break;
                        }
                    }
                }
            }

            if (_eacLog == null && _logFiles != null && _logFiles.Count > 0)
            {
                CUEToolsSourceFile selectedLogFile = ChooseFile(_logFiles, _defaultLog, false);
                _eacLog = selectedLogFile != null ? selectedLogFile.contents : null;
            }

            CDImageLayout tocFromLog = _eacLog == null ? null : LogToTocParser.LogToToc(this._toc, _eacLog);

            if (tocFromLog == null)
            {
                string tocPath = Path.ChangeExtension(InputPath, ".toc");
                if (File.Exists(tocPath))
                {
                    tocFromLog = LogToTocParser.LogToToc(this._toc, new StreamReader(tocPath, CUESheet.Encoding).ReadToEnd());
                }
            }

            // use pregaps from log
            if (tocFromLog != null)
            {
                //int srcNo = (int) _toc[_toc.FirstAudio].LastIndex - (PreGapLength == 0 ? 1 : 0);
                if (PreGapLength < tocFromLog.Pregap)
                {
                    PreGapLength = tocFromLog.Pregap;
                    //srcNo ++;
                }
                int trNo;
                for (trNo = 1; trNo < tocFromLog.AudioTracks && trNo < _toc.AudioTracks; trNo++)
                {
                    if (_toc[_toc.FirstAudio + trNo].Pregap < tocFromLog[tocFromLog.FirstAudio + trNo].Pregap)
                        _toc[_toc.FirstAudio + trNo].Pregap = tocFromLog[tocFromLog.FirstAudio + trNo].Pregap;
                }
                //if (_toc[_toc.FirstAudio].Length > tocFromLog[tocFromLog.FirstAudio].Length)
                //{
                //    uint offs = _toc[_toc.FirstAudio].Length - tocFromLog[tocFromLog.FirstAudio].Length;
                //    _toc[_toc.FirstAudio].Length -= offs;

                //    sourceInfo = _sources[srcNo];
                //    sourceInfo.Length -= offs * 588;
                //    _sources[srcNo] = sourceInfo;
                //    for (i = _toc.FirstAudio + 1; i <= _toc.TrackCount; i++)
                //    {
                //        _toc[i].Start -= offs;
                //        for (int j = 0; j <= _toc[i].LastIndex; j++)
                //            if (i != _toc.FirstAudio + 1 || j != 0 || _toc[i][0].Start == _toc[i][1].Start)
                //                _toc[i][j].Start -= offs;
                //    }
                //}
                //for (trNo = 1; trNo < tocFromLog.AudioTracks && trNo < _toc.AudioTracks; trNo++)
                //{
                //    srcNo ++;
                //    if (_toc[_toc.FirstAudio + trNo].Length > tocFromLog[tocFromLog.FirstAudio + trNo].Length)
                //    {
                //        uint offs = _toc[_toc.FirstAudio + trNo].Length - tocFromLog[tocFromLog.FirstAudio + trNo].Length;
                //        _toc[_toc.FirstAudio + trNo].Length -= offs;
                //        sourceInfo = _sources[srcNo];
                //        sourceInfo.Length -= offs * 588;
                //        _sources[srcNo] = sourceInfo;
                //        for (i = _toc.FirstAudio + trNo + 1; i <= _toc.TrackCount; i++)
                //        {
                //            _toc[i].Start -= offs;
                //            for (int j = 0; j <= _toc[i].LastIndex; j++)
                //                if (i != _toc.FirstAudio + trNo + 1 || j != 0 || _toc[i][0].Start == _toc[i][1].Start)
                //                    _toc[i][j].Start -= offs;
                //        }
                //    }
                //}
            }

            // use data track length from log
            if (tocFromLog != null)
            {
                if (tocFromLog.AudioTracks == _toc.AudioTracks
                    && tocFromLog.TrackCount == tocFromLog.AudioTracks + 1
                    && !tocFromLog[tocFromLog.TrackCount].IsAudio)
                {
                    DataTrackLength = tocFromLog[tocFromLog.TrackCount].Length;
                    _toc[_toc.TrackCount].Start = tocFromLog[_toc.TrackCount].Start;
                    _toc[_toc.TrackCount][0].Start = tocFromLog[_toc.TrackCount].Start;
                    _toc[_toc.TrackCount][1].Start = tocFromLog[_toc.TrackCount].Start;
                }
                if (_toc.TrackCount == _toc.AudioTracks
                    && tocFromLog.TrackCount == tocFromLog.AudioTracks
                    && tocFromLog.TrackCount > _toc.TrackCount)
                {
                    int dtracks = tocFromLog.TrackCount - _toc.TrackCount;
                    bool matches = true;
                    for (int iTrack = 1; iTrack <= _toc.TrackCount; iTrack++)
                        if (tocFromLog[iTrack + dtracks].Length != _toc[iTrack].Length)
                            matches = false;
                    if (matches)
                    {
                        for (int iTrack = 1; iTrack <= dtracks; iTrack++)
                        {
                            _toc.InsertTrack(new CDTrack((uint)iTrack, 0, 0, false, false));
                            tocFromLog[iTrack].IsAudio = false;
                        }
                        tocFromLog.FirstAudio += dtracks;
                        tocFromLog.AudioTracks -= (uint)dtracks;
                    }
                }
                if (tocFromLog.AudioTracks == _toc.AudioTracks
                    && tocFromLog.TrackCount == _toc.TrackCount
                    && tocFromLog.FirstAudio == _toc.FirstAudio
                    && tocFromLog.TrackCount == tocFromLog.FirstAudio + tocFromLog.AudioTracks - 1)
                {
                    //DataTrackLength = tocFromLog[1].Length;
                    uint delta = tocFromLog[_toc.FirstAudio].Start - _toc[_toc.FirstAudio].Start;
                    for (int itr = 1; itr < _toc.FirstAudio; itr++)
                    {
                        _toc[itr].Start = tocFromLog[itr].Start;
                        _toc[itr].Length = tocFromLog[itr].Length;
                    }
                    for (int itr = _toc.FirstAudio; itr <= _toc.TrackCount; itr++)
                    {
                        _toc[itr].Start += delta;
                        for (int j = 0; j <= _toc[itr].LastIndex; j++)
                            _toc[itr][j].Start += delta;
                    }
                }
            }

            // use data track length range from cddbId
            if (DataTrackLength == 0 && _cddbDiscIdTag != null)
            {
                uint cddbDiscIdNum;
                if (uint.TryParse(_cddbDiscIdTag, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out cddbDiscIdNum) && (cddbDiscIdNum & 0xff) == _toc.AudioTracks + 1)
                {
                    if (_toc.TrackCount == _toc.AudioTracks)
                        _toc.AddTrack(new CDTrack((uint)_toc.TrackCount + 1, _toc.Length + 152 * 75, 0, false, false));
                    uint lengthFromTag = ((cddbDiscIdNum >> 8) & 0xffff);
                    _minDataTrackLength = (lengthFromTag + _toc[1].Start / 75) * 75 - _toc.Length;
                }
            }

            _arVerify = new AccurateRipVerify(_toc, proxy);

            if (_eacLog != null)
            {
                sr = new StringReader(_eacLog);
                bool isEACLog = false;
                int trNo = 1;
                while ((lineStr = sr.ReadLine()) != null)
                {
                    if (isEACLog && trNo <= TrackCount)
                    {
                        string[] s = { "Copy CRC ", "CRC копии" };
                        string[] s1 = { "CRC" };
                        string[] n = lineStr.Split(s, StringSplitOptions.None);
                        uint crc;
                        if (n.Length == 2 && uint.TryParse(n[1], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out crc))
                            _arVerify.CRCLOG(trNo++, crc);
                        else if (n.Length == 1)
                        {
                            n = lineStr.Split(s1, StringSplitOptions.None);
                            if (n.Length == 2 && n[0].Trim() == "" && uint.TryParse(n[1], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out crc))
                                _arVerify.CRCLOG(trNo++, crc);
                        }
                    }
                    else
                        if (lineStr.StartsWith("Exact Audio Copy")
                            || lineStr.StartsWith("EAC extraction logfile"))
                            isEACLog = true;
                }
                if (trNo == 2)
                {
                    _arVerify.CRCLOG(0, _arVerify.CRCLOG(1));
                    if (TrackCount > 1)
                        _arVerify.CRCLOG(1, 0);
                }
            }

            LoadAlbumArt(_tracks[0]._fileInfo ?? _fileInfo);
            ResizeAlbumArt();
            if (_config.embedAlbumArt || _config.CopyAlbumArt)
                _albumArt.ForEach(t => _padding += _albumArt[0].Data.Count);
            if (_config.embedLog && _eacLog != null)
                _padding += _eacLog.Length;

            cueMetadata.Id = TOC.TOCID;
            taglibMetadata.Id = TOC.TOCID;
            // TODO: It should also be set when assigning a DataTrack!!!
        }
コード例 #6
0
        private void WriteAudioFilesThread(object o)
        {
            object[] p = (object[])o;

            CUESheet cueSheet = (CUESheet)p[0];
            string pathIn = (string)p[1];
            CUEStyle cueStyle = (CUEStyle)p[2];
            CUEAction action = (CUEAction)p[3];
            string outputFormat = (string)p[4];
            AudioEncoderType audioEncoderType = (AudioEncoderType)p[5];
            CUEToolsScript script = (CUEToolsScript)p[6];
            DialogResult dlgRes = DialogResult.OK;
            string status = null;
            bool outputAudio = action == CUEAction.Encode && audioEncoderType != AudioEncoderType.NoAudio;
            bool useAR = action == CUEAction.Verify || (outputAudio && checkBoxUseAccurateRip.Checked);
            bool useCUEToolsDB = action == CUEAction.Verify && checkBoxVerifyUseCDRepair.Checked;
            bool useLocalDB = action != CUEAction.Verify || checkBoxVerifyUseLocal.Checked;
            bool skipRecent = action == CUEAction.Verify && checkBoxSkipRecent.Checked;

            try
            {
                if (_profile._config.checkForUpdates && DateTime.UtcNow - lastMOTD > TimeSpan.FromDays(1) && _batchReport.Length == 0)
                {
                    this.Invoke((MethodInvoker)(() => toolStripStatusLabel1.Text = "Checking for updates..."));
                    IWebProxy proxy = _profile._config.GetProxy();
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://cuetools.net/motd/motd.jpg");
                    req.Proxy = proxy;
                    req.Method = "GET";
                    try
                    {
                        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                            if (resp.StatusCode == HttpStatusCode.OK)
                            {
                                using (Stream respStream = resp.GetResponseStream())
                                using (FileStream motd = new FileStream(MOTDImagePath, FileMode.Create, FileAccess.Write))
                                {
                                    byte[] buff = new byte[0x8000];
                                    do
                                    {
                                        int count = respStream.Read(buff, 0, buff.Length);
                                        if (count == 0) break;
                                        motd.Write(buff, 0, count);
                                    } while (true);
                                }
                            }
                            else
                            {
                                File.Delete(MOTDImagePath);
                            }
                        lastMOTD = DateTime.UtcNow;
                    }
                    catch (WebException ex)
                    {
                        if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null && ex.Response is HttpWebResponse)
                        {
                            HttpWebResponse resp = (HttpWebResponse)ex.Response;
                            if (resp.StatusCode == HttpStatusCode.NotFound)
                            {
                                File.Delete(MOTDImagePath);
                                lastMOTD = DateTime.UtcNow;
                            }
                        }
                    }

                    motdImage = null;
                    if (File.Exists(MOTDImagePath))
                        using (FileStream imageStream = new FileStream(MOTDImagePath, FileMode.Open, FileAccess.Read))
                            try { motdImage = Image.FromStream(imageStream); }
                            catch { }

                    req = (HttpWebRequest)WebRequest.Create("http://cuetools.net/motd/motd.txt");
                    req.Proxy = proxy;
                    req.Method = "GET";
                    try
                    {
                        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                        {
                            if (resp.StatusCode == HttpStatusCode.OK)
                            {
                                using (Stream respStream = resp.GetResponseStream())
                                using (FileStream motd = new FileStream(MOTDTextPath, FileMode.Create, FileAccess.Write))
                                using (StreamReader sr = new StreamReader(respStream, Encoding.UTF8))
                                using (StreamWriter sw = new StreamWriter(motd, Encoding.UTF8))
                                {
                                    string motdText = sr.ReadToEnd();
                                    sw.Write(motdText);
                                }
                            }
                            else
                            {
                                File.Delete(MOTDTextPath);
                            }
                        }
                        lastMOTD = DateTime.UtcNow;
                    }
                    catch { }
                    if (File.Exists(MOTDTextPath))
                        try
                        {
                            using (StreamReader sr = new StreamReader(MOTDTextPath, Encoding.UTF8))
                            {
                                string version = sr.ReadLine();
                                if (version != MOTDVersion)
                                {
                                    string motd = sr.ReadToEnd();
                                    _batchReport.Append(motd);
                                }
                            }
                        }
                        catch { }
                }
                if (action == CUEAction.CreateDummyCUE)
                {
                    if (Directory.Exists(pathIn))
                    {
                        if (_batchPaths.Count == 0)
                            throw new Exception("is a directory");
                        List<FileGroupInfo> fileGroups = CUESheet.ScanFolder(_profile._config, pathIn);
                        int directoriesFound = 0, cueSheetsFound = 0;
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.Folder)
                                _batchPaths.Insert(++directoriesFound, fileGroup.main.FullName);
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.CUESheetFile)
                                throw new Exception("already contains a cue sheet");
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.TrackFiles || fileGroup.type == FileGroupInfoType.FileWithCUE || fileGroup.type == FileGroupInfoType.M3UFile)
                                _batchPaths.Insert(directoriesFound + (++cueSheetsFound), fileGroup.main.FullName);
                    }
                    else if (File.Exists(pathIn))
                    {
                        pathIn = Path.GetFullPath(pathIn);
                        List<FileGroupInfo> fileGroups = CUESheet.ScanFolder(_profile._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));
                        if (fileGroup == null)
                            throw new Exception("doesn't seem to be part of an album");
                        string cueSheetContents;
                        if (_batchPaths.Count == 0)
                        {
                            cueSheet.Open(fileGroup.main.FullName);
                            cueSheetContents = cueSheet.GetCUESheetContents();
                            cueSheet.Close();
                        }
                        else
                            cueSheetContents = CUESheet.CreateDummyCUESheet(_profile._config, fileGroup);
                        string fullCueName;
                        if (fileGroup.type == FileGroupInfoType.FileWithCUE)
                            fullCueName = Path.ChangeExtension(fileGroup.main.FullName, ".cue");
                        else
                        {
                            string cueName = Path.GetFileName(Path.GetDirectoryName(pathIn)) + (fileGroup.discNo != 1 ? ".cd" + fileGroup.discNo.ToString() : "") + ".cuetools" + Path.GetExtension(pathIn) + ".cue";
                            fullCueName = Path.Combine(Path.GetDirectoryName(pathIn), cueName);
                        }
                        if (File.Exists(fullCueName))
                            throw new Exception("file already exists");
                        bool utf8Required = CUESheet.Encoding.GetString(CUESheet.Encoding.GetBytes(cueSheetContents)) != cueSheetContents;
                        StreamWriter sw1 = new StreamWriter(fullCueName, false, utf8Required ? Encoding.UTF8 : CUESheet.Encoding);
                        sw1.Write(cueSheetContents);
                        sw1.Close();
                        BatchLog("created ok.", fullCueName);
                    }
                    else
                    {
                        //if (_batchPaths.Count > 0)
                        //BatchLog("invalid path", pathIn);
                        throw new Exception("invalid path");
                    }
                }
                else if (action == CUEAction.CorrectFilenames)
                {
                    if (Directory.Exists(pathIn))
                    {
                        if (_batchPaths.Count == 0)
                            throw new Exception("is a directory");
                        string[] cues = Directory.GetFiles(pathIn, "*.cue", SearchOption.AllDirectories);
                        if (cues.Length == 0)
                            BatchLog("no cue files.", pathIn);
                        else
                            _batchPaths.InsertRange(1, cues);
                    }
                    else if (File.Exists(pathIn))
                    {
                        if (Path.GetExtension(pathIn).ToLower() != ".cue")
                            throw new Exception("is not a .cue file");
                        string cue = null;
                        using (StreamReader sr = new StreamReader(pathIn, CUESheet.Encoding))
                            cue = sr.ReadToEnd();
                        string extension;
                        string fixedCue;
                        if (CorrectorMode == CorrectorModeEnum.Locate)
                            fixedCue = CUESheet.CorrectAudioFilenames(_profile._config, Path.GetDirectoryName(pathIn), cue, true, null, out extension);
                        else
                        {
                            extension = toolStripDropDownButtonCorrectorFormat.Text;
                            using (StringReader sr = new StringReader(cue))
                            {
                                using (StringWriter sw = new StringWriter())
                                {
                                    string lineStr;
                                    while ((lineStr = sr.ReadLine()) != null)
                                    {
                                        CUELine line = new CUELine(lineStr);
                                        if (line.Params.Count == 3 && line.Params[0].ToUpper() == "FILE"
                                            && (line.Params[2].ToUpper() != "BINARY" && line.Params[2].ToUpper() != "MOTOROLA")
                                            )
                                            sw.WriteLine("FILE \"" + Path.ChangeExtension(line.Params[1], "." + extension) + "\" WAVE");
                                        else
                                            sw.WriteLine(lineStr);
                                    }
                                    fixedCue = sw.ToString();
                                }
                            }
                        }
                        if (fixedCue != cue)
                        {
                            if (toolStripButtonCorrectorOverwrite.Checked)
                            {
                                using (StreamWriter sw = new StreamWriter(pathIn, false, CUESheet.Encoding))
                                    sw.Write(fixedCue);
                                BatchLog("corrected ({0}).", pathIn, extension);
                            }
                            else
                            {
                                string pathFixed = Path.ChangeExtension(pathIn, extension + ".cue");
                                if (File.Exists(pathFixed))
                                    BatchLog("corrected cue already exists.", pathIn);
                                else
                                {
                                    using (StreamWriter sw = new StreamWriter(pathFixed, false, CUESheet.Encoding))
                                        sw.Write(fixedCue);
                                    BatchLog("corrected ({0}).", pathIn, extension);
                                }
                            }
                        }
                        else
                            BatchLog("no changes.", pathIn);
                    }
                    else
                        throw new Exception("invalid path");
                }
                else
                {
                    if (Directory.Exists(pathIn) && !IsCDROM(pathIn))
                    {
                        if (_batchPaths.Count == 0)
                            throw new Exception("is a directory");
                        List<FileGroupInfo> fileGroups = CUESheet.ScanFolder(_profile._config, pathIn);
                        int directoriesFound = 0, cueSheetsFound = 0;
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.Folder)
                                _batchPaths.Insert(++directoriesFound, fileGroup.main.FullName);
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.FileWithCUE)
                                _batchPaths.Insert(directoriesFound + (++cueSheetsFound), fileGroup.main.FullName);
                        foreach (FileGroupInfo fileGroup in fileGroups)
                            if (fileGroup.type == FileGroupInfoType.CUESheetFile)
                            {
                                string cue;
                                using (TextReader tr = new StreamReader(fileGroup.main.FullName))
                                    cue = tr.ReadToEnd();
                                foreach (FileGroupInfo fileGroup2 in fileGroups)
                                    if (fileGroup2.type == FileGroupInfoType.FileWithCUE && fileGroup2.TOC != null)
                                    {
                                        CDImageLayout toc = CUESheet.CUE2TOC(cue, (int)fileGroup2.TOC.AudioLength);
                                        if (toc != null && toc.TrackOffsets == fileGroup2.TOC.TrackOffsets)
                                        {
                                            cue = null;
                                            break;
                                        }
                                    }
                                if (cue != null)
                                    _batchPaths.Insert(directoriesFound + (++cueSheetsFound), fileGroup.main.FullName);
                            }
                        if (cueSheetsFound == 0)
                            foreach (FileGroupInfo fileGroup in fileGroups)
                                if (fileGroup.type == FileGroupInfoType.TrackFiles)
                                    _batchPaths.Insert(directoriesFound + (++cueSheetsFound), fileGroup.main.FullName);
                    }
                    else if (File.Exists(pathIn) || IsCDROM(pathIn))
                    {
                        string pathOut = null;

                        if (Directory.Exists(pathIn) && !pathIn.EndsWith(new string(Path.DirectorySeparatorChar, 1)))
                            pathIn = pathIn + Path.DirectorySeparatorChar;

                        var fullInputPath = CUEToolsLocalDBEntry.NormalizePath(pathIn);
                        var recentEntry = skipRecent ? _localDB.Find(item =>
                            item.HasPath(fullInputPath) && item.VerificationDate != DateTime.MinValue && item.Status != null && item.VerificationDate.AddDays(30) > DateTime.Now) : null;
                        if (recentEntry != null)
                            throw new Exception("recently verified: " + recentEntry.Status);

                        cueSheet.Action = action;
                        cueSheet.OutputStyle = cueStyle;
                        cueSheet.Open(pathIn);
                        cueSheet.PreGapLengthMSF = txtPreGapLength.Text;
                        if (useAR || useCUEToolsDB)
                            cueSheet.DataTrackLengthMSF = txtDataTrackLength.Text;
                        if (useLocalDB)
                            cueSheet.UseLocalDB(_localDB);
                        if (useCUEToolsDB)
                            cueSheet.UseCUEToolsDB("CUETools " + CUESheet.CUEToolsVersion, null, true, CTDBMetadataSearch.None);
                        if (useAR)
                            cueSheet.UseAccurateRip();

                        List<string> fullAudioPaths = cueSheet.SourcePaths.ConvertAll(sp => CUEToolsLocalDBEntry.NormalizePath(sp));
                        recentEntry = skipRecent ? _localDB.Find(item =>
                            item.Equals(cueSheet.TOC, fullAudioPaths) && item.VerificationDate != null && item.Status != null && item.VerificationDate.AddDays(30) > DateTime.Now) : null;
                        if (recentEntry != null)
                        {
                            if (useLocalDB)
                            {
                                _localDB.Dirty = true;
                                if (recentEntry.InputPaths == null)
                                    recentEntry.InputPaths = new List<string>();
                                if (!recentEntry.InputPaths.Contains(fullInputPath))
                                    recentEntry.InputPaths.Add(fullInputPath);
                            }
                            throw new Exception("recently verified: " + recentEntry.Status);
                        }

                        this.Invoke((MethodInvoker)delegate()
                        {
                            toolStripStatusLabelAR.Visible = useAR;
                            toolStripStatusLabelCTDB.Visible = useCUEToolsDB;

                            if (_batchPaths.Count == 0 && action == CUEAction.Encode && (checkBoxUseFreeDb.Checked || checkBoxUseMusicBrainz.Checked))
                            {
                                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(_profile._config.advanced.CacheMetadata,
                                    true,
                                    true,
                                    CTDBMetadataSearch.Default);
                                dlgRes = dlg.ShowDialog(this);
                                _choiceMaxed = dlg.WindowState == FormWindowState.Maximized;
                                if (!_choiceMaxed)
                                {
                                    _choiceHeight = dlg.Height;
                                    _choiceWidth = dlg.Width;
                                }
                                if (dlgRes == DialogResult.Cancel)
                                {
                                    cueSheet.Close();
                                    SetupControls(false);
                                }
                                else if (_profile._config.advanced.CacheMetadata && dlg.ChosenRelease != null)
                                {
                                    var entry = cueSheet.OpenLocalDBEntry();
                                    if (entry != null)
                                    {
                                        _localDB.Dirty = true;
                                        entry.Metadata.CopyMetadata(dlg.ChosenRelease.metadata);
                                    }
                                }
                                dlg.Close();
                            }
                            else if (_profile._config.advanced.CacheMetadata)
                            {
                                recentEntry = _localDB.Find(item => item.Equals(cueSheet.TOC, fullAudioPaths));
                                if (recentEntry != null)
                                    cueSheet.CopyMetadata(recentEntry.Metadata);
                            }

                            UpdateOutputPath(pathIn, cueSheet);
                            pathOut = txtOutputPath.Text;
                            if (dlgRes != DialogResult.Cancel && cueSheet.AlbumArt.Count != 0)
                                pictureBoxMotd.Image = cueSheet.Cover;
                            else
                                pictureBoxMotd.Image = motdImage;
                        });

                        if (dlgRes == DialogResult.Cancel)
                            return;

                        cueSheet.GenerateFilenames(audioEncoderType, outputFormat, pathOut);

                        List<string> outputExists = cueSheet.OutputExists();

                        dlgRes = DialogResult.Cancel;
                        if (outputExists.Count > 0)
                        {
                            this.Invoke((MethodInvoker)delegate()
                            {
                                if (overwriteResult == DialogResult.None)
                                {
                                    using (frmOverwrite frm = new frmOverwrite())
                                    {
                                        outputExists.ForEach(path => frm.textFiles.AppendText(path + "\n"));
                                        dlgRes = frm.ShowDialog(this);
                                        if (frm.checkBoxRemember.Checked)
                                            overwriteResult = dlgRes;
                                    }
                                }
                                else
                                    dlgRes = overwriteResult;
                                if (dlgRes == DialogResult.Yes)
                                    outputExists.Clear();
                                else if (_batchPaths.Count == 0)
                                    SetupControls(false);
                            });
                            if (outputExists.Count > 0 && _batchPaths.Count == 0)
                            {
                                cueSheet.Close();
                                return;
                            }
                        }
                        if (outputExists.Count == 0)
                        {
                            cueSheet.UsePregapForFirstTrackInSingleFile = _usePregapForFirstTrackInSingleFile && !outputAudio;
                            if (script == null || (script.builtin && script.name == "default"))
                            {
                                status = cueSheet.Go();
                                if (cueSheet.Config.advanced.CTDBSubmit
                                    && useAR
                                    && useCUEToolsDB
                                    && cueSheet.ArVerify.ARStatus == null
                                    && cueSheet.ArVerify.WorstConfidence() >= 2
                                    && (cueSheet.AccurateRipId == null || AccurateRipVerify.CalculateAccurateRipId(cueSheet.TOC) == cueSheet.AccurateRipId)
                                    && cueSheet.CTDB.MatchingEntries.Count == 0
                                    && (cueSheet.CTDB.QueryExceptionStatus == WebExceptionStatus.Success
                                     || (cueSheet.CTDB.QueryExceptionStatus == WebExceptionStatus.ProtocolError && cueSheet.CTDB.QueryResponseStatus == HttpStatusCode.NotFound)
                                     )
                                    )
                                {
                                    DialogResult res = DialogResult.OK;
                                    if (cueSheet.Config.advanced.CTDBAsk)
                                    {
                                        bool remember = true;
                                        this.Invoke((MethodInvoker)delegate()
                                        {
                                            var confirm = new frmSubmit();
                                            res = confirm.ShowDialog(this);
                                            remember = confirm.checkBoxRemember.Checked;
                                        });
                                        if (remember)
                                        {
                                            cueSheet.Config.advanced.CTDBSubmit = res == DialogResult.OK;
                                            cueSheet.Config.advanced.CTDBAsk = false;
                                        }
                                    }
                                    if (res == DialogResult.OK)
                                    {
                                        cueSheet.CTDB.Submit(
                                            (int)cueSheet.ArVerify.WorstConfidence(),
                                            100,
                                            cueSheet.Metadata.Artist,
                                            cueSheet.Metadata.Title + (cueSheet.Metadata.Title != "" && cueSheet.Metadata.DiscNumberAndName != "" ? " (disc " + cueSheet.Metadata.DiscNumberAndName + ")" : ""),
                                            cueSheet.Metadata.Barcode);
                                        if (cueSheet.CTDB.SubStatus != null)
                                            status += ", submit: " + cueSheet.CTDB.SubStatus;
                                    }
                                }
                            }
                            else
                                status = cueSheet.ExecuteScript(script);

                            if (_batchPaths.Count > 0)
                            {
                                _batchProcessed++;
                                BatchLog("{0}.", pathIn, status);
                            }
                            cueSheet.CheckStop();
                        }
                    }
                    else
                        throw new Exception("invalid path");
                }
                this.Invoke((MethodInvoker)delegate()
                {
                    if (_batchPaths.Count == 0)
                    {
                        if (cueSheet.IsCD)
                        {
                            frmReport reportForm = new frmReport();
                            reportForm.Message = cueSheet.LOGContents;
                            reportForm.ShowDialog(this);
                        }
                        else if (action == CUEAction.CreateDummyCUE || action == CUEAction.CorrectFilenames)
                        {
                            ReportState = true;
                            //frmReport reportForm = new frmReport();
                            //reportForm.Message = _batchReport.ToString();
                            //reportForm.ShowDialog(this);
                        }
                        else if (useAR && cueSheet.Processed)
                        {
                            _batchReport.Append(CUESheetLogWriter.GetAccurateRipLog(cueSheet));
                            ReportState = true;

                            //frmReport reportForm = new frmReport();
                            //StringWriter sw = new StringWriter();
                            //cueSheet.GenerateAccurateRipLog(sw);
                            //if (status != null)
                            //    reportForm.Text += ": " + status;
                            //reportForm.Message = sw.ToString();
                            //_batchReport.Append(sw.ToString());
                            //sw.Close();
                            //reportForm.ShowDialog(this);
                        }
                        else
                            ShowFinishedMessage(cueSheet.PaddedToFrame, status);
                        SetupControls(false);
                    }
                });
            }
            catch (StopException)
            {
            }
#if !DEBUG
            catch (Exception ex)
            {
                if (_batchPaths.Count == 0)
                {
                    this.Invoke((MethodInvoker)delegate()
                    {
                        SetupControls(false);
                        ShowErrorMessage(ex);
                    });
                }
                else
                {
                    _batchProcessed++;
                    String msg = "";
                    for (Exception e = ex; e != null; e = e.InnerException)
                        msg += ": " + e.Message;
                    BatchLog("{0}.", pathIn, msg.Substring(2));

                }
            }
#endif
            try
            {
                cueSheet.CheckStop();
            }
            catch (StopException)
            {
                _batchPaths.Clear();
                this.Invoke((MethodInvoker)delegate()
                {
                    SetupControls(false);
                    MessageBox.Show(this, "Conversion was stopped.", "Stopped", MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);
                });
            }
            cueSheet.Close();

            if (_batchPaths.Count != 0)
            {
                _batchPaths.RemoveAt(0);
                if (_batchPaths.Count == 0)
                {
                    SaveDatabase();
                }
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    if (_batchPaths.Count == 0)
                    {
                        SetupControls(false);
                        ReportState = true;
                        //frmReport reportForm = new frmReport();
                        //reportForm.Message = _batchReport.ToString();
                        //reportForm.ShowDialog(this);
                        //ShowBatchDoneMessage();
                    }
                    else
                    {
                        StartConvert();
                    }
                });
            }
        }
コード例 #7
0
ファイル: General.cs プロジェクト: androidhacker/DotNetProjs
        public static void SetCUELine(List<CUELine> list, string command, string command2, string value, bool quoted)
        {
            if (value == "")
            {
                General.DelCUELine(list, command, command2);
                return;
            }

            value = value.Replace('\n', ' ').Replace('\r', ' ').Replace('"', '\'');
            if (value.Length > 1024)
                value = value.Substring(0, 1021) + "...";

            CUELine line = General.FindCUELine(list, command, command2);
            if (line == null)
            {
                line = new CUELine();
                line.Params.Add(command); line.IsQuoted.Add(false);
                line.Params.Add(command2); line.IsQuoted.Add(false);
                line.Params.Add(value); line.IsQuoted.Add(quoted);
                list.Add(line);
            }
            else
            {
                while (line.Params.Count > 2)
                {
                    line.Params.RemoveAt(2);
                    line.IsQuoted.RemoveAt(2);
                }
                line.Params.Add(value); line.IsQuoted.Add(quoted);
            }
        }