Beispiel #1
0
        // ------------------------------------------------------------------------------------------

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="path">Path of the file to be parsed</param>
        public AudioFileIO(string path, bool readEmbeddedPictures, bool readAllMetaFrames = false)
        {
            byte alternate = 0;
            bool found     = false;

            thePath = path;

            audioData    = AudioDataIOFactory.GetInstance().GetDataReader(path, alternate);
            audioManager = new AudioDataManager(audioData);
            found        = audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);

            while (!found && alternate < AudioDataIOFactory.MAX_ALTERNATES)
            {
                alternate++;
                audioData    = AudioDataIOFactory.GetInstance().GetDataReader(path, alternate);
                audioManager = new AudioDataManager(audioData);
                found        = audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);
            }

            metaData = MetaDataIOFactory.GetInstance().GetMetaReader(audioManager);

            if (metaData is DummyTag && (0 == audioManager.getAvailableMetas().Count))
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "Could not find any metadata");
            }
        }
Beispiel #2
0
        public bool RemoveTagFromFile(int tagType)
        {
            bool result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, bufferSize, fileOptions))
                    using (BinaryReader reader = new BinaryReader(fs))
                    {
                        result = read(reader, false, false, true);

                        IMetaDataIO metaIO = getMeta(tagType);
                        if (metaIO.Exists)
                        {
                            using (BinaryWriter writer = new BinaryWriter(fs))
                            {
                                metaIO.Remove(writer);
                            }
                        }
                    }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
Beispiel #3
0
        private static void writeSizeAndNullTerminatedString(string key, string value, BinaryWriter w, IDictionary <string, string> writtenFields)
        {
            if (key.Length > 4)
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "'" + key + "' : LIST.INFO field key must be 4-characters long; cropping");
                key = Utils.BuildStrictLengthString(key, 4, ' ');
            }
            else if (key.Length < 4)
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "'" + key + "' : LIST.INFO field key must be 4-characters long; completing with whitespaces");
                key = Utils.BuildStrictLengthString(key, 4, ' ');
            }
            w.Write(Utils.Latin1Encoding.GetBytes(key));

            byte[] buffer = Utils.Latin1Encoding.GetBytes(value);
            // Needs one byte of padding if data size is odd
            int paddingByte = ((buffer.Length + 1) % 2 > 0) ? 1 : 0;

            w.Write(buffer.Length + 1 + paddingByte);
            w.Write(buffer);
            w.Write((byte)0); // String is null-terminated
            if (paddingByte > 0)
            {
                w.Write((byte)0);
            }

            writtenFields.Add("info." + key, value);
        }
Beispiel #4
0
        /// <summary>
        /// Construct picture information from its parts
        /// </summary>
        /// <param name="tagType">Type of the containing tag (see static fields in <see cref="ATL.AudioData.MetaDataIOFactory"/></param>
        /// <param name="nativePicCode">Native code of the picture, as stated in its containing format's specs</param>
        /// <param name="position">Position of the picture among the other pictures of the same file (default : 1)</param>
        public PictureInfo(int tagType, object nativePicCode, int position = 1)
        {
            PicType      = PIC_TYPE.Unsupported;
            NativeFormat = ImageFormat.Undefined;
            TagType      = tagType;
            Position     = position;

            string picCodeStr = nativePicCode as string;

            if (picCodeStr != null)
            {
                NativePicCodeStr = picCodeStr;
                NativePicCode    = -1;
            }
            else if (nativePicCode is byte)
            {
                NativePicCode = (byte)nativePicCode;
            }
            else if (nativePicCode is int)
            {
                NativePicCode = (int)nativePicCode;
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "nativePicCode type is not supported; expected byte, int or string; found " + nativePicCode.GetType().Name);
            }
        }
