Exemple #1
0
        unsafe static void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady(true);

            // make sure program always waits for user, except F5-Release run
            if (Debugger.IsAttached ||
                Environment.GetEnvironmentVariable("VisualStudioVersion") == null)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #2
0
        static public void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");

            mfxIMPL impl            = mfxIMPL.MFX_IMPL_AUTO;
            CodecId inputCodecId    = CodecId.MFX_CODEC_JPEG;
            CodecId outputCodecId   = CodecId.MFX_CODEC_JPEG;
            string  outputExtension = ".transcoded.264";//this should match codecld above


            string inFilename;

            inFilename = @"C:\x\core-imaging-playground\images\IMG_2301.jpg";
            //  inFilename = "BigBuckBunny_320x180.264";
            //inFilename = "BigBuckBunny_1920x1080.264";
            //inFilename = "BigBuckBunny_3840x2160.264";
            string outFilename = Path.ChangeExtension(inFilename, outputExtension);

            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine();

            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found. Press any key to exit.");
                Console.ReadKey();
                return;
            }


            Stream         infs, outfs;
            BenchmarkTimer bt = null;


#if !ENABLE_BENCHMARK
            infs  = File.Open(inFilename, FileMode.Open);
            outfs = File.Open(outFilename, FileMode.Create);
#else       // delete this code for most simple example
            // * Benchmark Mode *
            // this block does a couple things:
            //   1. causes the file to be pre-read into memory so we are not timing disk reads.
            //   2. replaces the output stream with a NullStream so nothing gets written to disk.
            //   3. Starts the timer for benchmarking
            // this pre-reads file into memory for benchmarking
            // maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024;
            Console.WriteLine("Pre-reading input");
            infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open));
            Console.WriteLine("Input read");

            outfs = new NullStream();
            bt    = new BenchmarkTimer();
            bt.Start();

            //int minimumFrames = 4000;
#endif

            Console.WriteLine("Output filename: {0}",
                              Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT"));
            Console.WriteLine();


            var config = TranscoderConfiguration.BuildTranscoderConfigurationFromStream(infs,
                                                                                        inputCodecId,
                                                                                        outputCodecId);

            var transcoder = new StreamTranscoder(infs, config, impl, false);

            string impltext = QuickSyncStatic.ImplementationString(transcoder.lowLevelTranscoder.session);
            Console.WriteLine("Implementation = {0}", impltext);
            //string memtext = QuickSyncStatic.ImplementationString(transcoder.lowLevelTranscoder.deviceSetup.memType);
            //Console.WriteLine("Memory type = {0}", memtext);



            int modulo = 100;

            int count = 0;


            foreach (var item in transcoder.GetFrames())
            {
                outfs.Write(item.bitstream, 0, item.bytesAvailable);

                if (++count % modulo == 0)
                {
                    Console.Write("Frames transcoded {0}\r", count);
                }
            }


            Console.WriteLine("Frames transcoded {0}", count);
            Console.WriteLine();

            if (bt != null)
            {
                bt.StopAndReport(count, infs.Position, outfs.Position);
            }

            infs.Close();
            outfs.Close();



            if (Debugger.IsAttached)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");


            int     width, height;
            string  inFilename;
            mfxIMPL impl   = mfxIMPL.MFX_IMPL_AUTO;
            FourCC  fourcc = FourCC.NV12;   // supported: RGB3 RGB4 BGR4 BGR3 NV12 I420 IYUV YUY2 UYVY YV12 P411 P422

            inFilename = "BigBuckBunny_320x180." + fourcc + ".yuv"; width = 320; height = 180;
            //inFilename = "BigBuckBunny_1920x1080." + fourcc + ".yuv"; width = 1920; height = 1080;


            string outFilename = Path.ChangeExtension(inFilename, "enc.264");


            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine("Input width: {0}  Input height: {1}", width, height);
            Console.WriteLine();

            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found.");
                Console.WriteLine("Please let Decoder1 run to completion to create input file");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
                return;
            }


            Stream         infs, outfs;
            BenchmarkTimer bt = null;


