Example #1
0
        private unsafe void DecodeAVIHeader(RiffParser rp, int unpaddedLength, int length)
        {
            //if (length < sizeof(AVIMAINHEADER))
            //{
            //	throw new RiffParserException(String.Format("Header size mismatch. Needed {0} but only have {1}",
            //		sizeof(AVIMAINHEADER), length));
            //}

            byte[] ba = new byte[length];

            if (rp.ReadData(ba, 0, length) != length)
            {
                throw new RiffParserException("Problem reading AVI header.");
            }

            fixed(Byte *bp = &ba[0])
            {
                AVIMAINHEADER *avi = (AVIMAINHEADER *)bp;

                m_frameRate   = avi->dwMicroSecPerFrame;
                m_height      = avi->dwHeight;
                m_maxBitRate  = avi->dwMaxBytesPerSec;
                m_numStreams  = avi->dwStreams;
                m_totalFrames = avi->dwTotalFrames;
                m_width       = avi->dwWidth;
            }
        }
Example #2
0
        /// <summary>
        /// Handle chunk elements found in the AVI file. Ignores unknown chunks and
        /// </summary>
        /// <param name="rp"></param>
        /// <param name="FourCC"></param>
        /// <param name="unpaddedLength"></param>
        /// <param name="paddedLength"></param>
        private void ProcessAVIChunk(RiffParser rp, int FourCC, int unpaddedLength, int paddedLength)
        {
            if (AviRiffData.ckidMainAVIHeader == FourCC)
            {
                // Main AVI header
                DecodeAVIHeader(rp, unpaddedLength, paddedLength);
            }
            else if (AviRiffData.ckidAVIStreamHeader == FourCC)
            {
                // Stream header
                DecodeAVIStream(rp, unpaddedLength, paddedLength);
            }
            else if (AviRiffData.ckidAVIISFT == FourCC)
            {
                Byte[] ba = new byte[paddedLength];
                rp.ReadData(ba, 0, paddedLength);
                StringBuilder sb = new StringBuilder(unpaddedLength);
                for (int i = 0; i < unpaddedLength; ++i)
                {
                    if (0 != ba[i])
                    {
                        sb.Append((char)ba[i]);
                    }
                }

                m_isft = sb.ToString();
            }
            else
            {
                // Unknon chunk - skip
                rp.SkipData(paddedLength);
            }
        }
Example #3
0
        private static void ValidateAt9File(RiffParser parser)
        {
            if (parser.RiffChunk.Type != "WAVE")
            {
                throw new InvalidDataException("Not a valid WAVE file");
            }

            WaveFmtChunk      fmt = parser.GetSubChunk <WaveFmtChunk>("fmt ") ?? throw new InvalidDataException("File must have a valid fmt chunk");
            At9WaveExtensible ext = fmt.Ext as At9WaveExtensible ?? throw new InvalidDataException("File must have a format chunk extension");

            if (parser.GetSubChunk <At9FactChunk>("fact") == null)
            {
                throw new InvalidDataException("File must have a valid fact chunk");
            }
            if (parser.GetSubChunk <At9DataChunk>("data") == null)
            {
                throw new InvalidDataException("File must have a valid data chunk");
            }

            if (fmt.ChannelCount == 0)
            {
                throw new InvalidDataException("Channel count must not be zero");
            }

            if (ext.SubFormat != MediaSubtypes.MediaSubtypeAtrac9)
            {
                throw new InvalidDataException($"Must contain ATRAC9 data. Has unsupported SubFormat {ext.SubFormat}");
            }
        }
Example #4
0
        // Process a RIFF chunk element (skip the data)
        public void ProcessChunk(RiffParser rp, int FourCC, int length, int paddedLength)
        {
            string type = RiffParser.FromFourCC(FourCC);

            Debug.WriteLine("Found chunk element of type \"" +
                            type + "\" and length " + length.ToString());

            if (type.Trim() == "fmt")
            {
                BinaryReader br = new BinaryReader(rp.m_stream);


                var format     = br.ReadUInt16();
                var channels   = br.ReadUInt16();
                var sampleRate = br.ReadUInt32();
                var bytePerSec = br.ReadUInt32();
                var blockSize  = br.ReadUInt16();
                var bit        = br.ReadUInt16();

                Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    this.Info.Text = $"{channels} channels / {sampleRate} hz / {bit} bit / {bytePerSec} bytes/sec";
                });

                rp.SkipData(paddedLength - 16);
            }
            else
            {
                // Skip data and update bytesleft
                rp.SkipData(paddedLength);
            }
        }
Example #5
0
        public static VideoInfo TryReadVideoInfoViaAviHeader(string fileName)
        {
            var info = new VideoInfo {
                Success = false
            };

            try
            {
                using (var rp = new RiffParser())
                {
                    if (rp.TryOpenFile(fileName) && rp.FileType == RiffParser.CkidAvi)
                    {
                        var dh = new RiffDecodeHeader(rp);
                        dh.ProcessMainAvi();
                        info.FileType          = RiffParser.FromFourCc(rp.FileType);
                        info.Width             = dh.Width;
                        info.Height            = dh.Height;
                        info.FramesPerSecond   = dh.FrameRate;
                        info.TotalFrames       = dh.TotalFrames;
                        info.TotalMilliseconds = dh.TotalMilliseconds;
                        info.TotalSeconds      = info.TotalMilliseconds / TimeCode.BaseUnit;
                        info.VideoCodec        = dh.VideoHandler;
                        info.Success           = true;
                    }
                }
            }
            catch
            {
                // ignored
            }

            return(info);
        }