Beispiel #5
0
        public bool ReadFromFile(bool readEmbeddedPictures = false, bool readAllMetaFrames = false)
        {
            bool result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            resetData();

            try
            {
                // Open file, read first block of data and search for a frame
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, fileOptions))
                    using (BinaryReader source = new BinaryReader(fs))
                    {
                        result = read(source, readEmbeddedPictures, readAllMetaFrames);
                    }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// Construct picture information from its parts
        /// </summary>
        /// <param name="picType">Type of the picture</param>
        /// <param name="tagType">Type of the containing tag (see static fields in <see cref="ATL.AudioData.MetaDataIOFactory"/></param>
        /// <param name="nativePicCode">Native code of the picture, as stated in its containing format's specs</param>
        /// <param name="position">Position of the picture among the other pictures of the same file</param>
        /// <param name="binaryData">Raw binary data of the picture</param>
        private PictureInfo(PIC_TYPE picType, int tagType, object nativePicCode, int position, byte[] binaryData)
        {
            PicType  = picType;
            TagType  = tagType;
            Position = position;

            string picCodeStr = nativePicCode as string;

            if (picCodeStr != null)
            {
                NativePicCodeStr = picCodeStr;
                NativePicCode    = -1;
            }
            else if (nativePicCode is byte)
            {
                NativePicCode = (byte)nativePicCode;
            }
            else if (nativePicCode is int)
            {
                NativePicCode = (int)nativePicCode;
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "nativePicCode type is not supported; expected byte, int or string; found " + nativePicCode.GetType().Name);
            }
            PictureData  = binaryData;
            NativeFormat = ImageUtils.GetImageFormatFromPictureHeader(PictureData);
        }
Beispiel #7
0
        private void GetReferenceLocation(Boolean inLocation, Boolean inImage, XmlReader source)
        {
            IsUri = true;
            if (!inLocation && !inImage)
            {
                return;
            }
            try
            {
                var uri = new Uri(source.Value);
                if (!uri.IsFile || !inLocation)
                {
                    return;
                }
                if (!System.IO.Path.IsPathRooted(uri.LocalPath))
                {
                    var absolute = System.IO.Path.Combine(
                        System.IO.Path.GetDirectoryName(FFileName), uri.LocalPath);
                    UpdateFile(uri.LocalPath, new Uri(absolute).AbsoluteUri);
                    Files.Add(absolute);
                }
                else
                {
                    Files.Add(uri.LocalPath);
                }

                //else if (inImage) result.Add(System.IO.Path.GetFullPath(uri.LocalPath));
                //TODO fetch track picture from playlists info ?
            }
            catch (UriFormatException)
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING,
                                              Files + " is not a valid URI [" + FFileName + "]");
            }
        }
        public bool ReadFromFile(TagData.PictureStreamHandlerDelegate pictureStreamHandler, bool readAllMetaFrames = false)
        {
            bool result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            resetData();

            try
            {
                // Open file, read first block of data and search for a frame
                Stream       s      = (null == stream) ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, fileOptions) : stream;
                BinaryReader source = new BinaryReader(s);
                try
                {
                    result = read(source, pictureStreamHandler, readAllMetaFrames);
                }
                finally
                {
                    if (null == stream)
                    {
                        source.Close();
                    }
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stream">Stream to access in-memory data to be parsed</param>
        /// <param name="mimeType">the file's mime type.</param>
        /// <param name="readEmbeddedPictures">Embedded pictures will be read if true; ignored if false</param>
        /// <param name="readAllMetaFrames">All metadata frames (including unmapped ones) will be read if true; ignored if false</param>
        public AudioFileIo(Stream stream, String mimeType, Boolean readEmbeddedPictures, Boolean readAllMetaFrames = false)
        {
            Byte alternate = 0;
            var  found     = false;

            _audioData = AudioDataIoFactory.GetInstance().GetFromMimeType(mimeType, "In-memory", alternate);

            _audioManager = new AudioDataManager(_audioData, stream);
            found         = _audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);

            while (!found && alternate < AudioDataIoFactory.MaxAlternates)
            {
                alternate++;
                _audioData    = AudioDataIoFactory.GetInstance().GetFromMimeType(mimeType, "In-memory", alternate);
                _audioManager = new AudioDataManager(_audioData, stream);
                found         = _audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);
            }

            _metaData = MetaDataIOFactory.GetInstance().GetMetaReader(_audioManager);

            if (_metaData is DummyTag && (0 == _audioManager.getAvailableMetas().Count))
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "Could not find any metadata");
            }
        }