#if !ENABLE_BENCHMARK
            infs  = File.Open(inFilename, FileMode.Open);
            outfs = File.Open(outFilename, FileMode.Create);
#else       // delete this code for most simple example
            // * Benchmark Mode *
            // this block does a couple things:
            //   1. causes the file to be pre-read into memory so we are not timing disk reads.
            //   2. replaces the output stream with a NullStream so nothing gets written to disk.
            //   3. Starts the timer for benchmarking
            // this pre-reads file into memory for benchmarking
            long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024;
            Console.WriteLine("Pre-reading input");
            infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate);
            Console.WriteLine("Input read");

            outfs = new NullStream();
            bt    = new BenchmarkTimer();
            bt.Start();

            int minimumFrames = 4000;
#endif
            Console.WriteLine("Output filename: {0}",
                              Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT"));
            Console.WriteLine();


            mfxVideoParam mfxEncParams = new mfxVideoParam();
            mfxEncParams.mfx.CodecId                 = CodecId.MFX_CODEC_AVC;
            mfxEncParams.mfx.TargetUsage             = TargetUsage.MFX_TARGETUSAGE_BALANCED;
            mfxEncParams.mfx.TargetKbps              = 2000;
            mfxEncParams.mfx.RateControlMethod       = RateControlMethod.MFX_RATECONTROL_VBR;
            mfxEncParams.mfx.FrameInfo.FrameRateExtN = 30;
            mfxEncParams.mfx.FrameInfo.FrameRateExtD = 1;
            mfxEncParams.mfx.FrameInfo.FourCC        = FourCC.NV12;
            mfxEncParams.mfx.FrameInfo.ChromaFormat  = ChromaFormat.MFX_CHROMAFORMAT_YUV420;
            mfxEncParams.mfx.FrameInfo.PicStruct     = PicStruct.MFX_PICSTRUCT_PROGRESSIVE;
            mfxEncParams.mfx.FrameInfo.CropX         = 0;
            mfxEncParams.mfx.FrameInfo.CropY         = 0;
            mfxEncParams.mfx.FrameInfo.CropW         = (ushort)width;
            mfxEncParams.mfx.FrameInfo.CropH         = (ushort)height;
            // Width must be a multiple of 16
            // Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture
            mfxEncParams.mfx.FrameInfo.Width  = QuickSyncStatic.ALIGN16(width);
            mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.AlignHeightTo32or16(height, mfxEncParams.mfx.FrameInfo.PicStruct);
            mfxEncParams.IOPattern            = IOPattern.MFX_IOPATTERN_IN_SYSTEM_MEMORY; // must be 'in system memory'
            mfxEncParams.AsyncDepth           = 4;                                        // Pipeline depth. Best at 4


            BitStreamChunk bsc = new BitStreamChunk(); //where we receive compressed frame data

            //var encoder = new LowLevelEncoder2(mfxEncParams, impl);
            ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl);


            string impltext = QuickSyncStatic.ImplementationString(encoder.session);
            Console.WriteLine("Implementation = {0}", impltext);
            //string memtext = QuickSyncStatic.ImplementationString(encoder.deviceSetup.memType);
            //Console.WriteLine("Memory type = {0}", memtext);

            var formatConverter = new NV12FromXXXXConverter(fourcc, width, height);


            int inputFrameLength = width * height * VideoUtility.GetBitsPerPixel(fourcc) / 8;

            byte[] uncompressed = new byte[inputFrameLength];

            int count = 0;

            while (infs.Read(uncompressed, 0, inputFrameLength) == inputFrameLength)
            {
                int ix = encoder.GetFreeFrameIndex();  //get index of free surface

                formatConverter.ConvertToNV12FrameSurface(ref encoder.Frames[ix], uncompressed, 0);

                encoder.EncodeFrame(ix, ref bsc);

                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);

                    if (++count % 100 == 0)
                    {
                        Console.Write("Frame {0}\r", count);
                    }
                }