Example #6
0
 private bool ProcessAviRiff(RiffParser rp, uint fourCC, int length)
 {
     //Debug.Log("RIFF " + RiffParser.FromFourCC(fourCC) + " " + rp.Position + " " + length);
     if (fourCC != AviDemux.ID_AVI_ && fourCC != AviDemux.ID_AVIX)
     {
         throw new MpException("Not an AVI");
     }
     return(true);
 }
Example #7
0
    void DoInfoWindow(int windowID)
    {
        if (moviePlayerBase.movie != null)
        {
            var demux = moviePlayerBase.movie.demux;
            DrawLabelValue("Demux", demux != null ? demux.GetType().ToString() : "N/A");

            if (demux != null)
            {
                if (demux.hasVideo)
                {
                    var videoStreamInfo = moviePlayerBase.movie.demux.videoStreamInfo;
                    var videoDecoder    = moviePlayerBase.movie.videoDecoder;

                    DrawLabelValue("Video fourCC", RiffParser.FromFourCC(videoStreamInfo.codecFourCC));
                    DrawLabelValue("Video decoder", videoDecoder != null ? videoDecoder.GetType().ToString() : "N/A");

                    DrawLabelValue("bitsPerPixel", videoStreamInfo.bitsPerPixel.ToString());
                    DrawLabelValue("frameCount", videoStreamInfo.frameCount.ToString());
                    DrawLabelValue("frame size", videoStreamInfo.width + "x" + videoStreamInfo.height);
                    DrawLabelValue("framerate", videoStreamInfo.framerate.ToString());
                    DrawLabelValue("lengthBytes", videoStreamInfo.lengthBytes.ToString());
                    DrawLabelValue("lengthSeconds", videoStreamInfo.lengthSeconds.ToString());
                }
                else
                {
                    GUILayout.Label("No video stream found");
                }

                if (demux.hasAudio)
                {
                    var audioStreamInfo = moviePlayerBase.movie.demux.audioStreamInfo;
                    var audioDecoder    = moviePlayerBase.movie.audioDecoder;

                    DrawLabelValue("Audio fourCC", RiffParser.FromFourCC(audioStreamInfo.codecFourCC));
                    DrawLabelValue("Audio decoder", audioDecoder != null ? audioDecoder.GetType().ToString() : "N/A");

                    DrawLabelValue("audioFormat", audioStreamInfo.audioFormat.ToString("X"));
                    DrawLabelValue("channels", audioStreamInfo.channels.ToString());
                    DrawLabelValue("sampleCount", audioStreamInfo.sampleCount.ToString());
                    DrawLabelValue("sampleSize", audioStreamInfo.sampleSize.ToString());
                    DrawLabelValue("sampleRate", audioStreamInfo.sampleRate.ToString());
                    DrawLabelValue("lengthBytes", audioStreamInfo.lengthBytes.ToString());
                    DrawLabelValue("lengthSeconds", audioStreamInfo.lengthSeconds.ToString());
                }
                else
                {
                    GUILayout.Label("No audio stream found");
                }
            }
        }
        else
        {
            GUILayout.Label("No movie loaded");
        }
        GUI.DragWindow(new Rect(0, 0, 4000, 4000));
    }
Example #8
0
        /// <summary>
        /// Initializes the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        private unsafe void Initialize(Stream stream)
        {
            var parser = new RiffParser(stream);

            FileFormatName = "Unknown";

            // Parse Header
            if (!parser.MoveNext() || parser.Current == null)
            {
                ThrowInvalidFileFormat();
                return;
            }

            // Check that WAVE header is present
            FileFormatName = parser.Current.Type;
            if (FileFormatName != "WAVE")
                throw new InvalidOperationException("Unsupported " + FileFormatName + " file format. Only WAVE.");

            // Parse inside the first chunk
            parser.Descend();

            // Get all the chunk
            var chunks = parser.GetAllChunks();

            // Get "fmt" chunk
            var fmtChunk = Chunk(chunks, "fmt ");
            if (fmtChunk.Size < sizeof(WaveFormat.__PcmNative))
                ThrowInvalidFileFormat();

            try
            {
                Format = WaveFormat.MarshalFrom(fmtChunk.GetData());
            }
            catch (InvalidOperationException ex)
            {
                ThrowInvalidFileFormat(ex);
            }

            switch (Format.Encoding)
            {
                case WaveFormatEncoding.Pcm:
                case WaveFormatEncoding.IeeeFloat:
                case WaveFormatEncoding.Extensible:
                case WaveFormatEncoding.Adpcm:
                    break;
                default:
                    ThrowInvalidFileFormat();
                    break;
            }

            // Check for "data" chunk
            var dataChunk = Chunk(chunks, "data");
            startPositionOfData = dataChunk.DataPosition;
            length = dataChunk.Size;

            input.Position = startPositionOfData;
        }
Example #9
0
 public Wave(string fileName)
 {
     RiffParser parser = new RiffParser();
     RiffDecodeHeader decoder = new RiffDecodeHeader(parser);
     parser.OpenFile(fileName);
     if (RiffParser.ckidAVI == parser.FileType)
     {
         decoder.ProcessMainAVI();
         decoder.ProcessMainWAVE();
         parser.CloseFile();
     }
 }