Beispiel #10
0
        private String getResourceLocation(XmlTextReader source)
        {
            String result = "";

            while (source.MoveToNextAttribute()) // Read the attributes.
            {
                if (source.Name.Equals("href", StringComparison.OrdinalIgnoreCase))
                {
                    result = source.Value;

                    if (result.Contains("://") && Uri.IsWellFormedUriString(result, UriKind.RelativeOrAbsolute))
                    {
                        try
                        {
                            Uri uri = new Uri(result);
                            if (uri.IsFile)
                            {
                                result = uri.LocalPath;
                            }
                        }
                        catch (UriFormatException)
                        {
                            LogDelegator.GetLogDelegate()(Log.LV_WARNING, result + " is not a valid URI [" + FFileName + "]");
                        }
                    }

                    if (!System.IO.Path.IsPathRooted(result))
                    {
                        result = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(FFileName), result);
                    }
                }
            }
            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stream">Stream to access in-memory data to be parsed</param>
        /// <param name="mimeType">Mime-type of the stream to process</param>
        /// <param name="readEmbeddedPictures">Embedded pictures will be read if true; ignored if false</param>
        /// <param name="readAllMetaFrames">All metadata frames (including unmapped ones) will be read if true; ignored if false</param>
        /// <param name="writeProgress">Object to use to signal writing progress (optional)</param>
        public AudioFileIO(Stream stream, String mimeType, bool readEmbeddedPictures, bool readAllMetaFrames = false, IProgress <float> writeProgress = null)
        {
            byte alternate = 0;
            bool found     = false;

            audioData = AudioDataIOFactory.GetInstance().GetFromMimeType(mimeType, "In-memory", alternate);

            audioManager       = new AudioDataManager(audioData, stream, writeProgress);
            this.writeProgress = writeProgress;
            found = audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);

            while (!found && alternate < AudioDataIOFactory.MAX_ALTERNATES)
            {
                alternate++;
                audioData    = AudioDataIOFactory.GetInstance().GetFromMimeType(mimeType, "In-memory", alternate);
                audioManager = new AudioDataManager(audioData, stream, writeProgress);
                found        = audioManager.ReadFromFile(readEmbeddedPictures, readAllMetaFrames);
            }

            metaData = MetaDataIOFactory.GetInstance().GetMetaReader(audioManager);

            if (metaData is DummyTag && (0 == audioManager.getAvailableMetas().Count))
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "Could not find any metadata");
            }
        }