#if ENABLE_BENCHMARK     // delete this code for most simple example
                if (infs.Position + inputFrameLength - 1 >= infs.Length)
                {
                    infs.Position = 0;
                }
                if (count >= minimumFrames)
                {
                    break;
                }
#endif
            }



            while (encoder.Flush(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);

                    if (++count % 100 == 0)
                    {
                        Console.Write("Frame {0}\r", count);
                    }
                }
            }

            if (bt != null)
            {
                bt.StopAndReport(count, infs.Position, outfs.Position);
            }

            infs.Close();
            outfs.Close();

            encoder.Dispose();

            Console.WriteLine("Encoded {0} frames", count);

            if (Debugger.IsAttached)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #4
0
        static public void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");

            mfxIMPL impl            = mfxIMPL.MFX_IMPL_AUTO;
            CodecId inputCodecId    = CodecId.MFX_CODEC_AVC;
            CodecId outputCodecId   = CodecId.MFX_CODEC_AVC;
            string  outputExtension = ".transcoded.264";//this should match codecld above


            string inFilename = "BigBuckBunny_320x180.264";
            //string inFilename = "BigBuckBunny_1920x1080.264";
            string outFilename = Path.ChangeExtension(inFilename, outputExtension);

            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine("Output filename: {0}", outFilename);
            Console.WriteLine();

            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found. Press any key to exit.");
                Console.ReadKey();
                return;
            }

            var infs  = File.Open(inFilename, FileMode.Open);
            var outfs = File.Open(outFilename, FileMode.Create);


            var config = TranscoderConfiguration.BuildTranscoderConfigurationFromStream(infs,
                                                                                        inputCodecId,
                                                                                        outputCodecId);

            var transcoder = new LowLevelTranscoderCSharp(config, impl);

            string impltext = QuickSyncStatic.ImplementationString(transcoder.session);

            Console.WriteLine("Implementation = {0}", impltext);
            //string memtext = QuickSyncStatic.ImplementationString(transcoder.deviceSetup.memType);
            //Console.WriteLine("Memory type = {0}", memtext);

            int            count = 0;
            var            buf   = new byte[transcoder.BufferFreeCount];
            BitStreamChunk bsc   = new BitStreamChunk();

            int modulo = 100;



            while (true)
            {
                int free = transcoder.BufferFreeCount;


                if (free > transcoder.BufferSize / 2)
                {
                    int n = infs.Read(buf, 0, free);
                    if (n <= 0)
                    {
                        break;
                    }
                    transcoder.PutBitstream(buf, 0, n);
                }



                transcoder.GetNextFrame(ref bsc);
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            while (transcoder.GetNextFrame(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            while (transcoder.Flush1(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            while (transcoder.Flush2(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            while (transcoder.Flush3(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            while (transcoder.Flush4(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);
                    if (++count % modulo == 0)
                    {
                        Console.Write("Frames transcoded {0}\r", count);
                    }
                }
            }

            infs.Close();
            outfs.Close();

            Console.WriteLine("Frames transcoded {0}", count);



            if (Debugger.IsAttached)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #5
0
        static public void Main()
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");

            mfxIMPL impl    = mfxIMPL.MFX_IMPL_AUTO; //automatic GPU/CPU mode
            CodecId codecId = CodecId.MFX_CODEC_AVC;
            // avc fourcc supported: RGB3 RGB4 BGR4 BGR3 NV12 I420 IYUV YUY2 UYVY YV12 P411 P422
            FourCC fourcc       = FourCC.NV12;
            string fourccString = fourcc.ToString().Substring(0, 4);

            string inFilename;

            inFilename = "BigBuckBunny_320x180.264";
            //inFilename = "BigBuckBunny_1920x1080.264";
            //inFilename = "BigBuckBunny_3840x2160.264";
            string outFilename = Path.ChangeExtension(inFilename, fourccString + ".yuv");

            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine();

            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found. Press any key to exit.");
                Console.ReadKey();
                return;
            }


            Stream         infs, outfs;
            BenchmarkTimer bt = null;


#if !ENABLE_BENCHMARK
            infs  = File.Open(inFilename, FileMode.Open);
            outfs = File.Open(outFilename, FileMode.Create);
#else       // delete this code for most simple example
            // * Benchmark Mode *
            // this block does a couple things:
            //   1. causes the file to be pre-read into memory so we are not timing disk reads.
            //   2. replaces the output stream with a NullStream so nothing gets written to disk.
            //   3. Starts the timer for benchmarking
            // this pre-reads file into memory for benchmarking
            // maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024;
            Console.WriteLine("Pre-reading input");
            infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open));
            Console.WriteLine("Input read");

            outfs = new NullStream();
            bt    = new BenchmarkTimer();
            bt.Start();

            //int minimumFrames = 4000;
#endif

            Console.WriteLine("Output filename: {0}",
                              Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT"));
            Console.WriteLine();

            var outIOPattern = IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY;

            mfxVideoParam decoderParameters = QuickSyncStatic.ReadFileHeaderInfo(codecId, impl, infs, outIOPattern);
            decoderParameters.mfx.FrameInfo.FourCC = fourcc;

            var decoder = new StreamDecoder(infs, CodecId.MFX_CODEC_AVC, impl, outIOPattern);

            string impltext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.session);
            Console.WriteLine("Implementation = {0}", impltext);



            var formatConverter = new NV12ToXXXXConverter(fourcc, decoder.width, decoder.height);



            int count = 0;



            foreach (var frame in decoder.GetFrames())
            {
                var frameBytes = formatConverter.ConvertFromNV12(frame.Data);        // Convert to format requested
                outfs.Write(frameBytes, 0, frameBytes.Length);



                if (++count % 100 == 0)
                {
                    Console.Write("Frame {0}\r", count);
                }
            }
            Console.WriteLine("Decoded {0} frames", count);
            Console.WriteLine();

            if (bt != null)
            {
                bt.StopAndReport(count, infs.Position, outfs.Position);
            }

            infs.Close();
            outfs.Close();



            // make sure program always waits for user, except F5-Release run
            if (!UnitTest.IsRunning && Debugger.IsAttached ||
                Environment.GetEnvironmentVariable("VisualStudioVersion") == null)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #6
0
        unsafe static void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");


            CodecId codecId = CodecId.MFX_CODEC_JPEG;
            FourCC  fourcc  = FourCC.UYVY;  // supported: RGB4, YUY2 NV12 [UYVY through tricks! see below]
            mfxIMPL impl    = mfxIMPL.MFX_IMPL_AUTO;


            int    width, height;
            string inFilename;

            //inFilename = "BigBuckBunny_320x180." + fourcc + ".yuv"; width = 320; height = 180;
            inFilename = "BigBuckBunny_1920x1080." + fourcc + ".yuv"; width = 1920; height = 1080;
            string outFilename = Path.ChangeExtension(inFilename, "enc.jpeg");


            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine("Input width: {0}  Input height: {1}", width, height);


            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found.");
                Console.WriteLine("Please let Decoder1 run to completion to create input file");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
                return;
            }


            Stream         infs, outfs;
            BenchmarkTimer bt = null;


#if !ENABLE_BENCHMARK
            infs  = File.Open(inFilename, FileMode.Open);
            outfs = File.Open(outFilename, FileMode.Create);
#else       // delete this code for most simple example
            // * Benchmark Mode *
            // this block does a couple things:
            //   1. causes the file to be pre-read into memory so we are not timing disk reads.
            //   2. replaces the output stream with a NullStream so nothing gets written to disk.
            //   3. Starts the timer for benchmarking
            // this pre-reads file into memory for benchmarking
            long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024;
            Console.WriteLine("Pre-reading input");
            infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate);
            Console.WriteLine("Input read");

            outfs = new NullStream();
            bt    = new BenchmarkTimer();
            bt.Start();

            int minimumFrames = 4000;
#endif

            Console.WriteLine("Output filename: {0}",
                              Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT"));
            Console.WriteLine();

            // The encoder cannot encode UYVY, but if you are the only decoder of the JPEG
            // files, you can encode UYVY as YUY2 and everything is good.
            if (fourcc == FourCC.UYVY)
            {
                fourcc = FourCC.YUY2;
            }


            mfxVideoParam mfxEncParams = new mfxVideoParam();
            mfxEncParams.mfx.CodecId     = codecId;
            mfxEncParams.mfx.TargetUsage = TargetUsage.MFX_TARGETUSAGE_BALANCED;
            //mfxEncParams.mfx.TargetKbps = 2000;
            //mfxEncParams.mfx.RateControlMethod = RateControlMethod.MFX_RATECONTROL_VBR;
            mfxEncParams.mfx.Quality                 = 90;
            mfxEncParams.mfx.Interleaved             = 1;
            mfxEncParams.mfx.FrameInfo.FrameRateExtN = 30;
            mfxEncParams.mfx.FrameInfo.FrameRateExtD = 1;
            mfxEncParams.mfx.FrameInfo.FourCC        = fourcc;


            switch (fourcc)
            {
            case FourCC.NV12:
            case FourCC.YV12:
                mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV420;
                break;

            case FourCC.YUY2:
                mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV422V;     // fatal on SKYLAKE!
                mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV422;
                break;

            case FourCC.RGB4:
                mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV444;
                break;

            default:
                Trace.Assert(false);
                break;
            }


            mfxEncParams.mfx.FrameInfo.PicStruct = PicStruct.MFX_PICSTRUCT_PROGRESSIVE;
            mfxEncParams.mfx.FrameInfo.CropX     = 0;
            mfxEncParams.mfx.FrameInfo.CropY     = 0;
            mfxEncParams.mfx.FrameInfo.CropW     = (ushort)width;
            mfxEncParams.mfx.FrameInfo.CropH     = (ushort)height;
            // Width must be a multiple of 16
            // Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture
            mfxEncParams.mfx.FrameInfo.Width  = QuickSyncStatic.ALIGN16(width);
            mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.AlignHeightTo32or16(height, mfxEncParams.mfx.FrameInfo.PicStruct);
            mfxEncParams.IOPattern            = IOPattern.MFX_IOPATTERN_IN_SYSTEM_MEMORY; // must be 'in system memory'
            mfxEncParams.AsyncDepth           = 4;                                        // Pipeline depth. Best at 4


            mfxEncParams.mfx.FrameInfo.Width  = QuickSyncStatic.ALIGN32(width);
            mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.ALIGN32(height);


            BitStreamChunk bsc = new BitStreamChunk(); //where we receive compressed frame data

            ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl);
            //ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl);


            string impltext = QuickSyncStatic.ImplementationString(encoder.session);
            Console.WriteLine("Implementation = {0}", impltext);


            // not needed for YUY2 encoding
            //var formatConverter = new NV12FromXXXXConverter(fileFourcc, width, height);


            int inputFrameLength = width * height * VideoUtility.GetBitsPerPixel(fourcc) / 8;

            byte[] uncompressed = new byte[inputFrameLength];

            int count = 0;

            // we do not call encoder.LockFrame() and encoder.UnlockFrame() as this example is
            // for system memory.


            while (infs.Read(uncompressed, 0, inputFrameLength) == inputFrameLength)
            {
                int ix = encoder.GetFreeFrameIndex();  //this call relys locks in authoritative array of surf

                //formatConverter.ConvertToNV12FrameSurface(ref encoder.Frames[ix], uncompressed, 0);
                mfxFrameSurface1 *f = (mfxFrameSurface1 *)encoder.Frames[ix];


                switch (fourcc)
                {
                case FourCC.NV12:
                    Trace.Assert(f->Data.Pitch == width * 1);

                    fixed(byte *aa = &uncompressed[0])
                    FastMemcpyMemmove.memcpy(f->Data.Y, (IntPtr)aa, height * width);

                    fixed(byte *aa = &uncompressed[height * width])
                    FastMemcpyMemmove.memcpy(f->Data.UV, (IntPtr)aa, height / 2 * width);

                    break;

                case FourCC.YUY2:

                    Trace.Assert(f->Data.Pitch == width * 2);

                    fixed(byte *aa = &uncompressed[0])
                    FastMemcpyMemmove.memcpy(f->Data.Y, (IntPtr)aa, height * width * 2);

                    break;

                default:
                    Trace.Assert(false);
                    break;
                }

                encoder.EncodeFrame(ix, ref bsc);

                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);

                    if (++count % 100 == 0)
                    {
                        Console.Write("Frame {0}\r", count);
                    }
                }

#if ENABLE_BENCHMARK     // delete this code for most simple example
                if (infs.Position + inputFrameLength - 1 >= infs.Length)
                {
                    infs.Position = 0;
                }
                if (count >= minimumFrames)
                {
                    break;
                }
#endif
            }

            while (encoder.Flush(ref bsc))
            {
                if (bsc.bytesAvailable > 0)
                {
                    outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable);

                    if (++count % 100 == 0)
                    {
                        Console.Write("Frame {0}\r", count);
                    }
                }
            }

            if (bt != null)
            {
                bt.StopAndReport(count, infs.Position, outfs.Position);
            }

            infs.Close();
            outfs.Close();

            encoder.Dispose();

            Console.WriteLine("Encoded {0} frames", count);

            // make sure program always waits for user, except F5-Release run
            if (Debugger.IsAttached ||
                Environment.GetEnvironmentVariable("VisualStudioVersion") == null)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }
