Example #1
0
        /// <summary>
        /// Read the Tags from the File
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static TrackData Create(string fileName)
        {
            TrackData track = new TrackData();

            TagLib.File file  = null;
            bool        error = false;

            try
            {
                TagLib.ByteVector.UseBrokenLatin1Behavior = true;
                file = TagLib.File.Create(fileName);
            }
            catch (CorruptFileException)
            {
                log.Warn("File Read: Ignoring track {0} - Corrupt File!", fileName);
                error = true;
            }
            catch (UnsupportedFormatException)
            {
                log.Warn("File Read: Ignoring track {0} - Unsupported format!", fileName);
                error = true;
            }
            catch (FileNotFoundException)
            {
                log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", fileName);
                error = true;
            }
            catch (Exception ex)
            {
                log.Error("File Read: Error processing file: {0} {1}", fileName, ex.Message);
                error = true;
            }

            if (error)
            {
                return(null);
            }

            TagLib.Id3v2.Tag id3v2tag = null;
            try
            {
                if (file.MimeType.Substring(file.MimeType.IndexOf("/") + 1) == "mp3")
                {
                    id3v2tag = file.GetTag(TagTypes.Id3v2, false) as TagLib.Id3v2.Tag;
                }
            }
            catch (Exception ex)
            {
                log.Error("File Read: Error retrieving id3tag: {0} {1}", fileName, ex.Message);
                return(null);
            }

            #region Set Common Values

            FileInfo fi = new FileInfo(fileName);
            try
            {
                track.Id           = Guid.NewGuid();
                track.FullFileName = fileName;
                track.FileName     = Path.GetFileName(fileName);
                track.Readonly     = fi.IsReadOnly;
                track.TagType      = file.MimeType.Substring(file.MimeType.IndexOf("/") + 1);
            }
            catch (Exception ex)
            {
                log.Error("File Read: Error setting Common tags: {0} {1}", fileName, ex.Message);
                return(null);
            }
            #endregion

            #region Set Tags

            try
            {
                // Artist
                track.Artist = String.Join(";", file.Tag.Performers);
                if (track.Artist.Contains("AC;DC"))
                {
                    track.Artist = track.Artist.Replace("AC;DC", "AC/DC");
                }

                track.ArtistSortName = String.Join(";", file.Tag.PerformersSort);
                if (track.ArtistSortName.Contains("AC;DC"))
                {
                    track.ArtistSortName = track.ArtistSortName.Replace("AC;DC", "AC/DC");
                }

                track.AlbumArtist = String.Join(";", file.Tag.AlbumArtists);
                if (track.AlbumArtist.Contains("AC;DC"))
                {
                    track.AlbumArtist = track.AlbumArtist.Replace("AC;DC", "AC/DC");
                }

                track.AlbumArtistSortName = String.Join(";", file.Tag.AlbumArtistsSort);
                if (track.AlbumArtistSortName.Contains("AC;DC"))
                {
                    track.AlbumArtistSortName = track.AlbumArtistSortName.Replace("AC;DC", "AC/DC");
                }

                track.Album         = file.Tag.Album ?? "";
                track.AlbumSortName = file.Tag.AlbumSort ?? "";

                track.BPM         = (int)file.Tag.BeatsPerMinute;
                track.Compilation = id3v2tag == null ? false : id3v2tag.IsCompilation;
                track.Composer    = string.Join(";", file.Tag.Composers);
                track.Conductor   = file.Tag.Conductor ?? "";
                track.Copyright   = file.Tag.Copyright ?? "";

                track.DiscNumber = file.Tag.Disc;
                track.DiscCount  = file.Tag.DiscCount;

                track.Genre         = string.Join(";", file.Tag.Genres);
                track.Grouping      = file.Tag.Grouping ?? "";
                track.Title         = file.Tag.Title ?? "";
                track.TitleSortName = file.Tag.TitleSort ?? "";

                track.ReplayGainTrack     = file.Tag.ReplayGainTrack ?? "";
                track.ReplayGainTrackPeak = file.Tag.ReplayGainTrackPeak ?? "";
                track.ReplayGainAlbum     = file.Tag.ReplayGainAlbum ?? "";
                track.ReplayGainAlbumPeak = file.Tag.ReplayGainAlbumPeak ?? "";

                track.TrackNumber = file.Tag.Track;
                track.TrackCount  = file.Tag.TrackCount;
                track.Year        = (int)file.Tag.Year;

                // Pictures
                foreach (IPicture picture in file.Tag.Pictures)
                {
                    MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture
                    {
                        Type        = picture.Type,
                        MimeType    = picture.MimeType,
                        Description = picture.Description
                    };

                    pic.Data = picture.Data.Data;
                    track.Pictures.Add(pic);
                }

                // Comments
                if (track.IsMp3 && id3v2tag != null)
                {
                    foreach (CommentsFrame commentsframe in id3v2tag.GetFrames <CommentsFrame>())
                    {
                        track.ID3Comments.Add(new Comment(commentsframe.Description, commentsframe.Language, commentsframe.Text));
                    }
                }
                else
                {
                    track.Comment = file.Tag.Comment;
                }

                // Lyrics
                track.Lyrics = file.Tag.Lyrics;
                if (track.IsMp3 && id3v2tag != null)
                {
                    foreach (UnsynchronisedLyricsFrame lyricsframe in id3v2tag.GetFrames <UnsynchronisedLyricsFrame>())
                    {
                        // Only add non-empty Frames
                        if (lyricsframe.Text != "")
                        {
                            track.LyricsFrames.Add(new Lyric(lyricsframe.Description, lyricsframe.Language, lyricsframe.Text));
                        }
                    }
                }

                // Rating
                if (track.IsMp3)
                {
                    TagLib.Id3v2.PopularimeterFrame popmFrame = null;
                    // First read in all POPM Frames found
                    if (id3v2tag != null)
                    {
                        foreach (PopularimeterFrame popmframe in id3v2tag.GetFrames <PopularimeterFrame>())
                        {
                            // Only add valid POPM Frames
                            if (popmframe.User != "" && popmframe.Rating > 0)
                            {
                                track.Ratings.Add(new PopmFrame(popmframe.User, (int)popmframe.Rating, (int)popmframe.PlayCount));
                            }
                        }

                        popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, "MPTagThat", false);
                        if (popmFrame != null)
                        {
                            track.Rating = popmFrame.Rating;
                        }
                    }

                    if (popmFrame == null)
                    {
                        // Now check for Ape Rating
                        TagLib.Ape.Tag  apetag  = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag;
                        TagLib.Ape.Item apeItem = apetag.GetItem("RATING");
                        if (apeItem != null)
                        {
                            string rating = apeItem.ToString();
                            try
                            {
                                track.Rating = Convert.ToInt32(rating);
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                else if (track.TagType == "ape")
                {
                    TagLib.Ape.Tag  apetag  = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag;
                    TagLib.Ape.Item apeItem = apetag.GetItem("RATING");
                    if (apeItem != null)
                    {
                        string rating = apeItem.ToString();
                        try
                        {
                            track.Rating = Convert.ToInt32(rating);
                        }
                        catch (Exception)
                        { }
                    }
                }
                else if (track.TagType == "ogg" || track.TagType == "flac")
                {
                    XiphComment xiph   = file.GetTag(TagLib.TagTypes.Xiph, false) as XiphComment;
                    string[]    rating = xiph.GetField("RATING");
                    if (rating.Length > 0)
                    {
                        try
                        {
                            track.Rating = Convert.ToInt32(rating[0]);
                        }
                        catch (Exception)
                        { }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception setting Tags for file: {0}. {1}", fileName, ex.Message);
            }

            #endregion

            #region Set Properties

            try
            {
                track.DurationTimespan = file.Properties.Duration;

                int fileLength = (int)(fi.Length / 1024);
                track.FileSize = fileLength.ToString();

                track.BitRate       = file.Properties.AudioBitrate.ToString();
                track.SampleRate    = file.Properties.AudioSampleRate.ToString();
                track.Channels      = file.Properties.AudioChannels.ToString();
                track.Version       = file.Properties.Description;
                track.CreationTime  = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.CreationTime);
                track.LastWriteTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.LastWriteTime);
            }
            catch (Exception ex)
            {
                log.Error("Exception setting Properties for file: {0}. {1}", fileName, ex.Message);
            }

            #endregion

            // Now copy all Text frames of an ID3 V2
            try
            {
                if (track.IsMp3 && id3v2tag != null)
                {
                    foreach (TagLib.Id3v2.Frame frame in id3v2tag.GetFrames())
                    {
                        string id = frame.FrameId.ToString();
                        if (!Util.StandardFrames.Contains(id) && Util.ExtendedFrames.Contains(id))
                        {
                            track.Frames.Add(new Frame(id, "", frame.ToString()));
                        }
                        else if (!Util.StandardFrames.Contains(id) && !Util.ExtendedFrames.Contains(id))
                        {
                            if ((Type)frame.GetType() == typeof(UserTextInformationFrame))
                            {
                                // Don't add Replaygain frames, as they are handled in taglib tags
                                if (!Util.IsReplayGain((frame as UserTextInformationFrame).Description))
                                {
                                    track.UserFrames.Add(new Frame(id, (frame as UserTextInformationFrame).Description ?? "",
                                                                   (frame as UserTextInformationFrame).Text.Length == 0
                                                 ? ""
                                                 : (frame as UserTextInformationFrame).Text[0]));
                                }
                            }
                            else if ((Type)frame.GetType() == typeof(PrivateFrame))
                            {
                                track.UserFrames.Add(new Frame(id, (frame as PrivateFrame).Owner ?? "",
                                                               (frame as PrivateFrame).PrivateData == null
                                                 ? ""
                                                 : (frame as PrivateFrame).PrivateData.ToString()));
                            }
                            else if ((Type)frame.GetType() == typeof(UniqueFileIdentifierFrame))
                            {
                                track.UserFrames.Add(new Frame(id, (frame as UniqueFileIdentifierFrame).Owner ?? "",
                                                               (frame as UniqueFileIdentifierFrame).Identifier == null
                                                 ? ""
                                                 : (frame as UniqueFileIdentifierFrame).Identifier.ToString()));
                            }
                            else if ((Type)frame.GetType() == typeof(UnknownFrame))
                            {
                                track.UserFrames.Add(new Frame(id, "",
                                                               (frame as UnknownFrame).Data == null
                                                 ? ""
                                                 : (frame as UnknownFrame).Data.ToString()));
                            }
                            else
                            {
                                track.UserFrames.Add(new Frame(id, "", frame.ToString()));
                            }
                        }
                    }

                    track.ID3Version = id3v2tag.Version;
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception getting User Defined frames for file: {0}. {1}", fileName, ex.Message);
            }

            return(track);
        }
        /// <summary>
        ///   Get Cover Art via Amazon Webservice
        /// </summary>
        private void GetCoverArtThread()
        {
            log.Trace(">>>");
              //Make calls to Tracksgrid Threadsafe
              if (tracksGrid.InvokeRequired)
              {
            ThreadSafeGridDelegate d = GetCoverArtThread;
            tracksGrid.Invoke(d, new object[] { });
            return;
              }

              int count = 0;
              int trackCount = tracksGrid.SelectedRows.Count;
              SetProgressBar(trackCount);

              AmazonAlbum amazonAlbum = null;

              bool isMultipleArtistAlbum = false;
              string savedArtist = "";
              string savedAlbum = "";
              string savedFolder = "";

              Core.Common.Picture folderThumb = null;

              // Find out, if we deal with a multiple artist album and submit only the album name
              // If we have different artists, then it is a multiple artist album.
              // BUT: if the album is different, we don't have a multiple artist album and should submit the artist as well
              foreach (DataGridViewRow row in tracksGrid.Rows)
              {
            ClearStatusColumn(row.Index);

            if (!row.Selected)
            {
              continue;
            }

            TrackData track = Options.Songlist[row.Index];
            if (savedArtist == "")
            {
              savedArtist = track.Artist;
              savedAlbum = track.Album;
            }
            if (savedArtist != track.Artist)
            {
              isMultipleArtistAlbum = true;
            }
            if (savedAlbum != track.Album)
            {
              isMultipleArtistAlbum = false;
              break;
            }
              }

              if (isMultipleArtistAlbum)
              {
            log.Debug("CoverArt: Album contains Multiple Artists, just search for the album");
              }

              Dictionary<string, AmazonAlbum> savedCoverCash = new Dictionary<string, AmazonAlbum>();

              foreach (DataGridViewRow row in tracksGrid.Rows)
              {
            ClearStatusColumn(row.Index);

            if (!row.Selected)
            {
              continue;
            }

            count++;
            try
            {
              Application.DoEvents();
              _main.progressBar1.Value += 1;
              if (_progressCancelled)
              {
            ResetProgressBar();
            return;
              }
              TrackData track = Options.Songlist[row.Index];

              Util.SendProgress(string.Format("Search coverart for {0}", track.FileName));
              log.Debug("CoverArt: Retrieving coverart for: {0} - {1}", track.Artist, track.Album);
              // Should we take an existing folder.jpg instead of searching the web
              if (Options.MainSettings.EmbedFolderThumb && !Options.MainSettings.OnlySaveFolderThumb)
              {
            if (folderThumb == null || Path.GetDirectoryName(track.FullFileName) != savedFolder)
            {
              savedFolder = Path.GetDirectoryName(track.FullFileName);
              folderThumb = GetFolderThumb(savedFolder);
            }

            if (folderThumb != null)
            {
              // Only write a picture if we don't have a picture OR Overwrite Pictures is set
              if (track.Pictures.Count == 0 || Options.MainSettings.OverwriteExistingCovers)
              {
                if (Options.MainSettings.ChangeCoverSize && Picture.ImageFromData(folderThumb.Data).Width > Options.MainSettings.MaxCoverWidth)
                {
                  folderThumb.Resize(Options.MainSettings.MaxCoverWidth);
                }

                log.Debug("CoverArt: Using existing folder.jpg");
                // First Clear all the existingPictures
                track.Pictures.Clear();
                track.Pictures.Add(folderThumb);
                SetBackgroundColorChanged(row.Index);
                track.Changed = true;
                Options.Songlist[row.Index] = track;
                _itemsChanged = true;
                _main.SetGalleryItem();
              }
              continue;
            }
              }

              // If we don't have an Album don't do any query
              if (track.Album == "")
            continue;

              string coverSearchString = track.Artist + track.Album;
              if (isMultipleArtistAlbum)
              {
            coverSearchString = track.Album;
              }

              bool foundInCash = savedCoverCash.ContainsKey(coverSearchString);
              if (foundInCash)
              {
            amazonAlbum = savedCoverCash[coverSearchString];
              }
              else
              {
            amazonAlbum = null;
              }

              // Only retrieve the Cover Art, if we don't have it yet)
              if (!foundInCash || amazonAlbum == null)
              {
            CoverSearch dlgAlbumResults = new CoverSearch();
            dlgAlbumResults.Artist = isMultipleArtistAlbum ? "" : track.Artist;
            dlgAlbumResults.Album = track.Album;
            dlgAlbumResults.FileDetails = track.FullFileName;
            dlgAlbumResults.Owner = _main;

            amazonAlbum = null;
            DialogResult dlgResult = _main.ShowModalDialog(dlgAlbumResults);
            if (dlgResult == DialogResult.OK)
            {
              if (dlgAlbumResults.SelectedAlbum != null)
              {
                amazonAlbum = dlgAlbumResults.SelectedAlbum;
              }
            }
            else if (dlgResult == DialogResult.Abort)
            {
              log.Debug("CoverArt: Search for all albums cancelled");
              break;
            }
            else
            {
              log.Debug("CoverArt: Album Selection cancelled");
              continue;
            }
            dlgAlbumResults.Dispose();
              }

              // Now update the Cover Art
              if (amazonAlbum != null)
              {
            if (!savedCoverCash.ContainsKey(coverSearchString))
            {
              savedCoverCash.Add(coverSearchString, amazonAlbum);
            }

            // Only write a picture if we don't have a picture OR Overwrite Pictures is set);
            if ((track.Pictures.Count == 0 || Options.MainSettings.OverwriteExistingCovers) && !Options.MainSettings.OnlySaveFolderThumb)
            {
              track.Pictures.Clear();

              ByteVector vector = amazonAlbum.AlbumImage;
              if (vector != null)
              {
                MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture();
                pic.MimeType = "image/jpg";
                pic.Description = "Front Cover";
                pic.Type = PictureType.FrontCover;
                pic.Data = vector.Data;

                if (Options.MainSettings.ChangeCoverSize && Picture.ImageFromData(pic.Data).Width > Options.MainSettings.MaxCoverWidth)
                {
                  pic.Resize(Options.MainSettings.MaxCoverWidth);
                }

                track.Pictures.Add(pic);
              }

              // And also set the Year from the Release Date delivered by Amazon
              // only if not present in Track
              if (amazonAlbum.Year != null)
              {
                string strYear = amazonAlbum.Year;
                if (strYear.Length > 4)
                  strYear = strYear.Substring(0, 4);

                int year = 0;
                try
                {
                  year = Convert.ToInt32(strYear);
                }
                catch (Exception) { }
                if (year > 0 && track.Year == 0)
                  track.Year = year;
              }

              SetBackgroundColorChanged(row.Index);
              track.Changed = true;
              Options.Songlist[row.Index] = track;
              _itemsChanged = true;
              _main.SetGalleryItem();
            }
              }

              // If the user has selected to store only the folder thumb, without touching the file
              if (amazonAlbum != null && Options.MainSettings.OnlySaveFolderThumb)
              {
            ByteVector vector = amazonAlbum.AlbumImage;
            if (vector != null)
            {
              string fileName = Path.Combine(Path.GetDirectoryName(track.FullFileName), "folder.jpg");
              try
              {
                MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture();
                if (Options.MainSettings.ChangeCoverSize && Picture.ImageFromData(pic.Data).Width > Options.MainSettings.MaxCoverWidth)
                {
                  pic.Resize(Options.MainSettings.MaxCoverWidth);
                }

                Image img = Picture.ImageFromData(vector.Data);

                // Need to make a copy, otherwise we have a GDI+ Error
                Bitmap bmp = new Bitmap(img);
                bmp.Save(fileName, ImageFormat.Jpeg);

                FileInfo fi = new FileInfo(fileName);
                _nonMusicFiles.RemoveAll(f => f.Name == fi.Name);
                _nonMusicFiles.Add(fi);
                _main.MiscInfoPanel.AddNonMusicFiles(_nonMusicFiles);
              }
              catch (Exception ex)
              {
                log.Error("Exception Saving picture: {0} {1}", fileName, ex.Message);
              }
              break;
            }
              }
            }
            catch (Exception ex)
            {
              Options.Songlist[row.Index].Status = 2;
              AddErrorMessage(row, ex.Message);
            }
              }

              Util.SendProgress("");
              tracksGrid.Refresh();
              tracksGrid.Parent.Refresh();
              _main.TagEditForm.FillForm();

              ResetProgressBar();

              log.Trace("<<<");
        }
        /// <summary>
        ///   Tag the the Selected files from Internet
        /// </summary>
        private void IdentifyFilesThread(object sender, DoWorkEventArgs e)
        {
            log.Trace(">>>");
              //Make calls to Tracksgrid Threadsafe
              if (tracksGrid.InvokeRequired)
              {
            ThreadSafeGridDelegate1 d = IdentifyFilesThread;
            tracksGrid.Invoke(d, new[] { sender, e });
            return;
              }

              int count = 0;
              int trackCount = tracksGrid.SelectedRows.Count;
              SetProgressBar(trackCount);

              MusicBrainzAlbum musicBrainzAlbum = new MusicBrainzAlbum();

              foreach (DataGridViewRow row in tracksGrid.Rows)
              {
            ClearStatusColumn(row.Index);

            if (!row.Selected)
            {
              continue;
            }

            count++;
            try
            {
              Application.DoEvents();
              _main.progressBar1.Value += 1;
              if (_progressCancelled)
              {
            ResetProgressBar();
            return;
              }
              TrackData track = Options.Songlist[row.Index];

              using (MusicBrainzTrackInfo trackinfo = new MusicBrainzTrackInfo())
              {
            Util.SendProgress(string.Format("Identifying file {0}", track.FileName));
            log.Debug("Identify: Processing file: {0}", track.FullFileName);
            List<MusicBrainzTrack> musicBrainzTracks = trackinfo.GetMusicBrainzTrack(track.FullFileName);

            if (musicBrainzTracks == null)
            {
              log.Debug("Identify: Couldn't identify file");
              continue;
            }

            if (musicBrainzTracks.Count > 0)
            {
              MusicBrainzTrack musicBrainzTrack = null;
              if (musicBrainzTracks.Count == 1)
                musicBrainzTrack = musicBrainzTracks[0];
              else
              {
                // Skip the Album selection, if the album been selected already for a previous track
                bool albumFound = false;
                foreach (MusicBrainzTrack mbtrack in musicBrainzTracks)
                {
                  if (mbtrack.AlbumID == musicBrainzAlbum.Id)
                  {
                    albumFound = true;
                    musicBrainzTrack = mbtrack;
                    break;
                  }
                }

                if (!albumFound)
                {
                  MusicBrainzAlbumResults dlgAlbumResults = new MusicBrainzAlbumResults(musicBrainzTracks);
                  dlgAlbumResults.Owner = _main;
                  if (_main.ShowModalDialog(dlgAlbumResults) == DialogResult.OK)
                  {
                    if (dlgAlbumResults.SelectedListItem > -1)
                      musicBrainzTrack = musicBrainzTracks[dlgAlbumResults.SelectedListItem];
                    else
                      musicBrainzTrack = musicBrainzTracks[0];
                  }
                  dlgAlbumResults.Dispose();
                }
              }

              // We didn't get a track
              if (musicBrainzTrack == null)
              {
                log.Debug("Identify: No information returned from Musicbrainz");
                continue;
              }

              // Are we still at the same album?
              // if not, get the album, so that we have the release date
              if (musicBrainzAlbum.Id != musicBrainzTrack.AlbumID)
              {
                using (MusicBrainzAlbumInfo albumInfo = new MusicBrainzAlbumInfo())
                {
                  Application.DoEvents();
                  if (_progressCancelled)
                  {
                    ResetProgressBar();
                    return;
                  }
                  musicBrainzAlbum = albumInfo.GetMusicBrainzAlbumById(musicBrainzTrack.AlbumID.ToString());
                }
              }

              track.Title = musicBrainzTrack.Title;
              track.Artist = musicBrainzTrack.Artist;
              track.Album = musicBrainzTrack.Album;
              track.Track = musicBrainzTrack.Number.ToString();

              if (musicBrainzAlbum.Year != null && musicBrainzAlbum.Year.Length >= 4)
                track.Year = Convert.ToInt32(musicBrainzAlbum.Year.Substring(0, 4));

              // Do we have a valid Amazon Album?
              if (musicBrainzAlbum.Amazon != null)
              {
                // Only write a picture if we don't have a picture OR Overwrite Pictures is set
                if (track.Pictures.Count == 0 || Options.MainSettings.OverwriteExistingCovers)
                {
                  ByteVector vector = musicBrainzAlbum.Amazon.AlbumImage;
                  if (vector != null)
                  {
                    MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture();
                    pic.MimeType = "image/jpg";
                    pic.Description = "";
                    pic.Type = PictureType.FrontCover;
                    pic.Data = vector.Data;
                    track.Pictures.Add(pic);
                  }
                }
              }

              SetBackgroundColorChanged(row.Index);
              track.Changed = true;
              Options.Songlist[row.Index] = track;
              _itemsChanged = true;
            }
              }
            }
            catch (Exception ex)
            {
              Options.Songlist[row.Index].Status = 2;
              AddErrorMessage(row, ex.Message);
            }
              }

              Util.SendProgress("");
              tracksGrid.Refresh();
              tracksGrid.Parent.Refresh();
              _main.TagEditForm.FillForm();

              ResetProgressBar();

              log.Trace("<<<");
        }
Example #4
0
        /// <summary>
        /// Read the Tags from the File 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static TrackData Create(string fileName)
        {
            TrackData track = new TrackData();
              TagLib.File file = null;
              bool error = false;

              try
              {
            TagLib.ByteVector.UseBrokenLatin1Behavior = true;
            file = TagLib.File.Create(fileName);
              }
              catch (CorruptFileException)
              {
            log.Warn("File Read: Ignoring track {0} - Corrupt File!", fileName);
            error = true;
              }
              catch (UnsupportedFormatException)
              {
            log.Warn("File Read: Ignoring track {0} - Unsupported format!", fileName);
            error = true;
              }
              catch (FileNotFoundException)
              {
            log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", fileName);
            error = true;
              }
              catch (Exception ex)
              {
            log.Error("File Read: Error processing file: {0} {1}", fileName, ex.Message);
            error = true;
              }

              if (error)
              {
            return null;
              }

              TagLib.Id3v2.Tag id3v2tag = null;
              try
              {
            if (file.MimeType.Substring(file.MimeType.IndexOf("/") + 1) == "mp3")
            {
              id3v2tag = file.GetTag(TagTypes.Id3v2, false) as TagLib.Id3v2.Tag;
            }
              }
              catch (Exception ex)
              {
            log.Error("File Read: Error retrieving id3tag: {0} {1}", fileName, ex.Message);
            return null;
              }

              #region Set Common Values

              FileInfo fi = new FileInfo(fileName);
              try
              {
            track.Id = new Guid();
            track.FullFileName = fileName;
            track.FileName = Path.GetFileName(fileName);
            track.Readonly = fi.IsReadOnly;
            track.TagType = file.MimeType.Substring(file.MimeType.IndexOf("/") + 1);
              }
              catch (Exception ex)
              {
            log.Error("File Read: Error setting Common tags: {0} {1}", fileName, ex.Message);
            return null;
              }
              #endregion

              #region Set Tags

              try
              {
            // Artist
            track.Artist = String.Join(";", file.Tag.Performers);
            if (track.Artist.Contains("AC;DC"))
            {
              track.Artist = track.Artist.Replace("AC;DC", "AC/DC");
            }

            track.AlbumArtist = String.Join(";", file.Tag.AlbumArtists);
            if (track.AlbumArtist.Contains("AC;DC"))
            {
              track.AlbumArtist = track.AlbumArtist.Replace("AC;DC", "AC/DC");
            }

            track.Album = file.Tag.Album ?? "";
            track.BPM = (int)file.Tag.BeatsPerMinute;
            track.Compilation = id3v2tag == null ? false : id3v2tag.IsCompilation;
            track.Composer = string.Join(";", file.Tag.Composers);
            track.Conductor = file.Tag.Conductor ?? "";
            track.Copyright = file.Tag.Copyright ?? "";

            track.DiscNumber = file.Tag.Disc;
            track.DiscCount = file.Tag.DiscCount;

            track.Genre = string.Join(";", file.Tag.Genres);
            track.Grouping = file.Tag.Grouping ?? "";
            track.Title = file.Tag.Title ?? "";

            track.TrackNumber = file.Tag.Track;
            track.TrackCount = file.Tag.TrackCount;
            track.Year = (int)file.Tag.Year;

            // Pictures
            foreach (IPicture picture in file.Tag.Pictures)
            {
              MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture
              {
            Type = picture.Type,
            MimeType = picture.MimeType,
            Description = picture.Description
              };

              pic.Data = pic.ImageFromData(picture.Data.Data);
              track.Pictures.Add(pic);
            }

            // Comments
            if (track.TagType == "mp3" && id3v2tag != null)
            {
              foreach (CommentsFrame commentsframe in id3v2tag.GetFrames<CommentsFrame>())
              {
            track.ID3Comments.Add(new Comment(commentsframe.Description, commentsframe.Language, commentsframe.Text));
              }
            }
            else
            {
              track.Comment = file.Tag.Comment;
            }

            // Lyrics
            track.Lyrics = file.Tag.Lyrics;
            if (track.TagType == "mp3" && id3v2tag != null)
            {
              foreach (UnsynchronisedLyricsFrame lyricsframe in id3v2tag.GetFrames<UnsynchronisedLyricsFrame>())
              {
            // Only add non-empty Frames
            if (lyricsframe.Text != "")
            {
              track.LyricsFrames.Add(new Lyric(lyricsframe.Description, lyricsframe.Language, lyricsframe.Text));
            }
              }
            }

            // Rating
            if (track.TagType == "mp3")
            {
              TagLib.Id3v2.PopularimeterFrame popmFrame = null;
              // First read in all POPM Frames found
              if (id3v2tag != null)
              {
            foreach (PopularimeterFrame popmframe in id3v2tag.GetFrames<PopularimeterFrame>())
            {
              // Only add valid POPM Frames
              if (popmframe.User != "" && popmframe.Rating > 0)
              {
                track.Ratings.Add(new PopmFrame(popmframe.User, (int)popmframe.Rating, (int)popmframe.PlayCount));
              }
            }

            popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, "MPTagThat", false);
            if (popmFrame != null)
            {
              track.Rating = popmFrame.Rating;
            }
              }

              if (popmFrame == null)
              {
            // Now check for Ape Rating
            TagLib.Ape.Tag apetag = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag;
            TagLib.Ape.Item apeItem = apetag.GetItem("RATING");
            if (apeItem != null)
            {
              string rating = apeItem.ToString();
              try
              {
                track.Rating = Convert.ToInt32(rating);
              }
              catch (Exception)
              { }
            }
              }
            }
            else
            {
              if (track.TagType == "ape")
              {
            TagLib.Ape.Tag apetag = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag;
            TagLib.Ape.Item apeItem = apetag.GetItem("RATING");
            if (apeItem != null)
            {
              string rating = apeItem.ToString();
              try
              {
                track.Rating = Convert.ToInt32(rating);
              }
              catch (Exception)
              { }
            }
              }
            }

              }
              catch (Exception ex)
              {
            log.Error("Exception setting Tags for file: {0}. {1}", fileName, ex.Message);
              }

              #endregion

              #region Set Properties

              try
              {
            track.DurationTimespan = file.Properties.Duration;

            int fileLength = (int) (fi.Length/1024);
            track.FileSize = fileLength.ToString();

            track.BitRate = file.Properties.AudioBitrate.ToString();
            track.SampleRate = file.Properties.AudioSampleRate.ToString();
            track.Channels = file.Properties.AudioChannels.ToString();
            track.Version = file.Properties.Description;
            track.CreationTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.CreationTime);
            track.LastWriteTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.LastWriteTime);
              }
              catch (Exception ex)
              {
            log.Error("Exception setting Properties for file: {0}. {1}", fileName, ex.Message);
              }

              #endregion

              // Now copy all Text frames of an ID3 V2
              try
              {
            if (track.TagType == "mp3" && id3v2tag != null)
            {
              foreach (TagLib.Id3v2.Frame frame in id3v2tag.GetFrames())
              {
            string id = frame.FrameId.ToString();
            if (!track.StandardFrames.Contains(id) && track.ExtendedFrames.Contains(id))
            {
              track.Frames.Add(new Frame(id, "", frame.ToString()));
            }
            else if (!track.StandardFrames.Contains(id) && !track.ExtendedFrames.Contains(id))
            {
              if (frame.GetType() == typeof (UserTextInformationFrame))
              {
                track.UserFrames.Add(new Frame(id, (frame as UserTextInformationFrame).Description ?? "",
                                               (frame as UserTextInformationFrame).Text.Length == 0
                                                 ? ""
                                                 : (frame as UserTextInformationFrame).Text[0]));
              }
              else if (frame.GetType() == typeof (PrivateFrame))
              {
                track.UserFrames.Add(new Frame(id, (frame as PrivateFrame).Owner ?? "",
                                               (frame as PrivateFrame).PrivateData == null
                                                 ? ""
                                                 : (frame as PrivateFrame).PrivateData.ToString()));
              }
              else if (frame.GetType() == typeof (UniqueFileIdentifierFrame))
              {
                track.UserFrames.Add(new Frame(id, (frame as UniqueFileIdentifierFrame).Owner ?? "",
                                               (frame as UniqueFileIdentifierFrame).Identifier == null
                                                 ? ""
                                                 : (frame as UniqueFileIdentifierFrame).Identifier.ToString()));
              }
              else if (frame.GetType() == typeof (UnknownFrame))
              {
                track.UserFrames.Add(new Frame(id, "",
                                               (frame as UnknownFrame).Data == null
                                                 ? ""
                                                 : (frame as UnknownFrame).Data.ToString()));
              }
              else
              {
                track.UserFrames.Add(new Frame(id, "", frame.ToString()));
              }
            }
              }

              track.ID3Version = id3v2tag.Version;
            }
              }
              catch (Exception ex)
              {
            log.Error("Exception getting User Defined frames for file: {0}. {1}", fileName, ex.Message);
              }

              return track;
        }