Beispiel #12
0
        /* Nightmarish implementation to be redone when Vendor ID is really useful
         *      private static String findVendorID(byte[] Data, int Size)
         *      {
         *              String VendorID;
         *              String result = "";
         *
         *              // Search for vendor ID
         *              if ( (Data.Length - Size - 8) < 0 ) Size = Data.Length - 8;
         *              for (int i=0; i <= Size; i++)
         *              {
         *      VendorID = Utils.Latin1Encoding.GetString(Data, Data.Length - i - 8, 4);
         *                      if (VENDOR_ID_LAME == VendorID)
         *                      {
         *          result = VendorID + Utils.Latin1Encoding.GetString(Data, Data.Length - i - 4, 4);
         *                              break;
         *                      }
         *                      else if (VENDOR_ID_GOGO_NEW == VendorID)
         *                      {
         *                              result = VendorID;
         *                              break;
         *                      }
         *              }
         *              return result;
         *      }
         */

        /* Unused for now
         *
         *      private String getVersion()
         *      {
         *          // Get MPEG version name
         *          return MPEG_VERSION[HeaderFrame.VersionID];
         *      }
         *
         *      private String getLayer()
         *      {
         *          // Get MPEG layer name
         *          return MPEG_LAYER[HeaderFrame.LayerID];
         *      }
         *
         *      private String getChannelMode()
         *      {
         *          // Get channel mode name
         *          return MPEG_CM_MODE[HeaderFrame.ModeID];
         *      }
         *
         *      private String getEmphasis()
         *      {
         *          // Get emphasis name
         *          return MPEG_EMPHASIS[HeaderFrame.EmphasisID];
         *      }
         *
         *      private long getFrames()
         *      {
         *          // Get total number of frames, calculate if VBR header not found
         *          if (vbrData.Found) return vbrData.Frames;
         *          else
         *          {
         *              long MPEGSize = sizeInfo.FileSize - sizeInfo.ID3v2Size - sizeInfo.ID3v1Size - sizeInfo.APESize;
         *
         *              return (long)Math.Floor(1.0*(MPEGSize - HeaderFrame.Position) / getFrameSize(HeaderFrame));
         *          }
         *      }
         *
         *      private byte getVBREncoderID()
         *      {
         *          // Guess VBR encoder and get ID
         *          byte result = 0;
         *
         *          if (VENDOR_ID_LAME == vbrData.VendorID.Substring(0, 4))
         *              result = MPEG_ENCODER_LAME;
         *          if (VENDOR_ID_GOGO_NEW == vbrData.VendorID.Substring(0, 4))
         *              result = MPEG_ENCODER_GOGO;
         *          if (VENDOR_ID_GOGO_OLD == vbrData.VendorID.Substring(0, 4))
         *              result = MPEG_ENCODER_GOGO;
         *          if ( StreamUtils.StringEqualsArr(VBR_ID_XING,vbrData.ID) &&
         *              (vbrData.VendorID.Substring(0, 4) != VENDOR_ID_LAME) &&
         *              (vbrData.VendorID.Substring(0, 4) != VENDOR_ID_GOGO_NEW) &&
         *              (vbrData.VendorID.Substring(0, 4) != VENDOR_ID_GOGO_OLD) )
         *              result = MPEG_ENCODER_XING;
         *          if ( StreamUtils.StringEqualsArr(VBR_ID_FHG,vbrData.ID))
         *              result = MPEG_ENCODER_FHG;
         *
         *          return result;
         *      }
         *
         *      private byte getCBREncoderID()
         *      {
         *          // Guess CBR encoder and get ID
         *          byte result = MPEG_ENCODER_FHG;
         *
         *          if ( (HeaderFrame.OriginalBit) &&
         *              (HeaderFrame.ProtectionBit) )
         *              result = MPEG_ENCODER_LAME;
         *          if ( (getBitRate(HeaderFrame) <= 160) &&
         *              (MPEG_CM_STEREO == HeaderFrame.ModeID))
         *              result = MPEG_ENCODER_BLADE;
         *          if ((HeaderFrame.CopyrightBit) &&
         *              (HeaderFrame.OriginalBit) &&
         *              (! HeaderFrame.ProtectionBit) )
         *              result = MPEG_ENCODER_XING;
         *          if ((HeaderFrame.Xing) &&
         *              (HeaderFrame.OriginalBit) )
         *              result = MPEG_ENCODER_XING;
         *          if (MPEG_LAYER_II == HeaderFrame.LayerID)
         *              result = MPEG_ENCODER_QDESIGN;
         *          if ((MPEG_CM_DUAL_CHANNEL == HeaderFrame.ModeID) &&
         *              (HeaderFrame.ProtectionBit) )
         *              result = MPEG_ENCODER_SHINE;
         *          if (VENDOR_ID_LAME == vendorID.Substring(0, 4))
         *              result = MPEG_ENCODER_LAME;
         *          if (VENDOR_ID_GOGO_NEW == vendorID.Substring(0, 4))
         *              result = MPEG_ENCODER_GOGO;
         *
         *          return result;
         *      }
         *
         *      private byte getEncoderID()
         *      {
         *          // Get guessed encoder ID
         *          if (HeaderFrame.Found)
         *              if (vbrData.Found) return getVBREncoderID();
         *              else return getCBREncoderID();
         *          else
         *              return 0;
         *      }
         *
         *      private String getEncoder()
         *      {
         *          String VendorID = "";
         *          String result;
         *
         *          // Get guessed encoder name and encoder version for LAME
         *          result = MPEG_ENCODER[getEncoderID()];
         *          if (vbrData.VendorID != "") VendorID = vbrData.VendorID;
         *          if (vendorID != "") VendorID = vendorID;
         *          if ( (MPEG_ENCODER_LAME == getEncoderID()) &&
         *              (VendorID.Length >= 8) &&
         *              Char.IsDigit(VendorID[4]) &&
         *              (VendorID[5] == '.') &&
         *              (Char.IsDigit(VendorID[6]) &&
         *              Char.IsDigit(VendorID[7]) ))
         *              result =
         *                  result + (char)32 +
         *                  VendorID[4] +
         *                  VendorID[5] +
         *                  VendorID[6] +
         *                  VendorID[7];
         *          return result;
         *      }
         *
         *      private bool getValid()
         *      {
         *          // Check for right MPEG file data
         *          return
         *              ((HeaderFrame.Found) &&
         *              (getBitRate() >= MIN_MPEG_BIT_RATE) &&
         *              (getBitRate() <= MAX_MPEG_BIT_RATE) &&
         *              (getDuration() >= MIN_ALLOWED_DURATION));
         *      }*/

        public bool Read(BinaryReader source, SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams)
        {
            this.sizeInfo = sizeInfo;
            resetData();

            bool result = false;

            BufferedBinaryReader reader = new BufferedBinaryReader(source.BaseStream);

            reader.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin);
            HeaderFrame = findFrame(reader, ref vbrData, sizeInfo);

            // Search for vendor ID at the end if CBR encoded

            /*
             *  This is a nightmarish implementation; to be redone when vendor ID is required by upper interfaces
             *
             *          if ( (HeaderFrame.Found) && (! FVBR.Found) )
             *          {
             *              fs.Seek(sizeInfo.FileSize - Data.Length - sizeInfo.ID3v1Size - sizeInfo.APESize, SeekOrigin.Begin);
             *              fs.Read(Data, 0, Data.Length);
             *              vendorID = findVendorID(Data, HeaderFrame.Size * 5);
             *          }
             */
            result = HeaderFrame.Found;

            if (!result)
            {
                resetData();
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Could not detect MPEG Audio header starting @ " + sizeInfo.ID3v2Size);
            }

            return(result);
        }