Example #10
0
        public RiffParserDemo2()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            // Initialize parser instance
            rp = new RiffParser();
            dh = new DecodeHeader(rp);
            cr = new CDRReader(rp);
        }
Example #11
0
 private void ProcessWaveChunk(RiffParser rp, int FourCC, int unpaddedLength, int length)
 {
     // Is this a 'fmt' chunk?
     if (AviRiffData.ckidWaveFMT == FourCC)
     {
         DecodeWave(rp, length);
     }
     else
     {
         rp.SkipData(length);
     }
 }
Example #12
0
        private static void ParseChunkIndex(AtomicBinaryReader reader, long p, ref AviStreamIndex index)
        {
            // read ix.. chunk id and size. do sanity check
            uint ixChunkFCC  = reader.ReadUInt32(ref p);
            uint ixChunkFCCb = (ixChunkFCC & 0x0000FFFF) | 0x20200000;

            if (ixChunkFCCb != RiffParser.ToFourCC("ix  ") && ixChunkFCC != RiffParser.ToFourCC("indx"))
            {
                throw new MpException("Unexpected chunk id for index " + RiffParser.FromFourCC(ixChunkFCC) +
                                      " for stream " + RiffParser.FromFourCC(index.streamId));
            }
            uint ixChunkSize = reader.ReadUInt32(ref p);

            // read index data header and do sanity check
            ushort wLongsPerEntry = reader.ReadUInt16(ref p);
            byte   bSubIndexType  = reader.ReadByte(ref p);
            byte   bIndexType     = reader.ReadByte(ref p);
            uint   nEntriesInUse  = reader.ReadUInt32(ref p);
            uint   streamId       = reader.ReadUInt32(ref p);

                        #if MP_DEBUG
            //Debug.Log("Parsing index for " + RiffParser.FromFourCC(index.streamId));
                        #endif

            if (bIndexType != (int)AviStreamIndex.Type.CHUNKS || bSubIndexType != 0 || streamId != index.streamId ||
                wLongsPerEntry != 2 || ixChunkSize < 4 * wLongsPerEntry * nEntriesInUse + 24)
            {
                throw new MpException("Broken or unsupported index for stream " + RiffParser.FromFourCC(streamId) +
                                      ". " + streamId + "!=" + index.streamId + ", wLongsPerEntry=" + wLongsPerEntry +
                                      ", bIndexType=" + bIndexType + ", bSubIndexType=" + bSubIndexType);
            }

            long qwBaseOffset = reader.ReadInt64(ref p);
            p += 4;             // not caring about reserved bytes

            // reading it all at once is about 10x faster than reading individual uints.
            // the index chunk is not that big, so it's ok for GC too.
            var uintBuf = new uint[nEntriesInUse * 2];
            reader.Read(ref p, uintBuf, 0, (int)nEntriesInUse * 2);

            for (int i = 0; i < nEntriesInUse; i++)
            {
                var entry = new AviStreamIndex.Entry();
                entry.chunkOffset = qwBaseOffset + uintBuf [2 * i];
                uint len = uintBuf [2 * i + 1];
                entry.chunkLength = (int)(len & 0x7FFFFFFF);
                if ((len & 0x80000000) == 0)
                {
                    entry.isKeyframe = true;
                }
                index.entries.Add(entry);
            }
        }
Example #13
0
        private static void WriteChunkIndex(RiffWriter rw, AviStreamIndex index, int superIndexChunkOffset, ref int superIndexEntryCount, long indexBaseOffset, int maxSuperindexEntries)
        {
            var bw = rw.binaryWriter;

            // the offset where this index will be written
            long streamIndexOffset = bw.Seek(0, SeekOrigin.Current);

            // update stream superindex
            superIndexEntryCount++;
            if (superIndexEntryCount > maxSuperindexEntries)
            {
                throw new MpException("Not enough space was reserved for superindex. Please increase maxSuperindexEntries");
            }

            bw.Seek(superIndexChunkOffset + 1 * 4, SeekOrigin.Begin);
            bw.Write(superIndexEntryCount);              // overwrite nEntriesInUse
            bw.Seek(superIndexChunkOffset + 6 * 4 + (superIndexEntryCount - 1) * 16, SeekOrigin.Begin);
            bw.Write(streamIndexOffset);
            bw.Write(32 + 8 * index.entries.Count);     // dwSize
            bw.Write(index.entries.Count);              // dwDuration in stream ticks. @todo this is OK only for video, for audio stream this should be ???

            // write stream chunk index
            // @xxx MSDN suggests not seeking BaseStream when using BinaryWriter, but there are no Seek(long)
            //      in BinaryWriter. According to this forum post, BinaryWriter.Seek is just a wrapper
            //      to BinaryWriter.BaseStream.Seek, so all should be ok.
            //      http://www.pcreview.co.uk/forums/binarywriter-seek-vs-binarywriter-basestream-seek-t1223754.html
            bw.BaseStream.Seek(streamIndexOffset, SeekOrigin.Begin);

            rw.BeginChunk((RiffParser.ToFourCC("ix__") & 0x0000FFFF) | ((index.streamId << 16) & 0xFFFF0000));
            bw.Write((short)2);                         // wLongsPerEntry is always 2 here
            bw.Write((byte)0);                          // bIndexSubType is always 0 here
            bw.Write((byte)AviStreamIndex.Type.CHUNKS); // bIndexType = AVI_INDEX_OF_CHUNKS
            bw.Write(index.entries.Count);              // nEntriesInUse.
            bw.Write(index.streamId);                   // dwChunkId ("##dc" and similar)
            bw.Write(indexBaseOffset);                  // qwBaseOffset
            bw.Write((int)0);                           // dwReserved3

            foreach (var entry in index.entries)
            {
                long offset = entry.chunkOffset - indexBaseOffset;
                if (offset > int.MaxValue)
                {
                    throw new MpException("Internal error. Can't write index, because chunk offset won't fit into 31 bits: " + offset);
                }
                bw.Write((uint)offset);                  // bit31==0 indicating that this is a keyframe
                bw.Write(entry.chunkLength);
            }
            rw.EndChunk();

            index.globalOffset += index.entries.Count;
            index.entries.Clear();
        }
