Esempio n. 1
0
        private void RippingThread()
        {
            if (_main.TreeView.InvokeRequired)
            {
                ThreadSafeGridDelegate d = RippingThread;
                _main.TreeView.Invoke(d, new object[] { });
                return;
            }

            if (_selectedCDRomDrive == "")
            {
                log.Info("No CD drive selected. Rip not started.");
                return;
            }

            log.Trace(">>>");
            string targetDir = "";
            string encoder   = null;

            try
            {
                _musicDir = _main.RipOutputDirectory;

                if (_main.RipEncoderCombo.SelectedItem != null)
                {
                    encoder = (string)(_main.RipEncoderCombo.SelectedItem as Item).Value;
                    Options.MainSettings.RipEncoder = encoder;
                }
                else
                {
                    encoder = Options.MainSettings.RipEncoder;
                }

                if (encoder == null)
                {
                    return;
                }

                log.Debug("Rip: Using Encoder: {0}", encoder);

                try
                {
                    if (!Directory.Exists(_musicDir) && !string.IsNullOrEmpty(_musicDir))
                    {
                        Directory.CreateDirectory(_musicDir);
                    }
                }
                catch (Exception ex)
                {
                    SetStatusLabel(localisation.ToString("Conversion", "ErrorDirectory"));
                    log.Error("Error creating Ripping directory: {0}. {1}", _musicDir, ex.Message);
                    return;
                }

                // Build the Target Directory
                string artistDir = tbAlbumArtist.Text == string.Empty ? "Artist" : tbAlbumArtist.Text;
                string albumDir  = tbAlbum.Text == string.Empty ? "Album" : tbAlbum.Text;

                string outFileFormat = Options.MainSettings.RipFileNameFormat;
                int    index         = outFileFormat.LastIndexOf('\\');
                if (index > -1)
                {
                    targetDir     = outFileFormat.Substring(0, index);
                    targetDir     = targetDir.Replace("<A>", artistDir);
                    targetDir     = targetDir.Replace("<O>", artistDir);
                    targetDir     = targetDir.Replace("<B>", albumDir);
                    targetDir     = targetDir.Replace("<G>", tbGenre.Text);
                    targetDir     = targetDir.Replace("<Y>", tbYear.Text);
                    outFileFormat = outFileFormat.Substring(index + 1);
                }
                else
                {
                    targetDir = string.Format(@"{0}\{1}", artistDir, albumDir);
                }

                targetDir = Util.MakeValidFolderName(targetDir);

                targetDir = string.Format(@"{0}\{1}", _musicDir, targetDir);

                log.Debug("Rip: Using Target Folder: {0}", targetDir);

                try
                {
                    if (!Directory.Exists(targetDir))
                    {
                        Directory.CreateDirectory(targetDir);
                    }
                }
                catch (Exception ex)
                {
                    SetStatusLabel(localisation.ToString("Conversion", "ErrorDirectory"));
                    log.Error("Error creating Ripping directory: {0}. {1}", targetDir, ex.Message);
                    return;
                }

                log.Debug("Rip: Selected CD Drive: {0}", _selectedCDRomDrive);

                int selectedDriveID = 0;
                try
                {
                    // User may change to a different drive while ripping
                    selectedDriveID = CurrentDriveID;
                    log.Debug("Rip: Selected drive id: {0}", selectedDriveID);
                }
                catch (Exception)
                {
                    log.Debug("Rip: Error setting the drive id. Fallback to drive #0");
                    selectedDriveID = 0;
                }

                // Lock the Door
                BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_LOCK);

                foreach (DataGridViewRow row in dataGridViewRip.Rows)
                {
                    // Reset the Status field to 0
                    row.Cells[1].Value = 0;
                }

                _currentRow = -1;
                foreach (DataGridViewRow row in dataGridViewRip.Rows)
                {
                    // when checking and unchecking a row, we have the DBNull value
                    if (row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value)
                    {
                        continue;
                    }

                    if ((int)row.Cells[0].Value == 0)
                    {
                        continue;
                    }

                    SetStatusLabel(localisation.ToString("Conversion", "Ripping"));

                    _currentRow = row.Index;

                    CDTrackDetail track = bindingList[selectedDriveID][_currentRow];

                    int stream = BassCd.BASS_CD_StreamCreate(selectedDriveID, row.Index, BASSFlag.BASS_STREAM_DECODE);
                    if (stream == 0)
                    {
                        log.Error("Error creating stream for Audio Track {0}. Error: {1}", _currentRow,
                                  Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                        continue;
                    }

                    log.Info("Ripping Audio CD Track{0} - {1}", row.Index + 1, track.Title);
                    _outFile = outFileFormat;
                    _outFile = _outFile.Replace("<O>", artistDir);
                    _outFile = _outFile.Replace("<B>", albumDir);
                    _outFile = _outFile.Replace("<G>", tbGenre.Text);
                    _outFile = _outFile.Replace("<Y>", tbYear.Text);
                    _outFile = _outFile.Replace("<A>", track.Artist);
                    _outFile = _outFile.Replace("<K>", track.Track.ToString().PadLeft(Options.MainSettings.NumberTrackDigits, '0'));
                    _outFile = _outFile.Replace("<T>", track.Title);
                    _outFile = Util.MakeValidFileName(_outFile);

                    _outFile = string.Format(@"{0}\{1}", targetDir, _outFile);

                    _outFile = audioEncoder.SetEncoder(encoder, _outFile);

                    if (audioEncoder.StartEncoding(stream) != BASSError.BASS_OK)
                    {
                        log.Error("Error starting Encoder for Audio Track {0}. Error: {1}", _currentRow,
                                  Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                    }

                    dataGridViewRip.Rows[_currentRow].Cells[1].Value = 100;

                    Bass.BASS_StreamFree(stream);
                    log.Info("Finished Ripping Audio CD Track{0}", _currentRow + 1);

                    try
                    {
                        // Now Tag the encoded File
                        File file = File.Create(_outFile);
                        file.Tag.AlbumArtists = new[] { tbAlbumArtist.Text };
                        file.Tag.Album        = tbAlbum.Text;
                        file.Tag.Genres       = new[] { tbGenre.Text };
                        file.Tag.Year         = tbYear.Text == string.Empty ? 0 : Convert.ToUInt32(tbYear.Text);
                        file.Tag.Performers   = new[] { track.Artist };
                        file.Tag.Track        = (uint)track.Track;
                        file.Tag.Title        = track.Title;
                        file = Util.FormatID3Tag(file);
                        file.Save();
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error tagging encoded file {0}. Error: {1}", _outFile, ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Rip: Exception: {0} {1}", ex.Message, ex.StackTrace);
            }

            _currentRow = -1;
            SetStatusLabel(localisation.ToString("Conversion", "RippingFinished"));
            Options.MainSettings.RipTargetFolder = _musicDir;
            Options.MainSettings.RipEncoder      = encoder;

            // Unlock the Drive and open the door, if selected
            BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_UNLOCK);
            if (Options.MainSettings.RipEjectCD)
            {
                BassCd.BASS_CD_Door(CurrentDriveID, BASSCDDoor.BASS_CD_DOOR_OPEN);
            }

            // Activate the target Folder, if selected
            if (Options.MainSettings.RipActivateTargetFolder)
            {
                _main.CurrentDirectory = targetDir;
                _main.TreeView.RefreshFolders();
                _main.Ribbon.CurrentTabPage = _main.TabTag;
                _main.TracksGridView.Show();
                if (_main.SplitterRight.IsCollapsed && !Options.MainSettings.RightPanelCollapsed)
                {
                    _main.SplitterRight.ToggleState();
                }
                _main.RefreshTrackList();
            }

            log.Trace("<<<");
        }
        private void ConversionThread()
        {
            if (_main.InvokeRequired)
            {
                ThreadSafeConvertDelegate d = ConversionThread;
                _main.Invoke(d);
                return;
            }

            log.Trace(">>>");
            string rootFolder = _main.EncoderOutputDirectory;

            if (string.IsNullOrEmpty(rootFolder))
            {
                rootFolder = Options.MainSettings.RipTargetFolder;
            }

            string encoder = null;

            if (_main.EncoderCombo.SelectedItem != null)
            {
                encoder = (string)(_main.EncoderCombo.SelectedItem as Item).Value;
            }

            if (encoder == null)
            {
                return;
            }

            try
            {
                if (!Directory.Exists(rootFolder) && !string.IsNullOrEmpty(rootFolder))
                {
                    Directory.CreateDirectory(rootFolder);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(localisation.ToString("Conversion", "ErrorDirectory"), localisation.ToString("message", "Error_Title"), MessageBoxButtons.OK);
                log.Error("Error creating Conversion output directory: {0}. {1}", rootFolder, ex.Message);
                return;
            }

            foreach (DataGridViewRow row in dataGridViewConvert.Rows)
            {
                // Reset the Status field to 0
                row.Cells[0].Value = 0;
            }

            _currentRow = -1;
            foreach (DataGridViewRow row in dataGridViewConvert.Rows)
            {
                _currentRow = row.Index;

                ConversionData track = bindingList[_currentRow];

                string inputFile = track.Track.FullFileName;
                string outFile   = Util.ReplaceParametersWithTrackValues(Options.MainSettings.RipFileNameFormat, track.Track);
                outFile = Path.Combine(rootFolder, outFile);
                string directoryName = Path.GetDirectoryName(outFile);

                // Now check the validity of the directory
                if (!Directory.Exists(directoryName))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryName);
                    }
                    catch (Exception e1)
                    {
                        log.Error("Error creating folder: {0} {1]", directoryName, e1.Message);
                        row.Cells[0].Value       = localisation.ToString("message", "Error");
                        row.Cells[0].ToolTipText = String.Format("{0}: {1}", localisation.ToString("message", "Error"), e1.Message);
                        continue; // Process next row
                    }
                }

                outFile = audioEncoder.SetEncoder(encoder, outFile);
                UpdateNewFileName(outFile);

                if (inputFile == outFile)
                {
                    row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "SameFile"));
                    log.Error("No conversion for {0}. Output would overwrite input", inputFile);
                    continue;
                }

                int stream = Bass.BASS_StreamCreateFile(inputFile, 0, 0, BASSFlag.BASS_STREAM_DECODE);
                if (stream == 0)
                {
                    row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "OpenFileError"));
                    log.Error("Error creating stream for file {0}. Error: {1}", inputFile,
                              Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                    continue;
                }

                log.Info("Convert file {0} -> {1}", inputFile, outFile);

                if (audioEncoder.StartEncoding(stream) != BASSError.BASS_OK)
                {
                    row.Cells[0].ToolTipText = String.Format("{0}: {1}", inputFile, localisation.ToString("Conversion", "EncodingFileError"));
                    log.Error("Error starting Encoder for File {0}. Error: {1}", inputFile,
                              Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                    Bass.BASS_StreamFree(stream);
                    continue;
                }

                dataGridViewConvert.Rows[_currentRow].Cells[0].Value = 100;

                Bass.BASS_StreamFree(stream);

                try
                {
                    // Now Tag the encoded File
                    File tagInFile  = File.Create(inputFile);
                    File tagOutFile = File.Create(outFile);
                    tagOutFile.Tag.AlbumArtists = tagInFile.Tag.AlbumArtists;
                    tagOutFile.Tag.Album        = tagInFile.Tag.Album;
                    tagOutFile.Tag.Genres       = tagInFile.Tag.Genres;
                    tagOutFile.Tag.Year         = tagInFile.Tag.Year;
                    tagOutFile.Tag.Performers   = tagInFile.Tag.Performers;
                    tagOutFile.Tag.Track        = tagInFile.Tag.Track;
                    tagOutFile.Tag.TrackCount   = tagInFile.Tag.TrackCount;
                    tagOutFile.Tag.Title        = tagInFile.Tag.Title;
                    tagOutFile.Tag.Comment      = tagInFile.Tag.Comment;
                    tagOutFile.Tag.Composers    = tagInFile.Tag.Composers;
                    tagOutFile.Tag.Conductor    = tagInFile.Tag.Conductor;
                    tagOutFile.Tag.Copyright    = tagInFile.Tag.Copyright;
                    tagOutFile.Tag.Disc         = tagInFile.Tag.Disc;
                    tagOutFile.Tag.DiscCount    = tagInFile.Tag.DiscCount;
                    tagOutFile.Tag.Lyrics       = tagInFile.Tag.Lyrics;
                    tagOutFile.Tag.Pictures     = tagInFile.Tag.Pictures;
                    tagOutFile = Util.FormatID3Tag(tagOutFile);
                    tagOutFile.Save();
                }
                catch (Exception ex)
                {
                    log.Error("Error tagging encoded file {0}. Error: {1}", outFile, ex.Message);
                }
            }
            Options.MainSettings.LastConversionEncoderUsed = encoder;
            _currentRow = -1;

            log.Trace("<<<");
        }