Beispiel #13
0
 private void parseLocation(XmlReader source, IList <string> result)
 {
     source.Read();
     if (source.NodeType == XmlNodeType.Text)
     {
         try
         {
             Uri uri = new Uri(source.Value);
             if (uri.IsFile)
             {
                 if (!System.IO.Path.IsPathRooted(uri.LocalPath))
                 {
                     result.Add(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(FFileName), uri.LocalPath));
                 }
                 else
                 {
                     result.Add(uri.LocalPath);
                 }
             }
         }
         catch (UriFormatException)
         {
             LogDelegator.GetLogDelegate()(Log.LV_WARNING, result + " is not a valid URI [" + FFileName + "]");
         }
     }
 }
Beispiel #14
0
        public void Log_Location_MultiThread()
        {
            messages.Clear();

            Thread thread = new Thread(log_Location_MultiThread_sub);

            thread.Start();

            LogDelegator.GetLocateDelegate()("here");
            LogDelegator.GetLogDelegate()(Log.LV_ERROR, "testI");
            LogDelegator.GetLogDelegate()(Log.LV_ERROR, "testD");

            Thread.Sleep(200);

            Assert.AreEqual(messages.Count, 4);
            foreach (Log.LogItem logItem in messages)
            {
                if (logItem.Level.Equals(Log.LV_WARNING))
                {
                    Assert.AreEqual(logItem.Location, "over there");
                }
                if (logItem.Level.Equals(Log.LV_ERROR))
                {
                    Assert.AreEqual(logItem.Location, "here");
                }
            }
        }
Beispiel #15
0
        public bool UpdateTagInFile(TagData theTag, int tagType)
        {
            bool        result = true;
            IMetaDataIO theMetaIO;

            LogDelegator.GetLocateDelegate()(fileName);
            theTag.DurationMs = audioDataIO.Duration;

            if (audioDataIO.IsMetaSupported(tagType))
            {
                try
                {
                    theMetaIO = getMeta(tagType);

                    Stream       s = (null == stream) ? new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, bufferSize, fileOptions) : stream;
                    BinaryReader r = new BinaryReader(s);
                    BinaryWriter w = new BinaryWriter(s);
                    try
                    {
                        // If current file can embed metadata, do a 1st pass to detect embedded metadata position
                        if (audioDataIO is IMetaDataEmbedder)
                        {
                            MetaDataIO.ReadTagParams readTagParams = new MetaDataIO.ReadTagParams(false, false);
                            readTagParams.PrepareForWriting = true;

                            audioDataIO.Read(r, sizeInfo, readTagParams);
                            theMetaIO.SetEmbedder((IMetaDataEmbedder)audioDataIO);
                        }

                        result = theMetaIO.Write(r, w, theTag, writeProgress);
                        if (result)
                        {
                            setMeta(theMetaIO);
                        }
                    } finally
                    {
                        if (null == stream)
                        {
                            r.Close();
                            w.Close();
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.Message);
                    System.Console.WriteLine(e.StackTrace);
                    LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                    result = false;
                }
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_DEBUG, "Tag type " + tagType + " not supported");
            }

            return(result);
        }