Exemple #7
0
        unsafe static void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new Exception("DirectX sample only works on Windows");
            }


            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");

            string fn;

            fn = @"BigBuckBunny_320x180.264";
            //fn = @"C:\w\BigBuckBunny_1920x1080.264";
            //fn = @"C:\w\bbb_sunflower_2160p_30fps_normal_track1.h264";


            var s = File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);


            var buf = new byte[1000];
            int n   = s.Read(buf, 0, buf.Length);

            s.Position = 0;
            Trace.Assert(n == buf.Length);

            var decVideoParam = QuickSyncStatic.DecodeHeader(buf, CodecId.MFX_CODEC_AVC);

            mfxVideoParam vppVideoParam = new mfxVideoParam();// = SetupVPPConfiguration(decVideoParam.mfx.FrameInfo.CropW, decVideoParam.mfx.FrameInfo.CropH);

            vppVideoParam.vpp.In  = decVideoParam.mfx.FrameInfo;
            vppVideoParam.vpp.Out = decVideoParam.mfx.FrameInfo;

            decVideoParam.IOPattern = IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
            vppVideoParam.IOPattern = IOPattern.MFX_IOPATTERN_IN_SYSTEM_MEMORY;

            vppVideoParam.IOPattern |= useSystemMemoryNotVideoMemory ?
                                       IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY : IOPattern.MFX_IOPATTERN_OUT_VIDEO_MEMORY;

            int vppOutWidth;
            int vppOutHeight;

            Console.WriteLine($"Bitstream -- width {0} height {1}",
                              decVideoParam.mfx.FrameInfo.CropW,
                              decVideoParam.mfx.FrameInfo.CropH);

            // vppOutWidth = 1920;
            //  vppOutHeight = 1080;
            bool doResize = true;

            if (doResize)
            {
            }
            else
            {
            }
            vppOutWidth  = decVideoParam.mfx.FrameInfo.CropW; // HxW of actual bitstream
            vppOutHeight = decVideoParam.mfx.FrameInfo.CropH;

            //resizing setup
            vppOutWidth  = decVideoParam.mfx.FrameInfo.CropW / 4;
            vppOutHeight = decVideoParam.mfx.FrameInfo.CropH / 4;

            Console.WriteLine($"VPP output -- width {0} height {1}",
                              vppOutWidth,
                              vppOutHeight);

            vppVideoParam.vpp.Out.FourCC = FourCC.RGB4;
            vppVideoParam.vpp.Out.CropW  = (ushort)(vppOutWidth);
            vppVideoParam.vpp.Out.CropH  = (ushort)(vppOutHeight);

            var form = new SharpDX.Windows.RenderForm();


            form.Width = vppOutWidth; form.Height = vppOutHeight;                                            // use resized HxW
            form.Width = decVideoParam.mfx.FrameInfo.CropW; form.Height = decVideoParam.mfx.FrameInfo.CropH; // use original HxW

            Console.WriteLine($"vppOutWidth {vppOutWidth}  vppOutHeight {vppOutHeight}");
            Console.WriteLine($"form.Width {form.Width}  form.Height {form.Height}");



            var impl = mfxIMPL.MFX_IMPL_VIA_D3D11 | mfxIMPL.MFX_IMPL_HARDWARE;

            var decoder = new StreamDecoder(s, decVideoParam, vppVideoParam, impl);

            //string impltext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.session);
            //Console.WriteLine("Implementation = {0}", impltext);
            //string memtext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.deviceSetup.memType);
            //Console.WriteLine("Memory type = {0}", memtext);


            if (useSystemMemoryNotVideoMemory)
            {
                device = new SharpDX.Direct3D11.Device(DriverType.Hardware);
            }
            else
            {
                IntPtr dx11device = decoder.lowLevelDecoder.videoAccelerationSupport.DeviceGetHandle(mfxHandleType.MFX_HANDLE_D3D11_DEVICE);
                device = new SharpDX.Direct3D11.Device(dx11device);
            }



            var fps = new FPSCounter();



            var sd = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(vppOutWidth, vppOutHeight, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput,
                Flags             = SwapChainFlags.None
            };

            var a = device.QueryInterface <SharpDX.DXGI.Device>();
            var b = a.Adapter.QueryInterface <Adapter2>();
            var c = b.GetParent <Factory2>();

            swapChain = new SwapChain(c, device, sd);


            var enumerator = decoder.GetFrames().GetEnumerator();

            RenderLoop.Run(form, () =>
            {
                enumerator.MoveNext();
                RenderFrameX(decoder, enumerator.Current);
                fps.PrintFPS();
            });


            swapChain.Dispose();
            device.Dispose();
        }