Example #14
0
        public Wave(string fileName)
        {
            RiffParser       parser  = new RiffParser();
            RiffDecodeHeader decoder = new RiffDecodeHeader(parser);

            parser.OpenFile(fileName);
            if (RiffParser.ckidAVI == parser.FileType)
            {
                decoder.ProcessMainAVI();
                decoder.ProcessMainWAVE();
                parser.CloseFile();
            }
        }
Example #15
0
        private unsafe void DecodeAVIStream(RiffParser rp, int unpaddedLength, int length)
        {
            byte[] ba = new byte[length];

            if (rp.ReadData(ba, 0, length) != length)
            {
                throw new RiffParserException("Problem reading AVI header.");
            }

            fixed(Byte *bp = &ba[0])
            {
                AVISTREAMHEADER *avi = (AVISTREAMHEADER *)bp;

                if (AviRiffData.streamtypeVIDEO == avi->fccType)
                {
                    m_vidHandler = RiffParser.FromFourCC(avi->fccHandler);
                    if (avi->dwScale > 0)
                    {
                        m_vidDataRate = (double)avi->dwRate / (double)avi->dwScale;
                    }
                    else
                    {
                        m_vidDataRate = 0.0;
                    }
                }
                else if (AviRiffData.streamtypeAUDIO == avi->fccType)
                {
                    if (AviRiffData.ckidMP3 == avi->fccHandler)
                    {
                        m_audHandler = "MP3";
                    }
                    else
                    {
                        m_audHandler = RiffParser.FromFourCC(avi->fccHandler);
                    }
                    if (avi->dwScale > 0)
                    {
                        m_audDataRate = 8.0 * (double)avi->dwRate / (double)avi->dwScale;
                        if (avi->dwSampleSize > 0)
                        {
                            m_audDataRate /= (double)avi->dwSampleSize;
                        }
                    }
                    else
                    {
                        m_audDataRate = 0.0;
                    }
                }
            }
        }
Example #16
0
        private unsafe void DecodeWave(RiffParser rp, int length)
        {
            byte[] ba = new byte[length];
            rp.ReadData(ba, 0, length);

            fixed(byte *bp = &ba[0])
            {
                WAVEFORMATEX *wave = (WAVEFORMATEX *)bp;

                m_numChannels   = wave->nChannels;
                m_bitsPerSec    = wave->nAvgBytesPerSec;
                m_bitsPerSample = wave->wBitsPerSample;
                m_samplesPerSec = wave->nSamplesPerSec;
            }
        }
Example #17
0
        private bool ProcessAviList(RiffParser rp, uint fourCC, int length)
        {
            //Debug.Log("LIST " + RiffParser.FromFourCC(fourCC) + " " + rp.Position + " " + length);
            if (fourCC == ID_movi)
            {
                // only if this is the first movi element
                if (idx1EntryOffset < 0)
                {
                    // point to the starting offset of "movi" LIST data
                    idx1EntryOffset = rp.Position + 4;
                }
            }

            // process chunks and lists only that are inside these two LIST elements
            return(fourCC == ID_hdrl || fourCC == ID_strl || fourCC == ID_odml);
        }
Example #18
0
        protected override WaveStructure ReadFile(Stream stream, bool readAudioData = true)
        {
            var structure = new WaveStructure();
            var parser    = new RiffParser {
                ReadDataChunk = readAudioData
            };

            parser.ParseRiff(stream);

            ValidateWaveFile(parser);

            WaveFmtChunk  fmt  = parser.GetSubChunk <WaveFmtChunk>("fmt ");
            WaveDataChunk data = parser.GetSubChunk <WaveDataChunk>("data");
            WaveSmplChunk smpl = parser.GetSubChunk <WaveSmplChunk>("smpl");

            int bytesPerSample = fmt.BitsPerSample.DivideByRoundUp(8);

            structure.RiffSubChunks = parser.GetAllSubChunks();
            structure.SampleCount   = data.SubChunkSize / bytesPerSample / fmt.ChannelCount;
            structure.SampleRate    = fmt.SampleRate;
            structure.BitsPerSample = fmt.BitsPerSample;
            structure.ChannelCount  = fmt.ChannelCount;

            if (smpl?.Loops?.FirstOrDefault() != null)
            {
                structure.LoopStart = smpl.Loops[0].Start;
                structure.LoopEnd   = smpl.Loops[0].End;
                structure.Looping   = structure.LoopEnd > structure.LoopStart;
            }

            if (!readAudioData)
            {
                return(structure);
            }

            switch (fmt.BitsPerSample)
            {
            case 16:
                structure.AudioData16 = data.Data.InterleavedByteToShort(fmt.ChannelCount);
                break;

            case 8:
                structure.AudioData8 = data.Data.DeInterleave(bytesPerSample, fmt.ChannelCount);
                break;
            }
            return(structure);
        }