Beispiel #16
0
        public void Log_Sync()
        {
            messages.Clear();

            LogDelegator.GetLogDelegate()(Log.LV_DEBUG, "test message");

            Assert.AreEqual(Log.LV_DEBUG, messages[0].Level);
            Assert.AreEqual("test message", messages[0].Message);
        }
Beispiel #17
0
        public void TestSyncMessage()
        {
            messages.Clear();

            LogDelegator.GetLocateDelegate()("file name");
            LogDelegator.GetLogDelegate()(Log.LV_DEBUG, "test message 1");
            LogDelegator.GetLogDelegate()(Log.LV_WARNING, "test message 2");

            System.Console.WriteLine(messages[0].Message);
        }
Beispiel #18
0
        // ---------------------------------------------------------------------------

        private bool ReadData(String FileName, ref FileData Data)
        {
            FileStream   fs     = null;
            BinaryReader Source = null;

            char[] ID = new char[16];
            int    ObjectCount;
            int    ObjectSize;
            long   Position;

            bool result;

            // Read file data
            try
            {
                fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                fs.Lock(0, fs.Length);
                Source = new BinaryReader(fs);

                Data.FileSize = (int)fs.Length;

                // Check for existing header
                ID = Utils.ReadTrueChars(Source, 16);

                if (Utils.ArrEqualsArr(WMA_HEADER_ID, ID))
                {
                    fs.Seek(8, SeekOrigin.Current);
                    ObjectCount = Source.ReadInt32();
                    fs.Seek(2, SeekOrigin.Current);
                    // Read all objects in header and get needed data
                    for (int iterator = 0; iterator < ObjectCount; iterator++)
                    {
                        Position   = fs.Position;
                        ID         = Utils.ReadTrueChars(Source, 16);
                        ObjectSize = Source.ReadInt32();
                        ReadObject(ID, Source, ref Data);
                        fs.Seek(Position + ObjectSize, SeekOrigin.Begin);
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }
            if (fs != null)
            {
                fs.Unlock(0, fs.Length);
                fs.Close();
            }
            return(result);
        }
Beispiel #19
0
        public void Log_Location()
        {
            messages.Clear();

            LogDelegator.GetLocateDelegate()("here");
            LogDelegator.GetLogDelegate()(Log.LV_INFO, "test1");
            Assert.AreEqual("here", messages[0].Location);

            LogDelegator.GetLocateDelegate()("there");
            LogDelegator.GetLogDelegate()(Log.LV_INFO, "test2");
            Assert.AreEqual("there", messages[1].Location);
        }
Beispiel #20
0
        public Boolean RemoveTagFromFile(Int32 tagType)
        {
            var result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            try
            {
                var s = (null == stream)
                    ? new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, bufferSize,
                                     fileOptions)
                    : stream;
                var          reader = new BinaryReader(s);
                BinaryWriter writer = null;
                try
                {
                    result = read(reader, false, false, true);

                    var metaIO = getMeta(tagType);
                    if (metaIO.Exists)
                    {
                        writer = new BinaryWriter(s);
                        metaIO.Remove(writer);
                    }
                }
                finally
                {
                    if (null == stream)
                    {
                        reader.Close();
                        if (writer != null)
                        {
                            writer.Close();
                        }
                    }
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                throw new AudioDataCorruptionException(
                          "Possible audio data corruption, check Inner Exception for details", e);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
Beispiel #21
0
        // ---------------------------------------------------------------------------

        // No explicit destructor in C#

        // ---------------------------------------------------------------------------

        // Read data from file
        public bool ReadFromFile(String FileName)
        {
            FileStream   fs     = null;
            BinaryReader Source = null;

            bool result = false;

            FResetData();
            // At first search for tags, then try to recognize header type
            FID3v2.ReadFromFile(FileName);
            FID3v1.ReadFromFile(FileName);
            FAPEtag.ReadFromFile(FileName);
            try
            {
                fs = new FileStream(FileName, FileMode.Open);
                fs.Lock(0, fs.Length);
                Source = new BinaryReader(fs);

                FFileSize     = (int)fs.Length;
                FHeaderTypeID = FRecognizeHeaderType(Source);
                // Read header data
                if (AAC_HEADER_TYPE_ADIF == FHeaderTypeID)
                {
                    FReadADIF(Source);
                }
                if (AAC_HEADER_TYPE_ADTS == FHeaderTypeID)
                {
                    FReadADTS(Source);
                }

                result = true;
            }
            catch (Exception e)
            {
                result = false;
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
            }

            if (fs != null)
            {
                fs.Unlock(0, fs.Length);
                if (Source != null)
                {
                    Source.Close();
                }
            }

            return(result);
        }
Beispiel #22
0
        public void Log_ASync_FlushQueue()
        {
            messages.Clear();

            theLog.SwitchAsync();
            LogDelegator.GetLogDelegate()(Log.LV_DEBUG, "test message");

            Assert.AreEqual(0, messages.Count);
            theLog.FlushQueue();


            Assert.AreEqual(Log.LV_DEBUG, messages[0].Level);
            Assert.AreEqual("test message", messages[0].Message);
        }
Beispiel #23
0
        // Most SMIL sample playlists store resource location with a relative path
        private String GetResourceLocation(XmlReader source)
        {
            var result = "";

            while (source.MoveToNextAttribute()) // Read the attributes.
            {
                if (!source.Name.Equals("src", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                result = source.Value;

                // It it an URI ?
                if (result.Contains("://"))
                {
                    if (Uri.IsWellFormedUriString(result, UriKind.RelativeOrAbsolute))
                    {
                        try
                        {
                            var uri = new Uri(result);
                            if (uri.IsFile)
                            {
                                result = uri.LocalPath;
                            }
                        }
                        catch (UriFormatException)
                        {
                            LogDelegator.GetLogDelegate()(Log.LV_WARNING,
                                                          result + " is not a valid URI [" + FFileName + "]");
                        }
                    }
                    else
                    {
                        result = result.Replace("file:///", "").Replace("file://", "");
                    }
                }

                if (!System.IO.Path.IsPathRooted(result))
                {
                    result = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(FFileName), result);
                }

                result = System.IO.Path.GetFullPath(result);
            }

            return(result);
        }
Beispiel #24
0
        // === PRIVATE METHODS ===

        private bool readHeader(BufferedBinaryReader source, ReadTagParams readTagParams)
        {
            string str;

            if (GYM_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(source.ReadBytes(GYM_SIGNATURE.Length))))
            {
                if (readTagParams.PrepareForWriting)
                {
                    structureHelper.AddZone(source.Position, 416, CORE_SIGNATURE);
                }

                tagExists = true;

                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_ALBUM, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_COPYRIGHT, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "EMULATOR", str));
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "DUMPER", str));
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(256))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, str);

                loopStart = source.ReadUInt32();
                uint packedSize = source.ReadUInt32();
                AudioDataOffset = source.Position;
                AudioDataSize   = sizeInfo.FileSize - AudioDataOffset;

                if (packedSize > 0)
                {
                    LogDelegator.GetLogDelegate()(Log.LV_WARNING, "GZIP-compressed files are not supported"); // will be as soon as I find a sample to test with
                    return(false);
                }

                return(true);
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Not a GYM file");
                return(false);
            }
        }