Exemple #8
0
        unsafe static void Main(string[] args)
        {
            ConfirmQuickSyncReadiness.HaltIfNotReady();

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            // keep ascending directories until 'media' folder is found
            for (int i = 0; i < 10 && !Directory.Exists("Media"); i++)
            {
                Directory.SetCurrentDirectory("..");
            }
            Directory.SetCurrentDirectory("Media");


            CodecId codecId = CodecId.MFX_CODEC_JPEG;
            FourCC  fourcc  = FourCC.UYVY;  // supported: RGB4, YUY2 NV12 [UYVY through tricks! see below]
            mfxIMPL impl    = mfxIMPL.MFX_IMPL_AUTO;



            string fourccString = fourcc.ToString().Substring(0, 4);
            string inFilename;

            //inFilename = "BigBuckBunny_320x180.UYVY.enc.jpeg";
            inFilename = "BigBuckBunny_1920x1080.UYVY.enc.jpeg";
            //inFilename = "BigBuckBunny_3840x2160.UYVY.enc.jpeg";
            string outFilename = Path.ChangeExtension(inFilename, ".yuv");

            Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory);
            Console.WriteLine("Input filename: {0}", inFilename);
            Console.WriteLine();

            if (!File.Exists(inFilename))
            {
                Console.WriteLine("Input file not found. Press any key to exit.");
                Console.ReadKey();
                return;
            }


            Stream         infs, outfs;
            BenchmarkTimer bt = null;