Example #19
0
        public async void CheckFile()
        {
            StorageFolder storageFolder = KnownFolders.MusicLibrary;
            var           checkFile     = await storageFolder.TryGetItemAsync(this.Recorder.FileName);

            if (checkFile == null)
            {
                this.Info.Text = "Wav not recorded ...";
            }
            else
            {
                StorageFile storageFile = await storageFolder.GetFileAsync(this.Recorder.FileName);

                var parser = new RiffParser();

                // read file
                await Windows.System.Threading.ThreadPool.RunAsync(
                    async (workItem) =>
                {
                    IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
                    Stream sstream             = stream.AsStream();
                    parser.OpenFile(sstream);
                    // Define the processing delegates
                    RiffParser.ProcessChunkElement pc = ProcessChunk;

                    // Read all top level elements and chunks
                    int size = parser.DataSize;
                    while (size > 0)
                    {
                        // Prefix the line with the current top level type
                        var info = (RiffParser.FromFourCC(parser.FileType) + " (" + size.ToString() + "): ");
                        // Get the next element (if there is one)
                        if (false == parser.ReadElement(ref size, pc, null))
                        {
                            break;
                        }
                    }

                    // Close the stream
                    parser.CloseFile();
                });
            }
        }
Example #20
0
        private void CheckFile(string filename)
        {
            rp.OpenFile(filename);
            txtFileFormat.Text = RiffParser.FromFourCC(rp.FileRIFF);
            txtFileType.Text   = RiffParser.FromFourCC(rp.FileType);
            if (txtFileType.Text.StartsWith("CDR"))
            {
            }
            // Is this a type we are familiar with?
            if (RiffParser.ckidAVI == rp.FileType)
            {
                dh.ProcessMainAVI();
                lbl1a.Text = dh.FrameSize;
                lbl2a.Text = dh.FrameRate;
                lbl3a.Text = dh.TotalFrames;
                lbl4a.Text = dh.TotalTime;
                lbl5a.Text = dh.NumStreams;

                lbl1b.Text = dh.ISFT;
                lbl2b.Text = dh.VideoHandler;
                lbl3b.Text = dh.VideoDataRate;
                lbl4b.Text = dh.AudioHandler;
                lbl5b.Text = dh.AudioDataRate;

                pnlAVI.Visible = true;
            }
            else if (RiffParser.ckidWAV == rp.FileType)
            {
                dh.ProcessMainWAVE();
                lbl1a.Text = dh.NumChannels;
                lbl2a.Text = dh.BitsPerSample;
                lbl3a.Text = dh.BitsPerSec;
                lbl4a.Text = dh.SamplesPerSec;

                pnlAVI.Visible = true;
            }
            else if (RiffParser.ckidRMID == rp.FileType)
            {
            }

            rp.CloseFile();
        }
Example #21
0
        private static void ValidateWaveFile(RiffParser parser)
        {
            if (parser.RiffChunk.Type != "WAVE")
            {
                throw new InvalidDataException("Not a valid WAVE file");
            }

            WaveFmtChunk fmt = parser.GetSubChunk <WaveFmtChunk>("fmt ") ?? throw new InvalidDataException("File must have a valid fmt chunk");

            if (parser.GetSubChunk <WaveDataChunk>("data") == null)
            {
                throw new InvalidDataException("File must have a valid data chunk");
            }

            int bytesPerSample = fmt.BitsPerSample.DivideByRoundUp(8);

            if (fmt.FormatTag != WaveFormatTags.WaveFormatPcm && fmt.FormatTag != WaveFormatTags.WaveFormatExtensible)
            {
                throw new InvalidDataException($"Must contain PCM data. Has unsupported format {fmt.FormatTag}");
            }

            if (fmt.BitsPerSample != 16 && fmt.BitsPerSample != 8)
            {
                throw new InvalidDataException($"Must have 8 or 16 bits per sample, not {fmt.BitsPerSample} bits per sample");
            }

            if (fmt.ChannelCount == 0)
            {
                throw new InvalidDataException("Channel count must not be zero");
            }

            if (fmt.BlockAlign != bytesPerSample * fmt.ChannelCount)
            {
                throw new InvalidDataException("File has invalid block alignment");
            }

            if (fmt.Ext != null && fmt.Ext.SubFormat != MediaSubtypes.MediaSubtypePcm)
            {
                throw new InvalidDataException($"Must contain PCM data. Has unsupported SubFormat {fmt.Ext.SubFormat}");
            }
        }
Example #22
0
        public At9DataChunk(RiffParser parser, BinaryReader reader) : base(reader)
        {
            // Do not trust the BlockAlign field in the fmt chunk to equal the superframe size.
            // Some AT9 files have an invalid number in there.
            // Calculate the size using the ATRAC9 DataConfig instead.

            At9WaveExtensible ext = parser.GetSubChunk <WaveFmtChunk>("fmt ")?.Ext as At9WaveExtensible ??
                                    throw new InvalidDataException("fmt chunk must come before data chunk");

            At9FactChunk fact = parser.GetSubChunk <At9FactChunk>("fact") ??
                                throw new InvalidDataException("fact chunk must come before data chunk");

            var config = new Atrac9Config(ext.ConfigData);

            FrameCount = (fact.SampleCount + fact.EncoderDelaySamples).DivideByRoundUp(config.SuperframeSamples);
            int dataSize = FrameCount * config.SuperframeBytes;

            if (dataSize > reader.BaseStream.Length - reader.BaseStream.Position)
            {
                throw new InvalidDataException("Required AT9 length is greater than the number of bytes remaining in the file.");
            }

            AudioData = reader.BaseStream.DeInterleave(dataSize, config.SuperframeBytes, FrameCount);
        }