Beispiel #25
0
        // ********************* Auxiliary functions & voids ********************

        private bool ReadHeader(String FileName, ref TagInfo Tag)
        {
            bool         result     = true;
            FileStream   fs         = null;
            BinaryReader SourceFile = null;

            try
            {
                // Set read-access and open file
                fs         = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                SourceFile = new BinaryReader(fs);

                // Read header and get file size
                Tag.ID       = SourceFile.ReadChars(3);
                Tag.Version  = SourceFile.ReadByte();
                Tag.Revision = SourceFile.ReadByte();
                Tag.Flags    = SourceFile.ReadByte();
                Tag.Size     = SourceFile.ReadBytes(4);

                //BlockRead(SourceFile, Tag, 10, Transferred);

                Tag.FileSize = (int)fs.Length;

                // if transfer is not complete
                //if Transferred < 10 then Result = false;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            if (SourceFile != null)
            {
                SourceFile.Close();
            }
            if (fs != null)
            {
                fs.Close();
            }

            return(result);
        }
Beispiel #26
0
        private void readGd3Tag(BinaryReader source, int offset)
        {
            source.BaseStream.Seek(offset, SeekOrigin.Begin);
            string str;

            if (GD3_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(source.ReadBytes(GD3_SIGNATURE.Length))))
            {
                source.BaseStream.Seek(4, SeekOrigin.Current);                        // Version number
                source.BaseStream.Seek(4, SeekOrigin.Current);                        // Length

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Title (english)
                tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, str);
                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Title (japanese)
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "TITLE_J", str));

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Game name (english)
                tagData.IntegrateValue(TagData.TAG_FIELD_ALBUM, str);
                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Game name (japanese)
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "GAME_J", str));

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // System name (english)
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "SYSTEM", str));
                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // System name (japanese)
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "SYSTEM_J", str));

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Author (english)
                tagData.IntegrateValue(TagData.TAG_FIELD_ARTIST, str);
                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Author (japanese)
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "AUTHOR_J", str));

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Release date
                tagData.IntegrateValue(TagData.TAG_FIELD_RECORDING_DATE, str);

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Dumper
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "DUMPER", str));

                str = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode); // Notes
                tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, str);
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_WARNING, "Not a GD3 footer");
            }
        }