#if !ENABLE_BENCHMARK
            infs  = File.Open(inFilename, FileMode.Open);
            outfs = File.Open(outFilename, FileMode.Create);
#else       // delete this code for most simple example
            // * Benchmark Mode *
            // this block does a couple things:
            //   1. causes the file to be pre-read into memory so we are not timing disk reads.
            //   2. replaces the output stream with a NullStream so nothing gets written to disk.
            //   3. Starts the timer for benchmarking
            // this pre-reads file into memory for benchmarking
            long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024;
            Console.WriteLine("Pre-reading input");
            infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate);



            Console.WriteLine("Input read");

            outfs = new NullStream();
            bt    = new BenchmarkTimer();
            bt.Start();

            int minimumFrames = 4000;
#endif



            Console.WriteLine("Output filename: {0}",
                              Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT"));
            Console.WriteLine();

            var outIOPattern = IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY;


            // The encoder cannot encode UYVY, but if you are the only decoder of the JPEG
            // files, you can encode UYVY as YUY2 and everything is good.
            if (fourcc == FourCC.UYVY)
            {
                fourcc = FourCC.YUY2;
            }

            mfxVideoParam decoderParameters = QuickSyncStatic.ReadFileHeaderInfo(codecId, impl, infs, outIOPattern);
            decoderParameters.mfx.FrameInfo.FourCC = fourcc;

            AssignChromaFormat(fourcc, ref decoderParameters);


            var decoder = new StreamDecoder(infs, decoderParameters, null, impl);

#if ENABLE_BENCHMARK     // delete this code for most simple example
            decoder.benchmarkNeverStopMode = true;
#endif

            string impltext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.session);
            Console.WriteLine("Implementation = {0}", impltext);

            // not needed
            //var formatConverter = new NV12ToXXXXConverter(fourcc, decoder.width, decoder.height);

            int width  = decoderParameters.mfx.FrameInfo.CropW;
            int height = decoderParameters.mfx.FrameInfo.CropH;
            var tmpbuf = new byte[width * height * 2];

            int count = 0;

            foreach (var frame in decoder.GetFrames())
            {
                //var frameBytes = formatConverter.ConvertFromNV12(frame.Data);        // Convert to format requested


                Trace.Assert(frame.Data.Pitch == width * 2);  // yuy2 only

                fixed(byte *aa = &tmpbuf[0])
                FastMemcpyMemmove.memcpy((IntPtr)aa, frame.Data.Y, height * width * 2);

                outfs.Write(tmpbuf, 0, tmpbuf.Length);

                if (++count % 100 == 0)
                {
                    Console.Write("Frame {0}\r", count);
                }

#if ENABLE_BENCHMARK     // delete this code for most simple example
                if (count > minimumFrames)
                {
                    break;
                }
#endif
            }

            if (bt != null)
            {
                bt.StopAndReport(count, infs.Position, outfs.Position);
            }

            infs.Close();
            outfs.Close();

            Console.WriteLine("Decoded {0} frames", count);

            // make sure program always waits for user, except F5-Release run
            if (Debugger.IsAttached ||
                Environment.GetEnvironmentVariable("VisualStudioVersion") == null)
            {
                Console.WriteLine("done - press a key to exit");
                Console.ReadKey();
            }
        }