Example #23
0
        protected override At9Structure ReadFile(Stream stream, bool readAudioData = true)
        {
            var structure = new At9Structure();
            var parser    = new RiffParser {
                ReadDataChunk = readAudioData
            };

            parser.RegisterSubChunk("fact", At9FactChunk.ParseAt9);
            parser.RegisterSubChunk("data", At9DataChunk.ParseAt9);
            parser.FormatExtensibleParser = At9WaveExtensible.ParseAt9;
            parser.ParseRiff(stream);

            ValidateAt9File(parser);

            var fmt  = parser.GetSubChunk <WaveFmtChunk>("fmt ");
            var ext  = (At9WaveExtensible)fmt.Ext;
            var fact = parser.GetSubChunk <At9FactChunk>("fact");
            var data = parser.GetSubChunk <At9DataChunk>("data");
            var smpl = parser.GetSubChunk <WaveSmplChunk>("smpl");

            structure.Config          = new Atrac9Config(ext.ConfigData);
            structure.SampleCount     = fact.SampleCount;
            structure.EncoderDelay    = fact.EncoderDelaySamples;
            structure.Version         = ext.VersionInfo;
            structure.AudioData       = data.AudioData;
            structure.SuperframeCount = data.FrameCount;

            if (smpl?.Loops?.FirstOrDefault() != null)
            {
                structure.LoopStart = smpl.Loops[0].Start - structure.EncoderDelay;
                structure.LoopEnd   = smpl.Loops[0].End - structure.EncoderDelay;
                structure.Looping   = structure.LoopEnd > structure.LoopStart;
            }

            return(structure);
        }
Example #24
0
        /// <summary>
        /// Handle List elements found in the AVI file. Ignores unknown lists and recursively looks
        /// at the content of known lists.
        /// </summary>
        /// <param name="rp"></param>
        /// <param name="FourCC"></param>
        /// <param name="length"></param>
        private void ProcessAVIList(RiffParser rp, int FourCC, int length)
        {
            RiffParser.ProcessChunkElement pac = new RiffParser.ProcessChunkElement(ProcessAVIChunk);
            RiffParser.ProcessListElement  pal = new RiffParser.ProcessListElement(ProcessAVIList);

            // Is this the header?
            if ((AviRiffData.ckidAVIHeaderList == FourCC) ||
                (AviRiffData.ckidAVIStreamList == FourCC) ||
                (AviRiffData.ckidINFOList == FourCC))
            {
                while (length > 0)
                {
                    if (false == rp.ReadElement(ref length, pac, pal))
                    {
                        break;
                    }
                }
            }
            else
            {
                // Unknown lists - ignore
                rp.SkipData(length);
            }
        }
Example #25
0
 private void ProcessCDRList(RiffParser rp, int FourCC, int length)
 {
     Console.WriteLine(String.Format("LIST:{0:s}", RiffParser.FromFourCC(FourCC)));
     rp.SkipData(length);
 }
Example #26
0
        private void ProcessAviChunk(RiffParser rp, uint fourCC, int unpaddedLength, int paddedLength)
        {
            //Debug.Log("CHUNK " + RiffParser.FromFourCC(fourCC) + " " + rp.Position + " " + unpaddedLength + " " + paddedLength);
            switch (fourCC)
            {
            case ID_avih:
                avi.avih = ParseMainHeader(rp.reader, rp.Position);
                break;

            case ID_strh:
                AVIStreamHeader strh = ParseStreamHeader(rp.reader, rp.Position);
                currentStrh4CC = strh.fccType;
                if (currentStrh4CC == FCC_vids)
                {
                    avi.strhVideo = strh;
                }
                else if (currentStrh4CC == FCC_auds)
                {
                    avi.strhAudio = strh;
                }
                else
                {
                                        #if MP_DEBUG
                    Debug.LogWarning("Skipping unknown stream header with fccType=" + currentStrh4CC);
                                        #endif
                }
                break;

            case ID_strf:
                if (currentStrh4CC == FCC_vids)
                {
                    avi.strfVideo = ParseVideoFormatHeader(rp.reader, rp.Position);
                }
                else if (currentStrh4CC == FCC_auds)
                {
                    avi.strfAudio = ParseAudioFormatHeader(rp.reader, rp.Position);
                }
                break;

            case ID_idx1:
                idx1Offset = rp.Position;
                idx1Size   = unpaddedLength;
                // index.idx1 will be filled later in ParseIndex method
                break;

            case ID_dmlh:             // OpenDML header
                avi.odml = ParseOdmlHeader(rp.reader, rp.Position);
                break;

            case ID_indx:             // OpenDML index
                uint streamId;
                var  index = ParseOdmlIndex(rp.reader, rp.Position, out streamId);
                if (streamId == ID_00dc || streamId == ID_00db)
                {
                    avi.videoIndex = index;
                }
                else if (streamId == ID_01wb)
                {
                    avi.audioIndex = index;
                }
                                #if MP_DEBUG
                else
                {
                    Debug.LogWarning("Ignoring index for unknown stream " + RiffParser.FromFourCC(streamId));
                }
                                #endif
                break;

                        #if MP_DEBUG
            default:
                // comment in for logging chunks that are ignored (not relevant for us)
                //Debug.Log("Ignoring CHUNK " + RiffParser.FromFourCC(fourCC) + " " + unpaddedLength + " " + paddedLength);
                break;
                        #endif
            }
        }