Beispiel #27
0
        public Boolean ReadFromFile(TagData.PictureStreamHandlerDelegate pictureStreamHandler,
                                    Boolean readAllMetaFrames = false)
        {
            var result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            resetData();

            try
            {
                // Open file, read first block of data and search for a frame
                var s = (null == stream)
                    ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, fileOptions)
                    : stream;
                var source = new BinaryReader(s);
                try
                {
                    result = read(source, pictureStreamHandler, readAllMetaFrames);
                }
                finally
                {
                    if (null == stream)
                    {
                        source.Close();
                    }
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                throw new AudioDataCorruptionException(
                          "Possible audio data corruption, check Inner Exception for details", e);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
Beispiel #28
0
        public bool RemoveTagFromFile(int tagType)
        {
            bool result = false;

            LogDelegator.GetLocateDelegate()(fileName);

            try
            {
                Stream       s      = (null == stream) ? new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, bufferSize, fileOptions) : stream;
                BinaryReader reader = new BinaryReader(s);
                BinaryWriter writer = null;
                try
                {
                    result = read(reader, false, false, true);

                    IMetaDataIO metaIO = getMeta(tagType);
                    if (metaIO.Exists)
                    {
                        writer = new BinaryWriter(s);
                        metaIO.Remove(writer);
                    }
                } finally
                {
                    if (null == stream)
                    {
                        reader.Close();
                        if (writer != null)
                        {
                            writer.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
                result = false;
            }

            return(result);
        }
Beispiel #29
0
        public IList <String> GetFiles()
        {
            IList <String> result = new List <String>();

            try
            {
                using (FileStream fs = new FileStream(FFileName, FileMode.Open, FileAccess.Read))
                {
                    GetFiles(fs, result);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.StackTrace);
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message + " (" + FFileName + ")");
            }

            return(result);
        }
Beispiel #30
0
        protected override Boolean read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
        {
            var result = true;

            resetData();

            source.BaseStream.Seek(0, SeekOrigin.Begin);

            MemoryStream memStream  = null;
            var          usedSource = source;

            var headerSignature = source.ReadBytes(2);

            source.BaseStream.Seek(0, SeekOrigin.Begin);
            if (headerSignature[0] == 0x1f && headerSignature[1] == 0x8b) // File is GZIP-compressed
            {
                if (readTagParams.PrepareForWriting)
                {
                    LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Writing metadata to gzipped VGM files is not supported yet.");
                    return(false);
                }

                using (var gzStream = new GZipStream(source.BaseStream, CompressionMode.Decompress))
                {
                    memStream = new MemoryStream();
                    StreamUtils.CopyStream(gzStream, memStream);
                    memStream.Seek(0, SeekOrigin.Begin);
                    usedSource = new BinaryReader(memStream);
                }
            }

            isValid = readHeader(usedSource, readTagParams);

            if (isValid && gd3TagOffset > VGM_HEADER_SIZE)
            {
                tagExists = true;
                readGd3Tag(usedSource, gd3TagOffset);
            }

            return(result);
        }