Esempio n. 1
0
        public static void Main()
        {
            AvFormatContext context = AvFormatContext.Open(@"E:\BBC\Light Fantastic\03 - The Stuff of Light.avi");
            AvStream[] streams = context.GetStreams();
            AvStream audioStream = null;

            foreach (AvStream stream in streams)
                if (stream.CodecContext.Type == CodecType.Audio)
                    audioStream = stream;
            
            if (audioStream == null)
            {
                Console.WriteLine("No Audio Stream found!");
                return;
            }

            // set up output
            AvOutputFormat oFormat = AvOutputFormat.GuessOutputFormat(null, @"D:\output.flac", null);
            AvFormatContext oContext = new AvFormatContext();
            oContext.OutputFormat = oFormat;
            oContext.IOStream = File.OpenWrite(@"D:\output.flac");
            AvStream oStream = oContext.AddAudioStream(oFormat.AudioCodec);

            AvCodec inCodec = audioStream.CodecContext.GetDecoder();
            AvCodec outCodec = oStream.CodecContext.GetEncoder();

            outCodec.Context.SampleRate = inCodec.Context.SampleRate;
            outCodec.Context.Channels = inCodec.Context.Channels;

            inCodec.Open();
            outCodec.Open();

            oContext.WriteHeader();
            for (int i = 0; i < 5000; i++)
            {
                // get an audio frame from the input.
                AvPacket frame = context.ReadFrame(null);
                if (frame.StreamIndex == audioStream.Index)
                {
                    AvSamples audioFrame = inCodec.DecodeAudio(frame);
                    AvPacket outPacket = outCodec.EncodeAudio(audioFrame);
                    //oContext.IOStream.Write(outPacket.Data, 0, outPacket.Length);
                    oContext.WritePacket(outPacket, oStream);
                }
            }
            oContext.WriteTrailer();
            oContext.IOStream.Close();
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an input codec, based on the settings found in the dataPacket/headerPacket.
        /// </summary>
        /// <param name="dataPacket">Contains the frame Data.</param>
        /// <param name="headerPacket">Contains the frame header Data.</param>
        /// <returns></returns>
        private VideoInputData CreateCodecFromPacket(IResultNode dataPacket, IResultNode headerPacket)
        {
            // Load the framedata from the packet to the byte buffer
            if (!PacketDataToBuffer(dataPacket, headerPacket))
            {
#if DEBUG
                Log.Info("No frame header information is available.");
#endif
                return(null);
            }

            IntPtr pInputFormatContext;
            if (_ffmpeg.AvOpenInputFile(out pInputFormatContext, DefraserProtocolPrefix + _convertId, IntPtr.Zero, 0, IntPtr.Zero) < 0)
            {
#if DEBUG
                Log.Info("Could not open input file.");
#endif
                return(null);
            }

            if (_ffmpeg.AvFindStreamInfo(pInputFormatContext) < 0)
            {
#if DEBUG
                Log.Info("Could not find (input)stream information.");
#endif
                return(null);
            }

            VideoInputData  videoInputData = null;
            AvFormatContext formatContext  = PtrToStructure <AvFormatContext>(pInputFormatContext);
            for (int i = 0; i < formatContext.NbStreams; ++i)
            {
                AvStream       stream = PtrToStructure <AvStream>(formatContext.Streams[i]);
                AvCodecContext codec  = PtrToStructure <AvCodecContext>(stream.Codec);

                if (codec.CodecType == CodecType.CodecTypeVideo)
                {
                    AvCodecContext videoCodecContext = PtrToStructure <AvCodecContext>(stream.Codec);
                    IntPtr         pVideoCodec       = _ffmpeg.AvcodecFindDecoder(videoCodecContext.CodecId);
                    if (pVideoCodec == IntPtr.Zero)
                    {
#if DEBUG
                        Log.Info("could not find input codec");
#endif
                        return(null);
                    }

                    if (_ffmpeg.AvcodecOpen(stream.Codec, pVideoCodec) < 0)
                    {
#if DEBUG
                        Log.Info("Could not open input codec.");
#endif
                        return(null);
                    }

                    // setup object used to decode (input) frames
                    videoInputData = new VideoInputData(_ffmpeg, pInputFormatContext, stream.Codec, PtrToStructure <AvCodecContext>(stream.Codec), i);

                    break;                     // stop seaching for video stream
                }
            }

            if (videoInputData == null)
            {
#if DEBUG
                Log.Info("Could not find video stream.");
#endif
                return(null);
            }
            return(videoInputData);
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            //AvInputFormat iFormat = AvInputFormat.GuessInputFormat(@"D:\BBC.Absolute.Zero.2of2.The.Race.for.Absolute.Zero.2007.DVBC.XviD.MP3.www.mvgroup.org.avi");
#if ENC_ONLY
            AvOutputFormat format = AvOutputFormat.GuessOutputFormat("mp3", null, null);
            AvFormatContext outputContext = new AvFormatContext();
            outputContext.OutputFormat = format;
            outputContext.Filename = @"DotNet://";
            if (format.AudioCodec == CodecId.None)
                throw new InvalidOperationException();
            AvStream outputStream = outputContext.AddAudioStream(format.AudioCodec);

            outputStream.CodecContext.SampleRate = 44100;
            outputStream.CodecContext.Channels = 2;
            outputStream.CodecContext.Bitrate = 64000;
            AvCodec outCodec = outputStream.CodecContext.GetEncoder();
            outCodec.Open();
            outputContext.WriteHeader();
            outCodec.Close();
            outputContext.WriteTrailer();

#else
            AvOutputFormat format = AvOutputFormat.GuessOutputFormat(null, "asdf.flac", null);
            AvFormatContext outputContext = new AvFormatContext();
            //outputContext.IOStream = File.OpenWrite(@"C:\out\output.mp3");
            //outputContext.OutputFormat = format;
            //if (format.AudioCodec == CodecId.None)
            //    throw new InvalidOperationException();
            //AvStream outputStream = outputContext.AddAudioStream(format.AudioCodec);

            AvFormatContext context = AvFormatContext.Open(@"E:\BBC\Light Fantastic\03 - The Stuff of Light.avi");
            // AvFormatContext context = AvFormatContext.Open(@"E:\BBC\Planet Earth\06 - Ice Worlds.avi");
            //string s = context.ToString();
            AvStream[] streams = context.GetStreams();
                    
            AvStream videoStream = null, audioStream = null;

            foreach (AvStream stream in streams)
            {
                switch (stream.CodecContext.Type)
                {
                    case CodecType.Video:
                        videoStream = stream;
                        break;
                    case CodecType.Audio:
                        audioStream = stream;
                        break;
                }
            }

            AvCodec videoCodec = videoStream.CodecContext.GetDecoder();
            AvCodec audioCodec = audioStream.CodecContext.GetDecoder();

            videoCodec.Open();
            audioCodec.Open();

            AvFrame finsihedFrame = null;
            AvPacket pkt;
            int frame = 0;

            AvCodec outcodec = AvCodec.FindEncoder(CodecId.Mp3);
            outcodec.Context.SampleRate = audioCodec.Context.SampleRate;
            outcodec.Context.Channels = audioCodec.Context.Channels;
            //outcodec.Context.Bitrate = 128000; // audioCodec.Context.Bitrate;
            //AvCodec outCodec = outputStream.CodecContext.GetEncoder();
            //outCodec.Open();
            outcodec.Open();

#if WAVE_OUTPUT
            BinaryWriter writer = new BinaryWriter(File.OpenWrite(@"C:\out\out.wav"));
            writer.Write(Encoding.ASCII.GetBytes("RIFF"), 0, 4);
            writer.Write((int)0);
            writer.Write(Encoding.ASCII.GetBytes("WAVEfmt "), 0, 8);
            writer.Write((int)16);
            writer.Write((short)1);
            writer.Write((short)audioCodec.Context.Channels);
            writer.Write((int)audioCodec.Context.SampleRate);
            writer.Write((int)(audioCodec.Context.SampleRate * audioCodec.Context.Channels * 16 / 8));
            writer.Write((short)(audioCodec.Context.Channels * 16 / 8));
            writer.Write((short)16);

            MemoryStream str = new MemoryStream();
            BinaryWriter sampleWriter = new BinaryWriter(str);
#endif

            DateTime start = DateTime.Now;

            short[] sampleCache = new short[outcodec.Context.FrameSize];
            
            int index = 0;
            //outputContext.WriteHeader();
            AvSamples final = null;
            for (int i = 0; i < 400; i++)
            {
                pkt = context.ReadFrame(null);
                if (pkt.StreamIndex == videoStream.Index ) {
                        finsihedFrame = videoCodec.DecodeVideo(pkt);
                        if (finsihedFrame != null)
                        {
                            Console.WriteLine("Frame format: " + finsihedFrame.Format + " (" + finsihedFrame.Width + "x" + finsihedFrame.Height + ")");
                            //Bitmap p = finsihedFrame.ConvertToBitmap();
                            //p.Save(@"C:\out\frame" + frame + @".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                            //p.Dispose();
                            finsihedFrame.Dispose();
                            finsihedFrame = null;
                            ++frame;
                        }
                }
                else if (pkt.StreamIndex == audioStream.Index)
                {
                    AvSamples samples = audioCodec.DecodeAudio(pkt);
                    if (samples.Count > 0)
                    {
                        if (final == null)
                            final = samples;
                        else
                            final += samples;
#if WAVE_OUTPUT
                        for (int xi = 0; xi < samples.Count; xi++)
                            sampleWriter.Write(samples.ShortSamples[xi]);
#endif
                    }
                }
                else
                    Console.WriteLine("Errrr");
                pkt.Dispose();
            }

            // encode
            int outIndez = 0;
            Stream str = File.OpenWrite(@"C:\out\output.flac");
            while (outIndez < final.Count)
            {
                AvSamples decoded = final.GetSamples(outIndez, outcodec.Context.FrameSize);
                AvPacket encodedFrame = outcodec.EncodeAudio(decoded);
                str.Write(encodedFrame.Data, 0, encodedFrame.Length);
                //outputContext.WritePacket(encodedFrame, outputStream);
                outIndez += outcodec.Context.FrameSize;
            }
            str.Close();

            outcodec.Close();
            //outputContext.WriteTrailer();
            TimeSpan timeTaken = DateTime.Now - start;
            Console.WriteLine(String.Format("Time Taken: {0} seconds.  Frames Decoded: {1}.  Overall framerate: {2}", timeTaken.Seconds, frame, frame / timeTaken.Seconds));
            Console.ReadKey();
#if WAVE_OUTPUT
            sampleWriter.Close();
            byte[] sampleBytes = str.ToArray();
            writer.Write(Encoding.ASCII.GetBytes("data"), 0, 4);
            writer.Write(sampleBytes.Length);
            writer.Write(sampleBytes);
            writer.Seek(4, SeekOrigin.Begin);
            writer.Write((int)36 + sampleBytes.Length);
            writer.Close();
#endif
            context.Close();
            return;
#endif
        }
Esempio n. 4
0
        public static void Main(string[] args)
        {
            WrapperUtils.RegisterLibrariesPathSimple("ffmpeg-x64", "ffmpeg-x86");
            AvFormat.RegisterAll();
            AvCodec.RegisterAll();
            AvFormat.NetworkInit();

            AvFormatContext format = AvFormatContext.Allocate();

            if (!format.OpenInput(@"http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"))
            {
                throw new Exception("Failed to open file :(");
            }
            if (!format.FindStreamInfo())
            {
                throw new Exception("Failed to find stream info :(");
            }

            AvStream pStream = null;

            foreach (AvStream avStream in format.Streams)
            {
                if (avStream.Codec.Type == AvMediaType.Video)
                {
                    pStream = avStream;
                    break;
                }
            }

            if (pStream == null)
            {
                throw new Exception("Could not find video stream :(");
            }

            AvCodecContext codecContext = pStream.Codec;

            int           width        = codecContext.Width;
            int           height       = codecContext.Height;
            AvPixelFormat sourceFormat = codecContext.PixelFormat;
            AvPixelFormat targetFormat = AvPixelFormat.Bgr24;

            SwsContext convertContext = SwsContext.Get(width, height, sourceFormat, width, height, targetFormat,
                                                       SwsFlags.FastBilinear);

            if (convertContext == null)
            {
                throw new Exception("Could not initialize the conversion context");
            }

            AvFrame     convertedFrame           = AvFrame.Allocate();
            int         convertedFrameBufferSize = AvPicture.GetSize(targetFormat, width, height);
            SByteBuffer convertedFrameBuffer     = AvUtil.Malloc((ulong)convertedFrameBufferSize);

            ((AvPicture)convertedFrame).Fill(convertedFrameBuffer, targetFormat, width, height);

            AvCodec codec = AvCodec.FindDecoder(codecContext.Id);

            if (codec == null)
            {
                throw new Exception("Unsupported codec");
            }

            if (codec.HasCapability(CodecCapabilities.Truncated))
            {
                codecContext.Flags |= CodecFlags.Truncated;
            }

            if (!codecContext.Open2(codec))
            {
                throw new Exception("Could not open codec");
            }

            AvFrame frame = AvFrame.Allocate();

            AvPacket packet = AvPacket.Create();

            packet.Init();

            int frameNumber = 0;

            while (frameNumber < 500)
            {
                if (!format.ReadFrame(packet))
                {
                    throw new Exception("Could not read frame!");
                }

                if (packet.StreamIndex != pStream.Index)
                {
                    continue;
                }

                int gotPicture;
                int size = codecContext.DecodeVideo2(frame, out gotPicture, packet);
                if (size < 0)
                {
                    throw new Exception("Error while decoding frame " + frameNumber);
                }

                if (gotPicture == 1)
                {
                    Console.WriteLine($"Frame: {frameNumber}");

                    SByteBufferArray src       = frame.Data;
                    SByteBufferArray dst       = convertedFrame.Data;
                    IntArray         srcStride = frame.LineSize;
                    IntArray         dstStride = convertedFrame.LineSize;
                    convertContext.Scale(src, srcStride, 0, height, dst, dstStride);

                    int linesize = dstStride[0];
                    using (
                        Bitmap bitmap = new Bitmap(width, height, linesize,
                                                   PixelFormat.Format24bppRgb, convertedFrame.Data0))
                    {
                        bitmap.Save(@"frame.buffer." + frameNumber + ".jpg", ImageFormat.Jpeg);
                    }
                    frameNumber++;
                }
            }

            convertedFrame.Free();
            convertedFrameBuffer.Free();
            convertContext.Free();
            frame.Free();
            codecContext.Close();
            format.CloseInput();
        }