Example #27
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            String riffFile = String.Empty;
            String name     = (String)e.Argument;
            bool   m14      = false;

            if (!File.Exists(name))
            {
                return;
            }
            FileStream   fs = File.OpenRead(name);
            BinaryReader br = new BinaryReader(fs);

            byte[] hd = new byte[2];
            br.Read(hd, 0, 2);
            if (Encoding.UTF8.GetString(hd) == "RI")
            {
                riffFile = name;
            }
            else if (Encoding.UTF8.GetString(hd) == "PK")
            {
                m14 = true;
                ZipInputStream zis = new ZipInputStream(File.OpenRead(name));
                ZipEntry       theEntry;
                bool           d = false;
                while ((theEntry = zis.GetNextEntry()) != null)
                {
                    String fileName;
                    if (theEntry.Name == "content/riffData.cdr" || theEntry.Name == "content/root.dat")
                    {
                        fileName = Path.GetFileName(theEntry.Name);
                        String tmp = Path.GetTempPath();
                        riffFile = tmp + fileName;
                        FileStream   fs1  = File.Open(tmp + fileName, FileMode.OpenOrCreate);
                        BinaryWriter bw   = new BinaryWriter(fs1);
                        int          size = 2048;
                        byte[]       data = new byte[2048];
                        while (true)
                        {
                            size = zis.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                bw.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        bw.Close();
                        fs1.Close();
                        zis.Close();
                        d = true;
                        break;
                    }
                }
                if (!d)
                {
                    MessageBox.Show("文件格式错误!");
                    return;
                }
            }
            else
            {
                MessageBox.Show("文件格式错误!");
                return;
            }
            br.Close();
            fs.Close();
            if (m14)
            {
            }
            RiffParser rp = new RiffParser();

            rp.OpenFile(riffFile);
            CDRReader cr = new CDRReader(rp);

            cr.Read();

            /*CDRWriter cw = new CDRWriter();
             * CDRFile cf = cr.CDRFile;
             * cf.list = RiffConn.DelRiff<CDRbmkt>(cf.list);
             * //cf.list = RiffConn.DelRiff<CDRcolo>(cf.list);
             * cf.list = RiffConn.DelRiff<CDRsyst>(cf.list);
             * cw.SetCDRFile(cf);
             * cw.Write(name + "_1");*/
            listBox1.Items.Clear();
            listBox1.Items.Add("文件名:");
            listBox1.Items.Add("    " + Path.GetFileName(name));
            listBox1.Items.Add("文件版本:");
            listBox1.Items.Add(String.Format("    CorelDraw {0:d}", cr.CDRFile.Version));
            listBox1.Items.Add("保存版本:");
            listBox1.Items.Add(String.Format("    CorelDraw {0:d} 子版本:{1:d}", cr.CDRFile.SVersion, cr.CDRFile.BuildID));
            listBox1.Items.Add("位图数量:");
            listBox1.Items.Add(String.Format("    {0:d}", cr.CDRFile.BMPCount));
            listBox1.Items.Add("视图样式数量:");
            listBox1.Items.Add(String.Format("    {0:d}", cr.CDRFile.ViewCount));
            listBox1.Items.Add(String.Format("使用字体:数量:{0:d}", cr.CDRFile.fonts.Count));
            foreach (CDRFile.Fonts f in cr.CDRFile.fonts)
            {
                listBox1.Items.Add(String.Format("    {0:1}", f.name));
            }
            rp.CloseFile();
        }
Example #28
0
        /// <summary>
        /// Initializes the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        private unsafe void Initialize(Stream stream)
        {
            var parser = new RiffParser(stream);

            FileFormatName = "Unknown";

            // Parse Header
            if (!parser.MoveNext() || parser.Current == null)
            {
                ThrowInvalidFileFormat();
                return;
            }

            // Check that WAVE or XWMA header is present
            FileFormatName = parser.Current.Type;
            if (FileFormatName != "WAVE" && FileFormatName != "XWMA")
                throw new InvalidOperationException("Unsupported " + FileFormatName + " file format. Only WAVE or XWMA");

            // Parse inside the first chunk
            parser.Descend();

            // Get all the chunk
            var chunks = parser.GetAllChunks();

            // Get "fmt" chunk
            var fmtChunk = Chunk(chunks, "fmt ");
            if (fmtChunk.Size < sizeof(WaveFormat.__PcmNative))
                ThrowInvalidFileFormat();

            try
            {
                Format = WaveFormat.MarshalFrom(fmtChunk.GetData());
            }
            catch (InvalidOperationException ex)
            {
                ThrowInvalidFileFormat(ex);
            }

            // If XWMA
            if (FileFormatName == "XWMA")
            {
                // Check that format is Wma
                if (Format.Encoding != WaveFormatEncoding.Wmaudio2 && Format.Encoding != WaveFormatEncoding.Wmaudio3)
                    ThrowInvalidFileFormat();

                // Check for "dpds" chunk
                // Get the dpds decoded packed cumulative bytes
                var dpdsChunk = Chunk(chunks, "dpds");
                DecodedPacketsInfo = dpdsChunk.GetDataAsArray<uint>();                
            } else
            {
                switch (Format.Encoding)
                {
                    case WaveFormatEncoding.Pcm:
                    case WaveFormatEncoding.IeeeFloat:
                    case WaveFormatEncoding.Extensible:
                    case WaveFormatEncoding.Adpcm:
                        break;
                    default:
                        ThrowInvalidFileFormat();
                        break;
                }                
            }

            // Check for "data" chunk
            var dataChunk = Chunk(chunks, "data");
            startPositionOfData = dataChunk.DataPosition;
            length = dataChunk.Size;

            input.Position = startPositionOfData;
        }
Example #29
0
        private static VideoInfo TryReadVideoInfoViaAviHeader(string fileName)
        {
            var info = new VideoInfo { Success = false };

            try
            {
                using (var rp = new RiffParser())
                {
                    var dh = new RiffDecodeHeader(rp);
                    rp.OpenFile(fileName);
                    info.FileType = RiffParser.FromFourCC(rp.FileType);
                    if (RiffParser.ckidAVI == rp.FileType)
                    {
                        dh.ProcessMainAVI();
                        info.Width = dh.Width;
                        info.Height = dh.Height;
                        info.FramesPerSecond = dh.FrameRate;
                        info.TotalFrames = dh.TotalFrames;
                        info.TotalMilliseconds = dh.TotalMilliseconds;
                        info.TotalSeconds = info.TotalMilliseconds / TimeCode.BaseUnit;
                        info.VideoCodec = dh.VideoHandler;
                        info.Success = true;
                    }
                }
            }
            catch
            {
            }
            return info;
        }
Example #30
0
 public DecodeHeader(RiffParser rp)
 {
     m_parser = rp;
 }
Example #31
0
 /// <summary>
 /// Defaulkt chunk handler - skip chunk data
 /// </summary>
 /// <param name="rp"></param>
 /// <param name="FourCC"></param>
 /// <param name="unpaddedLength"></param>
 /// <param name="paddedLength"></param>
 private void ProcessChunk(RiffParser rp, int FourCC, int unpaddedLength, int paddedLength)
 {
     rp.SkipData(paddedLength);
 }
Example #32
0
 /// <summary>
 /// Default list element handler - skip the entire list
 /// </summary>
 /// <param name="rp"></param>
 /// <param name="FourCC"></param>
 /// <param name="length"></param>
 private void ProcessList(RiffParser rp, int FourCC, int length)
 {
     rp.SkipData(length);
 }
Example #33
0
 private void ProcessCDRChunk(RiffParser rp, int FourCC, int unpaddedLength, int length)
 {
     Console.WriteLine(String.Format("Chunk:{0:s}", RiffParser.FromFourCC(FourCC)));
     rp.SkipData(length);
 }
Example #34
0
 public static At9DataChunk ParseAt9(RiffParser parser, BinaryReader reader) => new At9DataChunk(parser, reader);
Example #35
0
 private void Initialize(Stream stream)
 {
     RiffParser riffParser = new RiffParser(stream);
       this.FileFormatName = "Unknown";
       if (!riffParser.MoveNext() || riffParser.Current == null)
       {
     this.ThrowInvalidFileFormat((Exception) null);
       }
       else
       {
     this.FileFormatName = (string) riffParser.Current.Type;
     if (this.FileFormatName != "WAVE" && this.FileFormatName != "XWMA")
       throw new InvalidOperationException("Unsupported " + this.FileFormatName + " file format. Only WAVE or XWMA");
     riffParser.Descend();
     IList<RiffChunk> allChunks = riffParser.GetAllChunks();
     RiffChunk riffChunk1 = this.Chunk((IEnumerable<RiffChunk>) allChunks, "fmt ");
     if ((long) riffChunk1.Size < (long) sizeof (WaveFormat.__PcmNative))
       this.ThrowInvalidFileFormat((Exception) null);
     try
     {
       this.Format = WaveFormat.MarshalFrom(riffChunk1.GetData());
     }
     catch (InvalidOperationException ex)
     {
       this.ThrowInvalidFileFormat((Exception) ex);
     }
     if (this.FileFormatName == "XWMA")
     {
       if (this.Format.Encoding != WaveFormatEncoding.Wmaudio2 && this.Format.Encoding != WaveFormatEncoding.Wmaudio3)
     this.ThrowInvalidFileFormat((Exception) null);
       this.DecodedPacketsInfo = this.Chunk((IEnumerable<RiffChunk>) allChunks, "dpds").GetDataAsArray<uint>();
     }
     else
     {
       switch (this.Format.Encoding)
       {
     case WaveFormatEncoding.Extensible:
     case WaveFormatEncoding.Pcm:
     case WaveFormatEncoding.Adpcm:
     case WaveFormatEncoding.IeeeFloat:
       break;
     default:
       this.ThrowInvalidFileFormat((Exception) null);
       break;
       }
     }
     RiffChunk riffChunk2 = this.Chunk((IEnumerable<RiffChunk>) allChunks, "data");
     this.startPositionOfData = (long) riffChunk2.DataPosition;
     this.length = (long) riffChunk2.Size;
     this.input.Position = this.startPositionOfData;
       }
 }