示例#1
8
        static void Main(string[] args)
        {
            string outputFile = "test-output.wmv";
            int width = 320;
            int height = 240;

            // create instance of video writer
            VideoFileWriter writer = new VideoFileWriter();
            // create new video file
            writer.Open("test.avi", width, height, 25, VideoCodec.MPEG4);
            // create a bitmap to save into the video file
            Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            // write 1000 video frames
            for (int i = 0; i < 1000; i++)
            {
                image.SetPixel(i % width, i % height, Color.Red);
                writer.WriteVideoFrame(image);
            }
            writer.Close();

            Console.WriteLine("Finished");
            Console.ReadKey();
        }
示例#2
0
        private void buttonCreateVideo_Click(object sender, EventArgs e)
        {
            int width = 858;
            int height = 480;

            VideoFileWriter writer = new VideoFileWriter();
            writer.Open("sample-video.avi", width, height, 1, VideoCodec.MPEG4, 2500000);

            Bitmap image = new Bitmap(width, height);

            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = "Open Image";
                dlg.Filter = "bmp files (*.bmp)|*.bmp";

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    image = new Bitmap(dlg.FileName);
                }
            }

            for (int i = 0; i < 36000; i++)
            {
                writer.WriteVideoFrame(image);
            }

            writer.Close();
            Application.Exit();
        }
示例#3
0
        static void Main(string[] args)
        {
            var paths = args[0].Split(';');
            foreach (var path in paths.Where(s => !string.IsNullOrEmpty(s))){

                var files = Directory.GetFiles(path, "*.png");
                var images = GetImages(files.ToArray()).GroupBy(s => Regex.Replace(s, @"([^\d]*)([\d]*)([^\d]*)", "$1$3", RegexOptions.Singleline | RegexOptions.IgnoreCase));
                foreach (var grouping in images){
                    Console.WriteLine("Creating Videos for " + path);
                    var videoFileName = Path.Combine(path + "", grouping.Key + ".avi");
                    if (File.Exists(videoFileName))
                        File.Delete(videoFileName);
                    var videoFileWriter = new VideoFileWriter();
                    const int frameRate = 4;
                    using (var bitmap = new Bitmap(Path.Combine(path, grouping.First()+ImgExtentsion))){
                        videoFileWriter.Open(videoFileName, bitmap.Width, bitmap.Height, frameRate,VideoCodec.MPEG4);
                    }
                    WriteFranes(grouping, path, videoFileWriter, frameRate);
                    videoFileWriter.Close();
                    videoFileWriter.Dispose();
                    Console.WriteLine("Video for " + grouping.Key + " created");
                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
示例#4
0
        public void write_video_test()
        {
            var videoWriter = new VideoFileWriter();

            int width = 800;
            int height = 600;
            int framerate = 24;
            string path = Path.GetFullPath("output.avi");
            int videoBitRate = 1200 * 1000;
            //int audioBitRate = 320 * 1000;

            videoWriter.Open(path, width, height, framerate, VideoCodec.H264, videoBitRate);

            var m2i = new MatrixToImage();
            Bitmap frame;

            for (byte i = 0; i < 255; i++)
            {
                byte[,] matrix = Matrix.Create(height, width, i);
                m2i.Convert(matrix, out frame);
                videoWriter.WriteVideoFrame(frame, TimeSpan.FromSeconds(i));
            }

            videoWriter.Close();

            Assert.IsTrue(File.Exists(path));
        }
示例#5
0
        public static void CreateTimeLapse(string outputFilePath, int width, int height, int frameRate, bool orderByFileDate, string[] fileList)
        {
            try
            {
                using (var videoWriter = new VideoFileWriter())
                {
                    videoWriter.Open(outputFilePath, width, height, frameRate, VideoCodec.MPEG4, 1000000);

                    // use for ordering by file date
                    //System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(basePath);
                    //System.IO.FileSystemInfo[] images = di.GetFileSystemInfos();
                    //var orderedImages = images.OrderBy(f => f.CreationTime);

                    //foreach (FileSystemInfo imageFile in images)

                    foreach (string file in fileList)
                    {
                        // Out of Memory errors are common for incomplete or corrupted images.  Skip over them and continue.
                        try
                        {
                            using (Bitmap image = Image.FromFile(file) as Bitmap)
                            {
                                if (image != null)
                                {
                                    Bitmap bm = ResizeImage(image, width, height);
                                    videoWriter.WriteVideoFrame(bm);
                                }
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    videoWriter.Close();
                }

            }
            catch (Exception)
            {

                throw;
            }

        }
示例#6
0
        public override void Record(object o)
        {
            var r = (RecData)o;
            String outputFilePath = r.path;

            if (File.Exists(outputFilePath))
            {
                File.Delete(outputFilePath);
            }
            rec = true;
            var vFWriter = new VideoFileWriter();

            vFWriter.Open(outputFilePath, 800, 600, 5, VideoCodec.MPEG4);

            while (rec)
            {
                if (!pause)
                {
                    Stopwatch st = new Stopwatch();
                    st.Start();
                    using (Bitmap bmpScreenCapture = new Bitmap(r.width, r.height))
                    {
                        using (Graphics g = Graphics.FromImage(bmpScreenCapture))
                        {
                            g.CopyFromScreen(r.pos,
                                             new Point(0, 0),
                                             bmpScreenCapture.Size,
                                             CopyPixelOperation.SourceCopy);
                            Rectangle cursorBounds = new Rectangle(new Point(Cursor.Position.X - r.pos.X, Cursor.Position.Y - r.pos.Y), Cursors.Default.Size);
                            Cursors.Default.Draw(g, cursorBounds);
                        }
                        vFWriter.WriteVideoFrame(ReduceBitmap(bmpScreenCapture, 800, 600));
                        st.Stop();
                        var t = st.ElapsedMilliseconds;

                        if (200 - t > 0)
                            Thread.Sleep((int)(200 - t));
                    }

                }

            }

            vFWriter.Close();
        }
示例#7
0
 public void test()
 {
     int width = 320;
     int height = 240;
     // create instance of video writer
     VideoFileWriter writer = new VideoFileWriter();
     // create new video file
     writer.Open("test.avi", width, height, 25, VideoCodec.MPEG4);
     // create a bitmap to save into the video file
     Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb);
     // write 1000 video frames
     for (int i = 0; i < 1000; i++)
     {
         image.SetPixel(i % width, i % height, Color.Red);
         writer.WriteVideoFrame(image);
     }
     writer.Close();
 }
示例#8
0
 static void Main(string[] args)
 {
     if (args.Length < 3)
         printHelp();
     else
     {
         var dinfo = new DirectoryInfo(args[0]);
         var files = dinfo.GetFiles(args[1]).OrderBy(p => p.Name).ToArray();
         if (files.Length > 0)
         {
             Bitmap image = (Bitmap)Image.FromFile(files[0].FullName);
             var vFWriter = new VideoFileWriter();
             vFWriter.Open(args[2], image.Width, image.Height, 50, VideoCodec.MPEG4);
             foreach (var file in files)
             {
                 Console.WriteLine(file.FullName);
                 image = (Bitmap)Image.FromFile(file.FullName);
                 vFWriter.WriteVideoFrame(image);
             }
             vFWriter.Close();
         }
     }
 }
示例#9
0
        static void Main(string[] args)
        {
            var parserResults = Parser.Default.ParseArguments<Options>(args);

            if (parserResults.Tag == ParserResultType.NotParsed) {
                Console.WriteLine(
                    new HelpText { AddDashesToOption = true }
                        .AddPreOptionsLine("HeatMapVideoBuilder")
                        .AddPreOptionsLine("")
                        .AddOptions(parserResults).ToString());

                return;
            }

            var options = (parserResults as Parsed<Options>).Value;

            bool hasArgumentErrors = false;
            Image backgroundImage = null;
            IList<Image> spriteImages = new List<Image>();
            IList<SizeF> halfSpriteSize = new List<SizeF>();
            Image residualSpriteImage = null;
            Point mapOrigin = Point.Empty;
            Size mapSize = Size.Empty;
            Point dataOrigin = Point.Empty;
            Size dataSize = Size.Empty;
            IList<HeatMapData> heatMapData = new List<HeatMapData>();

            try {
                backgroundImage = Bitmap.FromFile(options.Background);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to load background image \"{0}\":\n\n{1}\n\n", options.Background, e);
                hasArgumentErrors = true;
            }

            try {
                mapOrigin = string.IsNullOrWhiteSpace(options.MapOrigin) ? Point.Empty : ParsePoint(options.MapOrigin);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse map origin \"{0}\":\n\n{1}\n\n", options.MapOrigin, e);
                hasArgumentErrors = true;
            }

            try {
                mapSize = string.IsNullOrWhiteSpace(options.MapSize) ? new Size(backgroundImage.Size.Width - mapOrigin.X, backgroundImage.Size.Height - mapOrigin.Y) : ParseSize(options.MapSize);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse map size \"{0}\":\n\n{1}\n\n", options.MapSize, e);
                hasArgumentErrors = true;
            }

            try {
                dataOrigin = string.IsNullOrWhiteSpace(options.DataOrigin) ? mapOrigin : ParsePoint(options.DataOrigin);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse data origin \"{0}\":\n\n{1}\n\n", options.DataOrigin, e);
                hasArgumentErrors = true;
            }

            try {
                dataSize = string.IsNullOrWhiteSpace(options.DataSize) ? mapSize : ParseSize(options.DataSize);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse data size \"{0}\":\n\n{1}\n\n", options.DataSize, e);
                hasArgumentErrors = true;
            }

            foreach (var spriteFile in options.SpriteFiles) {
                try {
                    var sprite = Bitmap.FromFile(spriteFile);
                    spriteImages.Add(sprite);
                    halfSpriteSize.Add(new SizeF(sprite.Width / 2.0f, sprite.Height / 2.0f));
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", spriteFile, e);
                    hasArgumentErrors = true;
                }
            }

            if (string.IsNullOrWhiteSpace(options.ResidualSpriteFile)) {
                residualSpriteImage = spriteImages.First();
            } else {
                try {
                    residualSpriteImage = Bitmap.FromFile(options.ResidualSpriteFile);
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", options.ResidualSpriteFile, e);
                    hasArgumentErrors = true;
                }
            }

            foreach (var inputFile in options.InputFile) {
                try {
                    var json = File.ReadAllText(inputFile);
                    var currentHeatMapData = JsonConvert.DeserializeObject<HeatMapData>(json);

                    if ((currentHeatMapData.Timestamps == null)) {
                        throw new Exception("Heat map data is missing a times array. This must be an array in a root object and contain time in milliseconds.");
                    }

                    if ((currentHeatMapData.X == null)) {
                        throw new Exception("Heat map data is missing an x coordinate array. This must be an array in a root object.");
                    }

                    if ((currentHeatMapData.Y == null)) {
                        throw new Exception("Heat map data is missing an y coordinate array. This must be an array in a root object.");
                    }

                    if ((currentHeatMapData.Timestamps.Count != currentHeatMapData.X.Count) || (currentHeatMapData.Timestamps.Count != currentHeatMapData.Y.Count)) {
                        throw new Exception("Heat map data arrays are not equal length.");
                    }

                    heatMapData.Add(currentHeatMapData);
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map data from \"{0}\":\n\n{1}\n\n", options.InputFile, e);
                    hasArgumentErrors = true;
                }
            }

            if (hasArgumentErrors) {
                return;
            }

            var frameRate = 25;
            var scaledFrameRate = options.TimeScale / frameRate;
            var timeDelta = (int) (1000 * scaledFrameRate);
            var width = backgroundImage.Width;
            var height = backgroundImage.Height;
            var fullRect = new Rectangle(0, 0, width, height);
            var xScaling = mapSize.Width / (float) dataSize.Width;
            var yScaling = mapSize.Height / (float) dataSize.Height;

            var compositeImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var compositeImageGraphics = Graphics.FromImage(compositeImage);
            compositeImageGraphics.CompositingMode = CompositingMode.SourceOver;
            compositeImageGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var heatMapBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var heatMapBufferGraphics = Graphics.FromImage(heatMapBuffer);
            heatMapBufferGraphics.CompositingMode = CompositingMode.SourceOver;
            heatMapBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var residualBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var residualBufferGraphics = Graphics.FromImage(residualBuffer);
            residualBufferGraphics.CompositingMode = CompositingMode.SourceOver;
            residualBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var tempBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var tempBufferGraphics = Graphics.FromImage(tempBuffer);
            tempBufferGraphics.CompositingMode = CompositingMode.SourceOver;
            tempBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var currentTime = 0;
            var currentIndices = Enumerable.Repeat(0, heatMapData.Count).ToArray();
            var heatMapDataDone = Enumerable.Repeat(false, heatMapData.Count).ToArray();

            var outputDirectory = Path.GetDirectoryName(options.OutputFile);
            if (!Directory.Exists(outputDirectory)) {
                Directory.CreateDirectory(outputDirectory);
            }

            var videoWriter = new VideoFileWriter();

            if (options.BitRate == 0) {
                videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4);
            } else {
                videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4, options.BitRate);
            }

            compositeImageGraphics.DrawImage(backgroundImage, Point.Empty);
            compositeImageGraphics.Save();
            videoWriter.WriteVideoFrame(compositeImage);

            var alphaFade = frameRate / options.Duration;

            var heatMapFadeMatrix = new ColorMatrix();
            heatMapFadeMatrix.Matrix33 = 0.95f;// alphaFade;

            var heatMapFadeImageAttributes = new ImageAttributes();
            heatMapFadeImageAttributes.SetColorMatrix(heatMapFadeMatrix);

            var residualFadeMatrix = new ColorMatrix();
            residualFadeMatrix.Matrix00 = 0.45f;
            residualFadeMatrix.Matrix01 = 0.45f;
            residualFadeMatrix.Matrix02 = 0.45f;
            residualFadeMatrix.Matrix10 = 0.45f;
            residualFadeMatrix.Matrix11 = 0.45f;
            residualFadeMatrix.Matrix12 = 0.45f;
            residualFadeMatrix.Matrix20 = 0.45f;
            residualFadeMatrix.Matrix21 = 0.45f;
            residualFadeMatrix.Matrix22 = 0.45f;

            var residualFadeImageAttributes = new ImageAttributes();
            residualFadeImageAttributes.SetColorMatrix(residualFadeMatrix);

            var lastTime = 0u;
            var endPadding = 8 * options.Duration * frameRate;

            var font = new Font("Consolas", 10.0f);
            var pens = new[] {
                new Pen(Color.FromArgb(unchecked((int) 0x080000FF))),
                new Pen(Color.FromArgb(unchecked((int) 0x08FF0000)))
             };
            residualBufferGraphics.CompositingMode = CompositingMode.SourceOver;

            while ((heatMapDataDone.Any(isDone => !isDone)) || (currentTime < (lastTime + endPadding))) {
                // Process the accumulation buffer.
                //tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height);
                //tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                //tempBufferGraphics.DrawImage(residualBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, residualFadeImageAttributes);
                //tempBufferGraphics.Save();

                //residualBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height);
                //residualBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                //residualBufferGraphics.DrawImage(tempBuffer, Point.Empty);
                //residualBufferGraphics.CompositingMode = CompositingMode.SourceOver;

                // Process the accumulation buffer.
                tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height);
                tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                tempBufferGraphics.DrawImage(heatMapBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, heatMapFadeImageAttributes);
                tempBufferGraphics.Save();

                heatMapBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height);
                heatMapBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                heatMapBufferGraphics.DrawImage(tempBuffer, Point.Empty);
                heatMapBufferGraphics.CompositingMode = CompositingMode.SourceOver;

                // Write the new heat map data into the heat map buffer.
                for (var i = 0; i < timeDelta; ++i) {
                    ++currentTime;

                    var heatMapIndex = 0;
                    var spriteIndex = 0;

                    foreach (var heatMapDataInstance in heatMapData) {
                        var currentIndex = currentIndices[heatMapIndex];

                        while ((currentIndex < heatMapDataInstance.Timestamps.Count) && (heatMapDataInstance.Timestamps[currentIndex] < currentTime)) {
                            lastTime = heatMapDataInstance.Timestamps[currentIndex];

                            var x = (heatMapDataInstance.X[currentIndex] - dataOrigin.X) * xScaling + mapOrigin.X;
                            var y = (heatMapDataInstance.Y[currentIndex] - dataOrigin.Y) * yScaling + mapOrigin.Y;

                            //residualBufferGraphics.DrawImage(residualSpriteImage, x, y);
                            residualBufferGraphics.DrawRectangle(pens[heatMapIndex], x -1, y -1, 3, 3);

                            x -= halfSpriteSize[spriteIndex].Width;
                            y -= -halfSpriteSize[spriteIndex].Height;
                            heatMapBufferGraphics.DrawImage(spriteImages[spriteIndex], x, y);

                            ++currentIndex;
                        }

                        currentIndices[heatMapIndex] = currentIndex;

                        if (currentIndex >= heatMapDataInstance.Timestamps.Count) {
                            heatMapDataDone[heatMapIndex] = true;
                        }

                        if (spriteIndex < spriteImages.Count - 1) {
                            ++spriteIndex;
                        }

                        ++heatMapIndex;
                    }
                }

                residualBufferGraphics.Save();
                heatMapBufferGraphics.Save();

                compositeImageGraphics.DrawImage(backgroundImage, Point.Empty);
                compositeImageGraphics.DrawImage(residualBuffer, Point.Empty);
                //compositeImageGraphics.DrawImage(heatMapBuffer, Point.Empty);

                var text = new TimeSpan(0, 0, 0, 0, currentTime).ToString(@"h\:mm\:ss");

                for (var i = -1; i <= 1; ++i) {
                    for (var j = -1; j <= 1; ++j) {
                        compositeImageGraphics.DrawString(text, font, Brushes.Black, 2 + i, 2 + j);
                    }
                }

                compositeImageGraphics.DrawString(text, font, Brushes.White, 2, 2);

                compositeImageGraphics.Save();

                videoWriter.WriteVideoFrame(compositeImage);
            }

            videoWriter.Close();
        }
示例#10
0
        private void button3_Click(object sender, EventArgs e)
        {
            int    Tap  = Int32.Parse(textBox3.Text);
            string Seed = textBox1.Text;

            Program.tap_vedio      = Tap;
            Program.seed_len_vedio = Seed.Length;
            int seed = 0, Power = 1;
            int currunt = 0;

            for (int i = Seed.Length - 1; i > -1; i--)
            {
                if (Seed[i] == '1')
                {
                    seed += Power;
                }
                Power *= 2;
                if (currunt < 63)
                {
                    Program.seed1_vedio = seed;
                }
                if (currunt == 62)
                {
                    Power = 1;
                    seed  = 0;
                }
                if (currunt >= 63)
                {
                    Program.seed2_vedio = seed;
                }
                currunt++;
            }
            for (int i = 0; i < Program.index_vedio; i++)
            {
                string OpenedFilePath = Program.images_name[i];
                Program.OriginalImage = ImageOperations.OpenImage(OpenedFilePath + ".bmp");
                int Width, Height;
                Width  = ImageOperations.GetWidth(Program.OriginalImage);
                Height = ImageOperations.GetHeight(Program.OriginalImage);
                Program.ApplyEncryptionOrDecryption1();
            }

            VideoFileWriter writer = new VideoFileWriter();

            writer.Open(@"C:\Users\JOE\Desktop\Videos\mov2.avi", 320, 240, 25, VideoCodec.Default);

            // ... here you'll need to load your bitmaps
            for (int i = 0; i <= 1312; i++)
            {
                string s           = Convert.ToString(i);
                Bitmap original_bm = new Bitmap(@"C:\Users\JOE\Desktop\[TEMPLATE] ImageEncryptCompress\Put Pictures/" + s + ".bmp");
                writer.WriteVideoFrame(original_bm);
            }
            writer.Close();

            /* var size = new Size(1600, 1200);                    // The desired size of the video
             * var fps = 25;                                       // The desired frames-per-second
             * var codec = VideoCodec.MPEG4;                       // Which codec to use
             * var destinationfile = @"d:\myfile.avi";             // Output file
             * var srcdirectory = @"d:\foo\bar";                   // Directory to scan for images
             * var pattern = "*.jpg";                              // Files to look for in srcdirectory
             * var searchoption = SearchOption.TopDirectoryOnly;   // Search Top Directory Only or all subdirectories (recursively)?
             *
             * using (var writer = new VideoFileWriter())          // Initialize a VideoFileWriter
             * {
             *   writer.Open(destinationfile, size.Width, size.Height, fps, codec);              // Start output of video
             *   foreach (var file in Directory.GetFiles(srcdirectory, pattern, searchoption))   // Iterate files
             *   {
             *       using (var original = (Bitmap)Image.FromFile(file))     // Read bitmap
             *       using (var resized = new Bitmap(original, size))        // Resize if necessary
             *           writer.WriteVideoFrame(resized);                    // Write frame
             *   }
             *   writer.Close();                                 // Close VideoFileWriter
             * }      */
        }
示例#11
0
        public void interpolateFrames()
        {
            videoWriter = new VideoFileWriter();
            videoWriter.Open("test.avi", getVideoWidth(), getVideoHeight(), 10, VideoCodec.MPEG4, 10000);

            Bitmap currentFrame;
            Bitmap nextFrame;
            Bitmap interpolatedFrame;

            currentFrame = videoReader.ReadVideoFrame();

            Rectangle rect = new Rectangle(0, 0, getVideoWidth(), getVideoHeight());

            Console.WriteLine(videoReader.FrameCount);

            foreach (var prop in videoReader.GetType().GetProperties())
            {
                Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(videoReader, null));
            }

            for (int i = 0; i < videoReader.FrameCount - 1; i++)
            {
                interpolatedFrame = new Bitmap(getVideoWidth(), getVideoHeight());

                //Get the current frame's bitmap data

                /*
                 * BitmapData currentFrameBmpData = currentFrame.LockBits(rect, ImageLockMode.ReadOnly, currentFrame.PixelFormat);
                 *
                 * IntPtr currentFramePtr = currentFrameBmpData.Scan0;
                 *
                 * int currentFrameBytes = Math.Abs(currentFrameBmpData.Stride) * currentFrame.Height;
                 *
                 * byte[] currentFrameRGB = new byte[currentFrameBytes];
                 *
                 * System.Runtime.InteropServices.Marshal.Copy(currentFramePtr, currentFrameRGB, 0, currentFrameBytes);
                 *
                 * //Unlock the bitmap data in memory after we're done with it
                 * currentFrame.UnlockBits(currentFrameBmpData);
                 */



                /*
                 * //Get the next frame's bitmap data
                 * BitmapData nextFrameBmpData = nextFrame.LockBits(rect, ImageLockMode.ReadOnly, nextFrame.PixelFormat);
                 *
                 * IntPtr nextFramePtr = nextFrameBmpData.Scan0;
                 *
                 * int nextFrameBytes = Math.Abs(nextFrameBmpData.Stride) * nextFrame.Height;
                 *
                 * byte[] nextFrameRGB = new byte[nextFrameBytes];
                 *
                 * System.Runtime.InteropServices.Marshal.Copy(nextFramePtr, nextFrameRGB, 0, nextFrameBytes);
                 *
                 * //Unlock the bitmap data
                 * nextFrame.UnlockBits(nextFrameBmpData);
                 *
                 *
                 * //byte[] interpolatedFrameRGB = currentFrameRGB.Zip(nextFrameRGB, (x, y) => (x + y));
                 */



                nextFrame = videoReader.ReadVideoFrame();


                for (int x = 0; x < getVideoWidth(); x++)
                {
                    for (int y = 0; y < getVideoHeight(); y++)
                    {
                        Color curFrameColor = currentFrame.GetPixel(x, y);

                        Color nextFrameColor = nextFrame.GetPixel(x, y);

                        Color averageColor = Color.FromArgb((curFrameColor.R + nextFrameColor.R) / 2, (curFrameColor.G + nextFrameColor.G) / 2, (curFrameColor.B + nextFrameColor.B) / 2);

                        interpolatedFrame.SetPixel(x, y, averageColor);
                    }
                }

                sender.updateCurrentFrameDisplay(i, (int)videoReader.FrameCount);

                currentFrame = nextFrame;

                videoWriter.WriteVideoFrame(currentFrame);

                sender.updatePreviewBox(currentFrame);

                videoWriter.WriteVideoFrame(interpolatedFrame);

                sender.updatePreviewBox(interpolatedFrame);

                //interpolatedFrame.Dispose();
            }
            videoWriter.Close();
        }
示例#12
0
 static public void Close()
 {
     writer.Close();
 }
 private void BtnStopRecording_Click(object sender, RoutedEventArgs e)
 {
     _isRecording = false;
     _writer.Close();
     _writer.Dispose();
 }
示例#14
0
 internal void StopRecord(bool ShowErr = true, bool CloseCamera = true)
 {
     try
     {
         if (CloseCamera && SettingHelp.Settings.摄像头)//摄像头关闭时调用该方法不需要再去关闭摄像头
         {
             foreach (Window shower in Application.Current.Windows)
             {
                 if (shower is CameraShow)
                 {
                     shower.Close();
                     break;
                 }
             }
         }
         if (SettingHelp.Settings.桌面)
         {
             videoStreamer.Stop();
             videoWriter.Close();
         }
         if (SettingHelp.Settings.声音)
         {
             audioStreamer.StopRecording();
             audioStreamer.Dispose();
         }
         isRecording = false;
         HiddenTools(SettingHelp.Settings.自动隐藏);
         btParse.Visibility = Visibility.Collapsed;
         btStop.Visibility  = Visibility.Collapsed;
         btSet.Visibility   = Visibility.Visible;
         lbTime.Visibility  = Visibility.Collapsed;
         btClose.Visibility = Visibility.Visible;
         btBegin.Visibility = Visibility.Visible;
         waitBar.Value      = 0;
         barGrid.Visibility = Visibility.Visible;
         //Convert后的MP4体积更小但清晰度没什么影响,所以无论有无声音都进行一次转换处理
         if (SettingHelp.Settings.桌面 || SettingHelp.Settings.摄像头)//没有视频则不转换
         {
             System.Threading.Tasks.Task.Factory.StartNew(() =>
             {
                 string tempVideo        = curVideoName, tempAudio = curAudioName;//运行未完成转换再次开始录制,所以这里需要把当前转换中的文件名记录下来
                 var ffMpeg              = new FFMpegConverter();
                 ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                 FFMpegInput[] input     = SettingHelp.Settings.声音 ? new FFMpegInput[] { new FFMpegInput(tempVideo), new FFMpegInput(tempAudio) } : new FFMpegInput[] { new FFMpegInput(tempVideo) };
                 ffMpeg.ConvertMedia(input, MakeFilePath(SettingHelp.Settings.编码类型), SettingHelp.Settings.编码类型, new OutputSettings());
                 try
                 {
                     if (File.Exists(tempVideo) && !SettingHelp.Settings.保留视频)
                     {
                         File.Delete(tempVideo);
                     }
                     if (File.Exists(tempAudio) && !SettingHelp.Settings.保留音频)
                     {
                         File.Delete(tempAudio);                                                      //合成后移除音频文件
                     }
                 }
                 catch { }//防止文件被占用删除失败
                 Dispatcher.Invoke(() =>
                 {
                     barGrid.Visibility = Visibility.Collapsed;
                 });
             });
         }
     }
     catch (Exception ex)
     {
         if (ShowErr)
         {
             Message(ex.Message);
         }
     }
 }
示例#15
0
 private void stop_Click(object sender, EventArgs e)
 {
     timer1.Stop();
     vw.Close();
 }
示例#16
0
 //停止录像
 private void button6_Click(object sender, EventArgs e)
 {
     videoWriter.Close();
     videoWriter.Dispose();
     video_flag = false;
 }
        public bool MakeVedioOfProcessVedioDate()
        {
            string VideoName = "";

            try
            {
                string day_str   = Convert.ToString(this.ProcessVedioDate.Day);
                string month_str = Convert.ToString(this.ProcessVedioDate.Month);
                string year_str  = Convert.ToString(this.ProcessVedioDate.Year);
                if (Convert.ToInt32(day_str) < 10)
                {
                    day_str = "0" + day_str;
                }
                if (Convert.ToInt32(month_str) < 10)
                {
                    month_str = "0" + month_str;
                }
                string ProcessVediodateStr = year_str + month_str + day_str;
                /* should so some work to frame it as 20170403 like that */
                VideoName = ProcessVediodateStr + this.CameraIMSINumber;
#if DEBUG
                var directory = new DirectoryInfo(Constants.ImagesDirectory_Debug);
#else
                var directory = new DirectoryInfo(Constants.ImagesDirectory_Release);
#endif

                FileInfo ImageFile = null;
                try
                {
                    ImageFile = (from Image in directory.GetFiles(ProcessVediodateStr + "*" + this.CameraIMSINumber + Constants.ImageExtension, SearchOption.AllDirectories)
                                 orderby Image.LastWriteTime descending
                                 select Image).First();
                }
                catch (Exception ex)
                {
                    /* no Image File exists for ProcessVediodateStr with that Cam IMSI */

                    return(false);
                }

                if (ImageFile == null)
                {
                    /* No Image Exists */
                    return(false);
                }
                else
                {
                    /* Image Exists */
                    string ImageName = Path.GetFileNameWithoutExtension(ImageFile.FullName);

                    string DateTimeOfIMage = ImageName.Substring(0, 14);

                    long DateTimeOfImage_long = Convert.ToInt64(DateTimeOfIMage);

                    if (DateTimeOfImage_long > this.ProcessedImagetime) /* Recent Image is there we need to process it */
                    {
                        Bitmap tmp_bitmap;
                        using (VideoFileWriter VideoWriter_Ogg = new VideoFileWriter())
                            using (VideoFileWriter VideoWriter_Mp4 = new VideoFileWriter())
                            {
                                VideoWriter_Ogg.VideoCodec = VideoCodec.Theora;
                                VideoWriter_Ogg.Height     = Constants.FrameHeight;
                                VideoWriter_Ogg.Width      = Constants.FrameWidth;
                                VideoWriter_Ogg.FrameRate  = Constants.FrameRate;

                                VideoWriter_Mp4.VideoCodec = VideoCodec.H264;
                                VideoWriter_Mp4.Height     = Constants.FrameHeight;
                                VideoWriter_Mp4.Width      = Constants.FrameWidth;
                                VideoWriter_Mp4.FrameRate  = Constants.FrameRate;
#if DEBUG
                                VideoWriter_Ogg.Open(Constants.TempVedioDirecory_Debug + VideoName + Constants.VedioExtension_Ogg); // Opening VideoFIle
                                VideoWriter_Mp4.Open(Constants.TempVedioDirecory_Debug + VideoName + Constants.VedioExtension_mp4);
#else
                                VideoWriter_Ogg.Open(Constants.TempVedioDirecory_Release + VideoName + Constants.VedioExtension_Ogg); // Opening VideoFIle
                                VideoWriter_Mp4.Open(Constants.TempVedioDirecory_Release + VideoName + Constants.VedioExtension_mp4);
#endif
                                var AllFilesOfCamera = directory.GetFiles(ProcessVediodateStr + "*" + this.CameraIMSINumber + Constants.ImageExtension, SearchOption.AllDirectories);
                                foreach (var file in AllFilesOfCamera) /*To Iterate through All Files of that Camera */
                                {
                                    string Imagefullpath = file.FullName;
                                    if (this.IsValidImage(Imagefullpath))
                                    {
                                        try
                                        {
                                            string tmp_Imagename            = Path.GetFileNameWithoutExtension(Imagefullpath);
                                            string tmp_DateTimeOfIMage      = tmp_Imagename.Substring(0, 14);
                                            long   tmp_DateTimeOfImage_long = Convert.ToInt64(tmp_DateTimeOfIMage);
                                            this.ProcessedImagetime = tmp_DateTimeOfImage_long;
                                            string created_hourofImage_Str  = tmp_Imagename.Substring(8, 2);
                                            short  created_hourofImage_long = Convert.ToInt16(created_hourofImage_Str);
                                            if (created_hourofImage_long >= Constants.MinimumHourtoMakeVideo)
                                            {
                                                tmp_bitmap = ConvertToBitmap(Imagefullpath);
                                                VideoWriter_Ogg.WriteVideoFrame(tmp_bitmap);
                                                VideoWriter_Mp4.WriteVideoFrame(tmp_bitmap);
                                            }
                                            else
                                            {
                                                /* Don't need to make it in video  */
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Global.AppendTexttoFile(Constants.ExceptionFilePath, "Exception Occured While Writing Bitmap to Video frame  " + ex.Message + "            " + DateTime.Now.ToString());
                                        }
                                    }
                                }
                                this.RecentlyCreatedVideoName_Ogg = VideoName + Constants.VedioExtension_Ogg;
                                this.RecentlyCreatedVideoName_Mp4 = VideoName + Constants.VedioExtension_mp4;
                                VideoWriter_Ogg.Close(); // TO CLose the VideoWriter After writing in to it..
                                VideoWriter_Mp4.Close();
                                this.ProcessedVedioDate = this.ProcessVedioDate;
                                return(true);
                            }
                    }
                    else
                    {
                        /* No need of processing & creating video */
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Global.AppendTexttoFile(Constants.ExceptionFilePath, "Exception Occured In Method MakeVedioOfProcessVedioDate()   " + ex.Message + "            " + DateTime.Now.ToString());
                if (VideoName != "")
                {
#if DEBUG
                    this.DeleteCorruptedVideoOfProcessVideoDate(Constants.TempVedioDirecory_Debug + VideoName + Constants.VedioExtension_Ogg);
                    this.DeleteCorruptedVideoOfProcessVideoDate(Constants.TempVedioDirecory_Debug + VideoName + Constants.VedioExtension_mp4);
#else
                    this.DeleteCorruptedVideoOfProcessVideoDate(Constants.TempVedioDirecory_Release + VideoName + Constants.VedioExtension_Ogg);
                    this.DeleteCorruptedVideoOfProcessVideoDate(Constants.TempVedioDirecory_Release + VideoName + Constants.VedioExtension_mp4);
#endif
                }

                return(false);
            }
        }
示例#18
0
        public async void RecordChat(float beginFramePerc, float endFramePerc)
        {
            if (CurrentChat == null)
            {
                return;
            }

            int chatPart = 0;

            uint  minFps          = 1;
            uint  maxFps          = 13;
            uint  fps             = maxFps;
            float speedMultiplier = 1.4f;

            bool firstMessageShown = false;

            int messageTimeChunk = 500;

            string recordedChatVideoFile = CurrentChat.FilePath + "-" + chatPart + ".mp4";

            chatWriter = new VideoFileWriter();
            chatWriter.Open(CurrentChat.FilePath + "-" + chatPart + "-" + beginFramePerc + "-" + endFramePerc + ".mp4", chatBoxWebControl.Width, chatBoxWebControl.Height, fps, VideoCodec.MPEG4, 100000000);

            Console.WriteLine("Starting Chat Recorder...");
            Instance.Text = "Starting Chat Recorder... Please wait.";

            recordingChat = true;

            long totalTime   = (long)chatLogLines[chatLogLines.Count - 1].Item1;
            long totalFrames = (totalTime * fps) / 1000;

            int beginFrame = (int)(totalFrames * beginFramePerc);
            int endFrame   = (int)(totalFrames * endFramePerc);

            int recordCurrentChatLogLinesIndex = 0;
            int targetTime = ((int)((((float)beginFrame / fps) * 1000) / messageTimeChunk)) * messageTimeChunk;

            for (int i = 0; i < chatLogLines.Count; i++)
            {
                Console.WriteLine(chatLogLines[i].Item1 + " >= " + targetTime);
                if (chatLogLines[i].Item1 >= targetTime)
                {
                    recordCurrentChatLogLinesIndex = Math.Max(0, i - 10);
                    break;
                }
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            int      prevChatLogLineIndex = recordCurrentChatLogLinesIndex;
            TimeSpan estTimeRemaining     = TimeSpan.Zero;

            int maxGifLines          = 8;
            int gifPresentSinceLines = 0;

            await Task.Delay(500);

            ExecuteJavascriptCommand("clearChatBox()");
            await Task.Delay(500);

            for (int i = beginFrame; i < endFrame; i++)
            {
                int messageTime = ((int)((((float)i / fps) * 1000) / messageTimeChunk)) * messageTimeChunk;
                if (recordCurrentChatLogLinesIndex < chatLogLines.Count &&
                    chatLogLines[recordCurrentChatLogLinesIndex].Item1 <= messageTime)
                {
                    Console.WriteLine(chatLogLines[recordCurrentChatLogLinesIndex].Item1 + " <= " + i + " / " + fps);

                    Func <string> parseChatLogLineFunction = new Func <string>(() =>
                                                                               ParseChatLogLine(chatLogLines[recordCurrentChatLogLinesIndex++].Item2, currentChannelId, parseChatLogLineTokenSource.Token));
                    string chatLogLine = await Task.Run <string>(parseChatLogLineFunction);

                    if (chatLogLine.Contains(".gif"))
                    {
                        gifPresentSinceLines = maxGifLines;
                    }
                    else
                    {
                        gifPresentSinceLines--;
                    }

                    if (chatLogLine != null && chatLogLine != "")
                    {
                        AddChatLine(chatLogLine);
                        if (!firstMessageShown)
                        {
                            firstMessageShown = true;
                        }
                    }

                    await Task.Delay(20);
                }
                else if (gifPresentSinceLines > 0)
                {
                    await Task.Delay((int)(1000 / fps / speedMultiplier));
                }

                using (Graphics controlGraphics = chatBoxWebControl.CreateGraphics()) {
                    using (Bitmap bitmap = new Bitmap(chatBoxWebControl.Size.Width, chatBoxWebControl.Size.Height, controlGraphics)) {
                        using (Graphics memoryGraphics = Graphics.FromImage(bitmap)) {
                            IntPtr dc = memoryGraphics.GetHdc();
                            PrintWindow(chatBoxWebControl.Handle, dc, 0);
                            memoryGraphics.ReleaseHdc(dc);
                            chatWriter.WriteVideoFrame(bitmap, (uint)(i));
                        }
                    }
                }

                if (stopwatch.ElapsedMilliseconds >= 6000)
                {
                    int framePerSec = (i - prevChatLogLineIndex) / 6;
                    prevChatLogLineIndex = i;
                    estTimeRemaining     = TimeSpan.FromSeconds((totalFrames - i) / framePerSec);
                    stopwatch.Restart();
                }

                string percentage = (((float)i / endFrame) * 100.0f).ToString("0.0000");

                Instance.Text =
                    "Recording Chat... - " + (i + " Frames / " + endFrame + " Frames (" + percentage + "%)");

                if (estTimeRemaining != TimeSpan.Zero)
                {
                    Instance.Text += " - EST: " + (int)estTimeRemaining.TotalHours + " H " + (int)estTimeRemaining.Minutes + " M ";
                }

                if (gifPresentSinceLines > 0)
                {
                    fps = maxFps;
                }
                else if (firstMessageShown)
                {
                    fps = minFps;
                }
            }

            Console.WriteLine("Finishing Chat Recorder...");

            ExecuteJavascriptCommand("clearChatBox()");

            recordingChat = false;

            Instance.Text = "Chat has been recorded.<br><br>You can find the video file at " + recordedChatVideoFile;

            chatWriter.Close();

            Instance.Text = "Chat";
        }
示例#19
0
 private void button7_Click(object sender, EventArgs e)
 {
     recording = false;
     writer.Close();
 }
示例#20
0
        private static void getimagefromurl(int cctv_code, String url, String path, String tempname)
        {
            List <System.Drawing.Bitmap> ListBitmap = new List <System.Drawing.Bitmap>();
            string filename = tempname + DateTime.Now.ToString("mmssfff") + ".mp4";

            for (int i = 0; i < 250; i++)
            {
                try
                {
                    System.Net.WebRequest request = System.Net.WebRequest.Create(url);
                    request.Credentials = new NetworkCredential("admin", "12345");


                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            Bitmap bitmap = new Bitmap(responseStream);
                            ListBitmap.Add(bitmap);
                        }
                    }
                }
                catch (Exception)
                {
                    //Console.WriteLine("fail get image "+tempname);
                }
                Thread.Sleep(1000);
            }
            int width    = 352;
            int height   = 288;
            var framRate = 25;

            try
            {
                using (var vFWriter = new VideoFileWriter())
                {
                    vFWriter.Open(filename, width, height, framRate, VideoCodec.MPEG4);


                    //loop throught all images in the collection
                    foreach (var bitmap in ListBitmap)
                    {
                        //what's the current image data?

                        var bmpReduced = ReduceBitmap(bitmap, width, height);

                        vFWriter.WriteVideoFrame(bmpReduced);
                    }
                    vFWriter.Close();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("failed create video");
            }

            Console.WriteLine("Success Create Video " + filename);
            try
            {
                uploadtoftp(cctv_code, filename, path, tempname);
            }
            catch (Exception)
            {
                Console.WriteLine("failed upload to ftp " + filename);
            }
            try
            {
                string currentexedirectory = "C:/Users/Administrator/Desktop/atcsvideorecorder/";
                File.SetAttributes(currentexedirectory + filename, FileAttributes.Normal);
                File.Delete(currentexedirectory + filename);
                Console.WriteLine("success delete " + @filename);
            }
            catch (Exception)
            {
                Console.WriteLine("failed delete file " + @filename);
            }
            try
            {
                uploadtodb(cctv_code, path, filename);

                Console.WriteLine("success upload to DB " + @filename);
            }
            catch (Exception)
            {
                Console.WriteLine("failed upload to DB " + @filename);
            }
        }
 public void StopRecording()
 {
     m_startrecording = false;
     //wait 0.1 s
     FileWriter.Close();
 }
示例#22
0
        public static void Command(string com)
        {
            if (com == "/help")
            {
                Console.WriteLine("----------");
                Console.WriteLine("Commands List:");
                Console.WriteLine("/load NN <file name> : Load Neural Network in floder NN");
                Console.WriteLine("/make image <file name> : render image in floder \"Images\"");
                Console.WriteLine("/make video <file name> : render video in floder \"Videos\"");
                Console.WriteLine("/exit : exit from program");
                Console.WriteLine("----------");
            }
            else if (com == "/exit")
            {
                Environment.Exit(0);
            }
            else if (com.StartsWith("/make image"))
            {
                string fname = com.Replace("/make image", "");
                if (fname.Replace(" ", "") == "")
                {
                    Console.WriteLine("---------- Please select image num : ----------");
                    DirectoryInfo d = new DirectoryInfo("Images");
                    for (int i = 0; i < d.GetFiles().Length; i++)
                    {
                        Console.WriteLine(i + " " + d.GetFiles()[i].Name);
                    }
                    Console.WriteLine("-1 exit");
                    Console.WriteLine("-----------------------------------------------");

                    int n = Convert.ToInt32(Console.ReadLine());
                    while (n < -1 || n > d.GetFiles().Length - 1)
                    {
                        Console.WriteLine("Please select correct num.");
                        n = Convert.ToInt32(Console.ReadLine());
                    }
                    if (n == -1)
                    {
                        return;
                    }
                    fname = d.GetFiles()[n].Name;
                }

                if (fname[0] == ' ')
                {
                    fname = fname.Remove(0, 1);
                }

                if (File.Exists("Images/" + fname))
                {
                    remakeimg(fname);
                }
                else
                {
                    Console.WriteLine("File \"" + fname + "\" not found");
                }
            }
            else if (com.StartsWith("/make video"))
            {
                string fname = com.Replace("/make video", "");
                if (fname.Replace(" ", "") == "")
                {
                    Console.WriteLine("---------- Please select video num : ----------");
                    DirectoryInfo d = new DirectoryInfo("Videos");
                    for (int i = 0; i < d.GetFiles().Length; i++)
                    {
                        Console.WriteLine(i + " " + d.GetFiles()[i].Name);
                    }
                    Console.WriteLine("-1 exit");
                    Console.WriteLine("-----------------------------------------------");

                    int n = Convert.ToInt32(Console.ReadLine());
                    while (n < -1 || n > d.GetFiles().Length - 1)
                    {
                        Console.WriteLine("Please select correct num.");
                        n = Convert.ToInt32(Console.ReadLine());
                    }
                    if (n == -1)
                    {
                        return;
                    }
                    fname = d.GetFiles()[n].Name;
                }

                if (fname[0] == ' ')
                {
                    fname = fname.Remove(0, 1);
                }

                if (File.Exists("Videos/" + fname))
                {
                    Console.CursorVisible = false;

                    Console.WriteLine("---------- " + fname + " rendering ----------");

                    VideoFileWriter w = new VideoFileWriter();

                    w.Open("New Videos/" + fname.Replace(".mp4", "") + ".avi", 1280, 720, 30, VideoCodec.MPEG4);

                    VideoFileReader f = new VideoFileReader();
                    f.Open("Videos/" + fname);
                    Console.WriteLine("Video loaded");
                    Console.WriteLine("Video frames Count :" + f.FrameCount);
                    long all = f.Width * f.Height * f.FrameCount;

                    Console.WriteLine("Rendering video : 0%      ");
                    Console.Write("Rendering frame 0/" + (f.FrameCount - 1) + " : 0%      ");

                    for (int i = 0; i < f.FrameCount; i++)
                    {
                        Bitmap b = f.ReadVideoFrame();
                        b = remakeimg(b, i, f.FrameCount);
                        w.WriteVideoFrame(b);
                        b.Dispose();
                    }

                    f.Close();
                    w.Close();

                    Console.CursorVisible = true;
                }
                else
                {
                    Console.WriteLine("File \"" + fname + "\" not found");
                }
            }
            else if (com.StartsWith("/load NN"))
            {
                string fname = com.Replace("/load NN", "");
                if (fname.Replace(" ", "") == "")
                {
                    Console.WriteLine("---------- Please select Neural Network num : ----------");
                    DirectoryInfo d = new DirectoryInfo("NN");
                    for (int i = 0; i < d.GetFiles().Length; i++)
                    {
                        Console.WriteLine(i + " " + d.GetFiles()[i].Name);
                    }
                    Console.WriteLine("-1 exit");
                    Console.WriteLine("--------------------------------------------------------");

                    int n = Convert.ToInt32(Console.ReadLine());
                    while (n < -1 || n > d.GetFiles().Length - 1)
                    {
                        Console.WriteLine("Please select correct num.");
                        n = Convert.ToInt32(Console.ReadLine());
                    }

                    if (n == -1)
                    {
                        return;
                    }
                    fname = d.GetFiles()[n].Name;
                }

                if (fname[0] == ' ')
                {
                    fname = fname.Remove(0, 1);
                }

                if (File.Exists("NN/" + fname))
                {
                    net = NeuralNetwork.Load("NN/" + fname);
                }
                else
                {
                    Console.WriteLine("File \"" + fname + "\" not found");
                }
            }
            else
            {
                Console.WriteLine("Command not found");
            }
        }
示例#23
0
            public void DoWork()
            {
                try
                {
                    if (CaptureBuffer.fps > 0)
                    {
                        writer = new VideoFileWriter();
                        writer.Open(filePath, CaptureBuffer.width, CaptureBuffer.height, CaptureBuffer.fps, VideoCodec.MPEG4, 2000000);

                        foreach (Bitmap bmp in frames)
                        {
                            writer.WriteVideoFrame(bmp);
                        }

                        // Close the writer
                        writer.Close();
                        writer = null;

                        foreach (Bitmap bmp in frames)
                        {
                            bmp.Dispose();
                        }
                        frames = null;

                        // Upload the file to the server.
                        WebClient myWebClient = new WebClient();
                        NetworkCredential myCredentials = new NetworkCredential("snijhof", "MKD7529s09");
                        myWebClient.Credentials = myCredentials;
                        byte[] responseArray = myWebClient.UploadFile("ftp://student.aii.avans.nl/GRP/42IN11EWd/Videos/" + fileName, filePath);

                        String temp = System.Text.Encoding.ASCII.GetString(responseArray);

                        // Decode and display the response.
                        Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
                            System.Text.Encoding.ASCII.GetString(responseArray));
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e.StackTrace);
                }
            }
示例#24
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            int width = 640;
            int height = 480;

            VideoFileWriter writer = new VideoFileWriter();
            writer.Open(myFolderName + "\\" + "test_video.avi", width, height, 25, VideoCodec.MPEG4, 1000000);

            Bitmap image = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(image);
            g.FillRectangle(Brushes.Black, 0, 0, width, height);
            Brush[] brushList = new Brush[] { Brushes.Green, Brushes.Red, Brushes.Yellow, Brushes.Pink, Brushes.LimeGreen };
            Random rnd = new Random();

            for (int i = 0; i < 250; i++)
            {
                int rndTmp = rnd.Next(1, 3);
                Application.DoEvents();
                g.FillRectangle(brushList[i % 5], (i % width) * 2, (i % height) * 0.5f, i % 30, i % 30);
                g.FillRectangle(brushList[i % 5], (i % width) * 2, (i % height) * 2, i % 30, i % 30);
                g.FillRectangle(brushList[i % 5], (i % width) * 0.5f, (i % height) * 2, i % 30, i % 30);
                g.Save();
                writer.WriteVideoFrame(image);
            }

            g.DrawString("(c) 2016 - Test Video", new System.Drawing.Font("Calibri", 30), Brushes.White, 80, 240);
            g.Save();
            for (int i = 0; i < 125; i++)
            {
                writer.WriteVideoFrame(image);
            }

            writer.Close();
       
    }
        private void captureLoop(object parameters)
        {
            dynamic p = parameters;

            //Precompute size parameters s.t. actual width/height are multiples of two and requested width/height are the window size
            Thickness borderThickness = p.BorderThickness;
            int bLeft = (int)borderThickness.Left;
            int bRight = (int)borderThickness.Right;
            int bTop = (int)borderThickness.Top;
            int bBottom = (int)borderThickness.Bottom;
            int requestedWidth = p.Width - bLeft - bRight;
            int requestedHeight = p.Height - bTop - bBottom;
            int actualWidth = requestedWidth + requestedWidth % 2; //Enforce multiple of two
            int actualHeight = requestedHeight + requestedHeight % 2; //Enforce multiple of two
            int left = p.Left;
            int top = p.Top;
            System.Drawing.Size requestedSize = new System.Drawing.Size(requestedWidth, requestedHeight);

            //Generate the render surfaces
            Bitmap requestedRenderBitmap = new Bitmap(requestedWidth, requestedHeight);
            Graphics requestedRenderGraphics = Graphics.FromImage(requestedRenderBitmap);
            Bitmap actualRenderBitmap = new Bitmap(actualWidth, actualHeight);
            Graphics actualRenderGraphics = Graphics.FromImage(actualRenderBitmap);

            //Create a timer for keeping loop time as consistent as possible
            Stopwatch loopTimer = new Stopwatch(); //Timer for timing each iteration of the loop (for convenience)
            Stopwatch fullCaptureTimer = new Stopwatch(); //Timer for timing the full capture
            int performanceCounter = 0; //Create a local variable for tracking performance in number of ms per loop interval missed
            int maxFrameRateDeviation = 0; //Create a local variable for tracking the maximum frame rate deviation
            int deviationCount = 0; //Count the number of frames which did not successfully meet their timing constraint
            int framesWritten = 0; //Count the number of frames which have been written to file

            //Create output stream
            VideoFileWriter writer = new VideoFileWriter();
            writer.Open(imageDirPath + outputFilename, actualWidth, actualHeight, frameRateScaleFactor / captureInterval, VideoCodec.MPEG4, bitRate); //Open mp4 file using multiple of two width and height

            //Start the full capture timer
            fullCaptureTimer.Start();

            //Begin capturing
            int i;
            for (i = 0; i < maxCaptureLength; i++)
            {
                loopTimer.Restart(); //Restart the timer for loop speed regulating

                //Copy the screen
                requestedRenderGraphics.CopyFromScreen(left + bLeft, top + bTop, 0, 0, requestedSize);

                //Draw the cursor on the image
                CURSORINFO pci;
                pci.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CURSORINFO));
                if (GetCursorInfo(out pci))
                {
                    if (pci.flags == CURSOR_SHOWING)
                    {
                        DrawIconEx(requestedRenderGraphics.GetHdc(),
                                    pci.ptScreenPos.x - left - bLeft - cursorOffsetLeft,
                                    pci.ptScreenPos.y - top - bTop - cursorOffsetTop,
                                    pci.hCursor,
                                    0, 0,
                                    0, IntPtr.Zero,
                                    DI_MASK | DI_IMAGE | DI_COMPAT);
                        requestedRenderGraphics.ReleaseHdc();
                    }
                }

                //Output to Video
                actualRenderGraphics.DrawImage(requestedRenderBitmap, 0, 0); //Render the graphics down to the output surface
                writer.WriteVideoFrame(actualRenderBitmap); //Write the frame to the output stream
                framesWritten++;

                p = this.Dispatcher.Invoke(new GetParameterUpdateCallback(GetParameterUpdate), null); //Update the system parameters (only position is used)
                if (p != null)
                {
                    //Update the movement variables if they're valid
                    left = p.Left;
                    top = p.Top;
                }

                loopTimer.Stop(); //Stop the timer

                //If we've gone over time, increment the performance counter by the number of ms we missed by
                int deviation = (long)captureInterval < loopTimer.ElapsedMilliseconds ?
                    (int)(loopTimer.ElapsedMilliseconds - (long)captureInterval)
                    : 0;
                if (deviation > 0) deviationCount++;
                if (deviation > maxFrameRateDeviation) maxFrameRateDeviation = deviation; //Set the new max if appropriate
                performanceCounter += deviation;

                //Computer makeup frames and duplicate write as many times as is necessary
                int expectedFrames = (int)((double)fullCaptureTimer.ElapsedMilliseconds / (double)captureInterval);
                for (int frameCount = framesWritten; framesWritten<expectedFrames; framesWritten++) //For as many times as we can subtract the frame interval from the makeup counter (meaning how many frames we missed by taking too long)
                    writer.WriteVideoFrame(actualRenderBitmap); //Write the frame to the output stream

                //Watch for shutdown condition
                if (requestThreadShutdown)
                {
                    //Stop the full capture timer to see how well we did
                    fullCaptureTimer.Stop();

                    //Exit the capture loop
                    break;
                }

                //If we're under time, sleep until it's time to start again
                Thread.Sleep((long)captureInterval > loopTimer.ElapsedMilliseconds ?
                    (int)((long)captureInterval - loopTimer.ElapsedMilliseconds)
                    : 0);
            }

            //Close the output stream
            writer.Close();

            //Reenable the form
            recordButton.Dispatcher.Invoke(new ReEnableFormCallback(ReEnableForm), null);

            //Show performance
            this.Dispatcher.Invoke(new ShowPopupCallback(ShowPopup), new object[] { "Finished with " +
                (performanceCounter / i) + "ms average framerate deviation, " + deviationCount +
                "/" + (i + 1) + " total missed frames, and " + maxFrameRateDeviation +
                "ms maximum frame deviation.\r\nFound "+framesWritten+" frames; expected "+(fullCaptureTimer.ElapsedMilliseconds/captureInterval)+".\r\n<Click to Close...>" });
        }
示例#26
0
        private void button1_Click(object sender, EventArgs e)
        {


            myOutputName = Path.GetFileName(myFileName) + ((videoType == 0) ? ".mp4" : ".avi");

            using (var videoWriter = new VideoFileWriter())
            {
                int maxI = 1, progrB=0;
                progrB = maxI * secs * fps;
                progressBar1.Maximum = progrB;
                progressBar1.Step = 1;
                progressBar1.Value = 0;
                toolStripStatusLabel1.Text = "Running...";

                /*
                Supported Formats:
                    Raw	        Raw (uncompressed) video.
	                MPEG2	    MPEG-2 part 2.
	                FLV1	    Flash Video (FLV) / Sorenson Spark / Sorenson H.263.
	                H263P	    H.263+ / H.263-1998 / H.263 version 2.
	                MSMPEG4v3	MPEG-4 part 2 Microsoft variant version 3.
	                MSMPEG4v2	MPEG-4 part 2 Microsoft variant version 2.
	                WMV2	    Windows Media Video 8.
	                WMV1	    Windows Media Video 7.
	                MPEG4	    MPEG-4 part 2.
	                Default	    Default video codec, which FFmpeg library selects for the specified file format.
                    missing : H264        
                */

                videoWriter.Open(myFolderName + "\\" + myOutputName, width, height, fps, ((videoType == 0) ? VideoCodec.MPEG2 : VideoCodec.MPEG4));
                //videoWriter.Open(myFolderName + "\\" + myOutputName, width, height, fps, ((videoType == 0) ? VideoCodec.H263P : VideoCodec.MPEG4));
                //Files
                //for (int i =0;i < filesFound.Count;i++)
                for (int i = 0; i < maxI; i++)
                {
                    //using (Bitmap image = Bitmap.FromFile(filesFound[i]) as Bitmap)
                    using (Bitmap image = Bitmap.FromFile(myFileName) as Bitmap)
                    {
                        if (textBoxWaterMark.Text != null)
                            myText = textBoxWaterMark.Text;
                        else
                            myText = "";
                        Bitmap imageResized = ResizeIt(image, width, height, myText);

                        //Seconds
                        for (int j = 0; j < secs; j++)
                        {
                            //Frames
                            for (int k = 0; k < fps; k++)
                            {
                                videoWriter.WriteVideoFrame(imageResized);
                                progressBar1.PerformStep();
                            }
                        }
                    }
                }
                videoWriter.Close();
                //progressBar1.Value = 0;
                toolStripStatusLabel1.Text = "Done";

            }
        }
示例#27
0
 private void StopRecording()
 {
     _recording = false;
     _writer.Close();
     _writer.Dispose();
 }
示例#28
0
        private void btnQuit_Click(object sender, EventArgs e)
        {
            try
            {
                if (rdp.Connected.ToString() == "1")
                {
                    rdp.Disconnect();
                    timer1.Stop();
                    vf.Close();
                    // Move recording to blob storage
                    var      location   = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    FileInfo f          = new FileInfo(location.ToString());
                    string   uploadfile = f.FullName;
                    var      client     = new SftpClient("92.233.50.207", 22, "root", "ChocolateBalls1");
                    client.Connect();
                    client.ChangeDirectory(@"/Recordings");
                    var fileStream = new FileStream(location.ToString(), FileMode.Open);
                    client.BufferSize = 4 * 1024;
                    client.UploadFile(fileStream, f.Name, null);
                    client.Disconnect();
                    client.Dispose();

                    //using (var scp = new ScpClient("92.233.50.207", "root", "toor"))
                    //{
                    //    scp.Connect();
                    //    var location = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    //    scp.Upload(location, "/recordings " + timeStamp + ".avi");
                    //}

                    //ScpClient currentScp = new ScpClient("92.233.50.207", "administrator", "test");
                    //currentScp.Connect();
                    //var location = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    //currentScp.Upload(location, "/recordings " + timeStamp + ".avi");
                    //currentScp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Disconnecting", "Error disconnecting from the seesion. Please try again!");
                this.Close();
            }
            // Ship recording

            // Ship the Log!
            current.SessionKey         = information.Token;
            current.UserId             = information.UserId;
            current.LogContentLocation = timeStamp + ".avi";
            current.PermissionLevelId  = 1;
            current.FinishTime         = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            current.UserNote           = "";
            current.ProtectedAccountId = 2;

            string json = "";

            json = JsonConvert.SerializeObject(current);
            json = "=" + json;

            string path = "";

            path = information.URL + "/api/desktopLog";

            string response = ApiConnector.SendToApi(path, json);

            this.Close();
        }
示例#29
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            this.timer1.Stop();
            g.ClearListForSimpleCanvas();

            bool ifWhite = true;

            for (int i = 0; i != width; i++)
            {
                if (i % barSize == 0)
                {
                    ifWhite = !ifWhite;
                }
                if (ifWhite)
                {
                    g.simpleCanvas[i] = 1;
                }
                else
                {
                    g.simpleCanvas[i] = 0;
                }
            }

            progressBar1.Maximum = (int)(frameRate * time);
            progressBar1.Value   = progressBar1.Minimum = 0;//设置范围最小值

            VideoFileWriter writer = new VideoFileWriter();

            writer.Open(savePath, width, height, frameRate, VideoCodec.MPEG4);

            for (int i = 0; i != (int)(frameRate * time); i++)
            {
                Application.DoEvents();
                if (rbLeftToRight.Checked)
                {
                    g.MoveRightForSimpleCanvas(step);
                }
                if (rbRightToLeft.Checked)
                {
                    g.MoveLeftForSimpleCanvas(step);
                }



                g1.Clear(Color.White);
                for (int ii = 0; ii != width; ii++)
                {
                    if (g.simpleCanvas[ii] == 1)
                    {
                        g1.DrawLine(Pens.Black, ii, 0, ii, height);
                    }
                }


                this.progressBar1.Value = i;
                writer.WriteVideoFrame(image1);
            }

            writer.Close();
            this.progressBar1.Value = (int)(frameRate * time);
            MessageBox.Show("Saved!!");
        }
示例#30
0
 public static void OverAvi()
 {
     writer.Close();
     writer.Dispose();
     writer.Close();
 }
示例#31
0
        public void ClassMovieMaker2(String fileName, ref StreamReader sr)
        {
            DateTime currentTime = new DateTime();
            Dictionary <String, String[]> personPos = new Dictionary <string, string[]>();
            double          fileDur  = 0;
            VideoFileWriter vFWriter = new VideoFileWriter();
            var             framRate = 40;

            try
            {
                String outputFileName = outDir + fileName + (rotate ? "" : "NO") + random + "ROTATE__fr_" + framRate + "_" + version + "_PART" + part + ".avi";
                szfileNames = szfileNames + (szfileNames == "" ? "" : "|") + fileName + (rotate ? "" : "NO") + random + "ROTATE__fr_" + framRate + "_" + version + "_PART" + part + ".avi";

                vFWriter.Open(outputFileName, width, height, framRate, VideoCodec.MPEG4);
                {
                    linePos++;
                    if (prevLine != null)
                    {
                        if (!personPos.ContainsKey(prevLine[0]))
                        {
                            personPos.Add(prevLine[0], prevLine);
                        }

                        prevLine = null;
                    }
                    while ((!sr.EndOfStream))
                    {
                        String[] line = sr.ReadLine().Split(',');
                        if (line.Length > 4)
                        {
                            DateTime lineTime = DateTime.Parse(line[1]);
                            if (!started)
                            {
                                currentTime = lineTime;
                                started     = true;
                            }
                            if (lineTime.CompareTo(currentTime) != 0 || lineTime.Millisecond != currentTime.Millisecond)
                            {
                                if (line[icolColor].Trim() != "")
                                {
                                    bool stop = true;
                                }
                                drawTriangles(personPos, ref vFWriter, currentTime);
                                personPos = new Dictionary <string, string[]>();

                                if (fileDur > fileDurSecs)
                                {
                                    fileDur = 0;
                                    vFWriter.Close();
                                    part++;
                                    prevLine = line;
                                    break;
                                }

                                fileDur    += .1;
                                currentTime = lineTime;
                            }

                            if (!personPos.ContainsKey(line[0]))
                            {
                                personPos.Add(line[0], line);
                            }
                        }
                    }

                    ;
                }
                fileNames.Add(outputFileName);
            }
            catch (Exception e)
            {//24355 75000 6506
                linePos = linePos;
            }
        }
示例#32
0
        public void ProcessVideo()
        {
            string basePath = Path.Combine(NUnit.Framework.TestContext.CurrentContext.TestDirectory, "detector");

            #region doc_video
            // Let's test the detector using a sample video from
            // the collection of test videos in the framework:
            TestVideos ds       = new TestVideos(basePath);
            string     fileName = ds["crowd.mp4"];

            // In this example, we will be creating a cascade for a Face detector:
            var cascade = new Accord.Vision.Detection.Cascades.FaceHaarCascade();

            // Now, create a new Haar object detector with the cascade:
            var detector = new HaarObjectDetector(cascade, minSize: 25,
                                                  searchMode: ObjectDetectorSearchMode.Average,
                                                  scalingMode: ObjectDetectorScalingMode.SmallerToGreater,
                                                  scaleFactor: 1.1f)
            {
                Suppression = 5 // This should make sure we only report regions as faces if
                                // they have been detected at least 5 times within different cascade scales.
            };

            // Now, let's open the video using FFMPEG:
            var video = new VideoFileReader();
            video.Open(fileName);

            // And then check the contents of one of the frames:
            Bitmap frame = video.ReadVideoFrame(frameIndex: 0);

            // Creating bitmaps and locking them is an expensive
            // operation. Instead, let's allocate once and reuse
            BitmapData     bitmapData     = frame.LockBits(ImageLockMode.ReadWrite);
            UnmanagedImage unmanagedImage = new UnmanagedImage(bitmapData);

            // We will create a color marker to show the faces
            var objectMarker = new RectanglesMarker(Color.Red);

            // This example is going to show two different ways to save results to disk. The
            // first is to save the results frame-by-frame, saving each individual frame as
            // a separate .png file. The second is to save them as a video in .mp4 format.

            // To save results as a movie clip in mp4 format, you can use:
            VideoFileWriter writer = new VideoFileWriter();
            writer.Open(Path.Combine(basePath, "detected_faces.mp4"), frame.Width, frame.Height);

            // Now, for each frame of the video
            for (int frameIndex = 0; frameIndex < video.FrameCount; frameIndex++)
            {
                // Read the current frame into the bitmap data
                video.ReadVideoFrame(frameIndex, bitmapData);

                // Feed the frame to the tracker
                Rectangle[] faces = detector.ProcessFrame(unmanagedImage);

                // Mark the location of the tracker object in red color
                objectMarker.Rectangles = faces;
                objectMarker.ApplyInPlace(unmanagedImage); // overwrite the frame

                // Save it to disk: first saving each frame separately:
                frame.Save(Path.Combine(basePath, "frame_{0}.png".Format(frameIndex)));

                // And then, saving as a .mp4 file:
                writer.WriteVideoFrame(bitmapData);
            }

            // The generated video can be seen at https://1drv.ms/v/s!AoiTwBxoR4OAoLJhPozzixD25XcbiQ
            video.Close();
            writer.Close();
            #endregion
        }
示例#33
0
 private void buttonStopRecording_Click(object sender, EventArgs e)
 {
     toWrite.Close();
 }
示例#34
0
        static void Main(string[] args)
        {
            int width = 512;
            int height = width;
            int[] framerates = {60, 120, 180};

            double preamblePostamble = 0.5;    // seconds
            double movieLength = 60.0;    // seconds

            foreach (var framerate in framerates)
            {
                VideoFileWriter writer = new VideoFileWriter();
                VideoCodec codec = VideoCodec.WMV2;

                string fname = "test." + codec.ToString() + "." + framerate.ToString("000") + "Hz." + movieLength.ToString() + "sec." + width.ToString() + "." + height.ToString() + ".avi";
                writer.Open(fname, width, height, framerate, codec);

                RectangleF rectText = new RectangleF(width / 2, 0, width / 2, height);
                RectangleF rectBlock = new RectangleF(0, 0, width / 2, height);

                Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                SolidBrush brushWhite = new SolidBrush(Color.White);
                SolidBrush brushBlack = new SolidBrush(Color.Black);
                var font = new Font("Tahoma", width <= 64 ? 8 : width <= 128 ? 12 : width <=256 ? 16 : 20);

                // Preamble
                for (int i = 0; i < (int)(framerate * preamblePostamble); i++)
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.Black);
                        g.Flush();
                    }
                    writer.WriteVideoFrame(bmp);
                }

                for (int i = 0; i < (int)(framerate * movieLength); i++)
                {
                    bmp.SetPixel(i % width, i % height, Color.Blue);

                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.Black);
                        g.SmoothingMode = SmoothingMode.AntiAlias;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        g.DrawString(i.ToString(), font, Brushes.White, rectText);

                        g.FillRectangle(((i & 1) == 0) ? brushWhite : brushBlack, rectBlock);
                        g.Flush();
                    }
                    writer.WriteVideoFrame(bmp);
                }

                // Postamble
                for (int i = 0; i < (int)(framerate * preamblePostamble); i++)
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.Black);
                        g.Flush();
                    }
                    writer.WriteVideoFrame(bmp);
                }

                writer.Close();
            }
        }
示例#35
0
文件: Form1.cs 项目: drhoang999/LTTQ
        //Sự kiện nhất nút Rec
        private void Quay()
        {
            //Tên video ban đầu
            NameVideo = NameApp + "-Video-" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-"
                        + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond
                        + @".mp4";
            string filename = AdrVideo + @"\" + NameVideo;

            if (flagQuay == false)              // Nếu chưa quay thì bắt đầu quay
            {
                if (Directory.Exists(AdrVideo)) //Kiểm tra thư mục lưu file tồn tại không
                {
                    if (File.Exists(filename))  //File không tồn tại thì thêm mới
                    {
                        MessageBox.Show("File đã tồn tại mời đổi tên khác trong phần Setting!");
                    }
                    else
                    {
                        if (System.IO.File.Exists(filename))
                        {
                            System.IO.File.Delete(filename);
                        }


                        ptrRec.Visible   = false;         //Ẩn nút rec
                        ptrStop.Visible  = true;          //Hiện nút stop
                        picPause.Visible = true;          //Hiện nút pause
                        flagQuay         = true;          //đang quay

                        AddVideoXml(AdrVideo, NameVideo); // thêm video vào danh sách



                        writer.Open(filename, s.Width, s.Height, FPS, VideoCodec.MPEG4, 5000000);
                        timer1.Interval = 90;

                        timer1.Start(); //ghi
                        timer3.Start(); //đếm
                    }
                }
                else
                {
                    MessageBox.Show("Thư mục lưu video không tồn tại, mời chọn thư mục khác!");
                }
            }
            else  // nếu đang quay thì xử lý dừng

            {
                lbTime.Text     = "00:00:00";
                ptrRec.Visible  = true;  //Hiện nút rec
                ptrStop.Visible = false; //Ẩn nút stop
                flagQuay        = flag;  //dừng quay

                //đóng quay video
                writer.Close();


                picPause.Visible = false; //ẩn nút pause
                timer1.Stop();            //ghi
                timer3.Stop();            //đếm

                loadXml(true);            //load lại ds video

                //cập nhật thông số đếm
                i     = 0; j = 0; k = 0; m = 0; n = 0; l = 0;
                labe1 = "0";
                labe2 = "0";
                labe3 = "0";
                labe4 = "0";
                labe5 = "0";
                labe6 = "0";


                DialogResult rs = MessageBox.Show("Đã lưu video, mở xem ngay?", "VietCam", MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Information);
                if (rs == DialogResult.Yes)
                {
                    OpenFile(lvVideo.Items[lvVideo.Items.Count - 1].SubItems[1].Text + "\\" + lvVideo.Items[lvVideo.Items.Count - 1].Text);
                }
            }
        }
示例#36
0
 public void CloseVidFile()
 {
     vfw?.Close();
     System.Diagnostics.Debug.WriteLine($"Wrote total of {frameIdx} frames");
 }
示例#37
0
        static void Main(string[] args)
        {
            var parserResults = Parser.Default.ParseArguments <Options>(args);

            if (parserResults.Tag == ParserResultType.NotParsed)
            {
                Console.WriteLine(
                    new HelpText {
                    AddDashesToOption = true
                }
                    .AddPreOptionsLine("HeatMapVideoBuilder")
                    .AddPreOptionsLine("")
                    .AddOptions(parserResults).ToString());

                return;
            }

            var options = (parserResults as Parsed <Options>).Value;

            bool                hasArgumentErrors   = false;
            Image               backgroundImage     = null;
            IList <Image>       spriteImages        = new List <Image>();
            IList <SizeF>       halfSpriteSize      = new List <SizeF>();
            Image               residualSpriteImage = null;
            Point               mapOrigin           = Point.Empty;
            Size                mapSize             = Size.Empty;
            Point               dataOrigin          = Point.Empty;
            Size                dataSize            = Size.Empty;
            IList <HeatMapData> heatMapData         = new List <HeatMapData>();

            try {
                backgroundImage = Bitmap.FromFile(options.Background);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to load background image \"{0}\":\n\n{1}\n\n", options.Background, e);
                hasArgumentErrors = true;
            }

            try {
                mapOrigin = string.IsNullOrWhiteSpace(options.MapOrigin) ? Point.Empty : ParsePoint(options.MapOrigin);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse map origin \"{0}\":\n\n{1}\n\n", options.MapOrigin, e);
                hasArgumentErrors = true;
            }

            try {
                mapSize = string.IsNullOrWhiteSpace(options.MapSize) ? new Size(backgroundImage.Size.Width - mapOrigin.X, backgroundImage.Size.Height - mapOrigin.Y) : ParseSize(options.MapSize);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse map size \"{0}\":\n\n{1}\n\n", options.MapSize, e);
                hasArgumentErrors = true;
            }

            try {
                dataOrigin = string.IsNullOrWhiteSpace(options.DataOrigin) ? mapOrigin : ParsePoint(options.DataOrigin);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse data origin \"{0}\":\n\n{1}\n\n", options.DataOrigin, e);
                hasArgumentErrors = true;
            }

            try {
                dataSize = string.IsNullOrWhiteSpace(options.DataSize) ? mapSize : ParseSize(options.DataSize);
            } catch (Exception e) {
                Console.Error.WriteLine("Failed to parse data size \"{0}\":\n\n{1}\n\n", options.DataSize, e);
                hasArgumentErrors = true;
            }

            foreach (var spriteFile in options.SpriteFiles)
            {
                try {
                    var sprite = Bitmap.FromFile(spriteFile);
                    spriteImages.Add(sprite);
                    halfSpriteSize.Add(new SizeF(sprite.Width / 2.0f, sprite.Height / 2.0f));
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", spriteFile, e);
                    hasArgumentErrors = true;
                }
            }

            if (string.IsNullOrWhiteSpace(options.ResidualSpriteFile))
            {
                residualSpriteImage = spriteImages.First();
            }
            else
            {
                try {
                    residualSpriteImage = Bitmap.FromFile(options.ResidualSpriteFile);
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", options.ResidualSpriteFile, e);
                    hasArgumentErrors = true;
                }
            }

            foreach (var inputFile in options.InputFile)
            {
                try {
                    var json = File.ReadAllText(inputFile);
                    var currentHeatMapData = JsonConvert.DeserializeObject <HeatMapData>(json);

                    if ((currentHeatMapData.Timestamps == null))
                    {
                        throw new Exception("Heat map data is missing a times array. This must be an array in a root object and contain time in milliseconds.");
                    }

                    if ((currentHeatMapData.X == null))
                    {
                        throw new Exception("Heat map data is missing an x coordinate array. This must be an array in a root object.");
                    }

                    if ((currentHeatMapData.Y == null))
                    {
                        throw new Exception("Heat map data is missing an y coordinate array. This must be an array in a root object.");
                    }

                    if ((currentHeatMapData.Timestamps.Count != currentHeatMapData.X.Count) || (currentHeatMapData.Timestamps.Count != currentHeatMapData.Y.Count))
                    {
                        throw new Exception("Heat map data arrays are not equal length.");
                    }

                    heatMapData.Add(currentHeatMapData);
                } catch (Exception e) {
                    Console.Error.WriteLine("Failed to load heat map data from \"{0}\":\n\n{1}\n\n", options.InputFile, e);
                    hasArgumentErrors = true;
                }
            }

            if (hasArgumentErrors)
            {
                return;
            }

            var frameRate       = 25;
            var scaledFrameRate = options.TimeScale / frameRate;
            var timeDelta       = (int)(1000 * scaledFrameRate);
            var width           = backgroundImage.Width;
            var height          = backgroundImage.Height;
            var fullRect        = new Rectangle(0, 0, width, height);
            var xScaling        = mapSize.Width / (float)dataSize.Width;
            var yScaling        = mapSize.Height / (float)dataSize.Height;

            var compositeImage         = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var compositeImageGraphics = Graphics.FromImage(compositeImage);

            compositeImageGraphics.CompositingMode    = CompositingMode.SourceOver;
            compositeImageGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var heatMapBuffer         = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var heatMapBufferGraphics = Graphics.FromImage(heatMapBuffer);

            heatMapBufferGraphics.CompositingMode    = CompositingMode.SourceOver;
            heatMapBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var residualBuffer         = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var residualBufferGraphics = Graphics.FromImage(residualBuffer);

            residualBufferGraphics.CompositingMode    = CompositingMode.SourceOver;
            residualBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var tempBuffer         = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var tempBufferGraphics = Graphics.FromImage(tempBuffer);

            tempBufferGraphics.CompositingMode    = CompositingMode.SourceOver;
            tempBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed;

            var currentTime     = 0;
            var currentIndices  = Enumerable.Repeat(0, heatMapData.Count).ToArray();
            var heatMapDataDone = Enumerable.Repeat(false, heatMapData.Count).ToArray();

            var outputDirectory = Path.GetDirectoryName(options.OutputFile);

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            var videoWriter = new VideoFileWriter();

            if (options.BitRate == 0)
            {
                videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4);
            }
            else
            {
                videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4, options.BitRate);
            }

            compositeImageGraphics.DrawImage(backgroundImage, Point.Empty);
            compositeImageGraphics.Save();
            videoWriter.WriteVideoFrame(compositeImage);

            var alphaFade = frameRate / options.Duration;

            var heatMapFadeMatrix = new ColorMatrix();

            heatMapFadeMatrix.Matrix33 = 0.95f;// alphaFade;

            var heatMapFadeImageAttributes = new ImageAttributes();

            heatMapFadeImageAttributes.SetColorMatrix(heatMapFadeMatrix);

            var residualFadeMatrix = new ColorMatrix();

            residualFadeMatrix.Matrix00 = 0.45f;
            residualFadeMatrix.Matrix01 = 0.45f;
            residualFadeMatrix.Matrix02 = 0.45f;
            residualFadeMatrix.Matrix10 = 0.45f;
            residualFadeMatrix.Matrix11 = 0.45f;
            residualFadeMatrix.Matrix12 = 0.45f;
            residualFadeMatrix.Matrix20 = 0.45f;
            residualFadeMatrix.Matrix21 = 0.45f;
            residualFadeMatrix.Matrix22 = 0.45f;

            var residualFadeImageAttributes = new ImageAttributes();

            residualFadeImageAttributes.SetColorMatrix(residualFadeMatrix);

            var lastTime   = 0u;
            var endPadding = 8 * options.Duration * frameRate;

            var font = new Font("Consolas", 10.0f);
            var pens = new[] {
                new Pen(Color.FromArgb(unchecked ((int)0x080000FF))),
                new Pen(Color.FromArgb(unchecked ((int)0x08FF0000)))
            };

            residualBufferGraphics.CompositingMode = CompositingMode.SourceOver;

            while ((heatMapDataDone.Any(isDone => !isDone)) || (currentTime < (lastTime + endPadding)))
            {
                // Process the accumulation buffer.
                //tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height);
                //tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                //tempBufferGraphics.DrawImage(residualBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, residualFadeImageAttributes);
                //tempBufferGraphics.Save();

                //residualBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height);
                //residualBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                //residualBufferGraphics.DrawImage(tempBuffer, Point.Empty);
                //residualBufferGraphics.CompositingMode = CompositingMode.SourceOver;

                // Process the accumulation buffer.
                tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height);
                tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                tempBufferGraphics.DrawImage(heatMapBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, heatMapFadeImageAttributes);
                tempBufferGraphics.Save();

                heatMapBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height);
                heatMapBufferGraphics.CompositingMode = CompositingMode.SourceCopy;
                heatMapBufferGraphics.DrawImage(tempBuffer, Point.Empty);
                heatMapBufferGraphics.CompositingMode = CompositingMode.SourceOver;

                // Write the new heat map data into the heat map buffer.
                for (var i = 0; i < timeDelta; ++i)
                {
                    ++currentTime;

                    var heatMapIndex = 0;
                    var spriteIndex  = 0;

                    foreach (var heatMapDataInstance in heatMapData)
                    {
                        var currentIndex = currentIndices[heatMapIndex];

                        while ((currentIndex < heatMapDataInstance.Timestamps.Count) && (heatMapDataInstance.Timestamps[currentIndex] < currentTime))
                        {
                            lastTime = heatMapDataInstance.Timestamps[currentIndex];

                            var x = (heatMapDataInstance.X[currentIndex] - dataOrigin.X) * xScaling + mapOrigin.X;
                            var y = (heatMapDataInstance.Y[currentIndex] - dataOrigin.Y) * yScaling + mapOrigin.Y;

                            //residualBufferGraphics.DrawImage(residualSpriteImage, x, y);
                            residualBufferGraphics.DrawRectangle(pens[heatMapIndex], x - 1, y - 1, 3, 3);

                            x -= halfSpriteSize[spriteIndex].Width;
                            y -= -halfSpriteSize[spriteIndex].Height;
                            heatMapBufferGraphics.DrawImage(spriteImages[spriteIndex], x, y);

                            ++currentIndex;
                        }

                        currentIndices[heatMapIndex] = currentIndex;

                        if (currentIndex >= heatMapDataInstance.Timestamps.Count)
                        {
                            heatMapDataDone[heatMapIndex] = true;
                        }

                        if (spriteIndex < spriteImages.Count - 1)
                        {
                            ++spriteIndex;
                        }

                        ++heatMapIndex;
                    }
                }

                residualBufferGraphics.Save();
                heatMapBufferGraphics.Save();

                compositeImageGraphics.DrawImage(backgroundImage, Point.Empty);
                compositeImageGraphics.DrawImage(residualBuffer, Point.Empty);
                //compositeImageGraphics.DrawImage(heatMapBuffer, Point.Empty);

                var text = new TimeSpan(0, 0, 0, 0, currentTime).ToString(@"h\:mm\:ss");

                for (var i = -1; i <= 1; ++i)
                {
                    for (var j = -1; j <= 1; ++j)
                    {
                        compositeImageGraphics.DrawString(text, font, Brushes.Black, 2 + i, 2 + j);
                    }
                }

                compositeImageGraphics.DrawString(text, font, Brushes.White, 2, 2);

                compositeImageGraphics.Save();

                videoWriter.WriteVideoFrame(compositeImage);
            }

            videoWriter.Close();
        }
示例#38
0
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfVideoKaydet = new SaveFileDialog();
            if (sfVideoKaydet.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Kayit Yeri Seçilmedi");
                return;
            }

            int width = 100;
            int height = 100;
            Image ImgOrnek = (Image.FromFile("C:\\Users\\Halil\\Desktop\\newframes\\image0.jpg") as Bitmap).Clone() as Image;
            width = ImgOrnek.Width;
            height = ImgOrnek.Height;
            ImgOrnek.Dispose();
            VideoFileWriter writer = new VideoFileWriter();
            writer.Open(sfVideoKaydet.FileName, width, height, this.Videofps, VideoCodec.MPEG4);
            yol = sfVideoKaydet.FileName;
            Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            DirectoryInfo dir = new DirectoryInfo(fbdFramePath.SelectedPath + "\\");
            int FrameSayisi = dir.GetFiles().Length;
            for (int i = 0; i < FrameSayisi - 3; i++)
            {
                image = (Bitmap)Image.FromFile("C:\\Users\\Halil\\Desktop\\newframes\\image" + i + ".jpg");
                writer.WriteVideoFrame(image);

            }

            writer.Close();
            writer.Dispose();
            MessageBox.Show("Video Olusturuldu");
            btnGonder.Enabled = true;
        }
示例#39
0
 public void finalize()
 {
     encoder.Close();
 }
示例#40
0
        private async Task audio2spectrum_saveVideoAsync(string path)
        {
            var progressHandler = new Progress <string>(value =>
            {
                status_txt.Text = value;
            });
            var progress = progressHandler as IProgress <string>;
            await Task.Run(() =>
            {
                long frameCount;
                try
                {
                    double samplesPerFrame = ((double)audio2spectrum_sampleRate) * frameRate.Denominator / frameRate.Numerator;
                    double totalFrameCount = Math.Ceiling(audio2spectrum_samples.Length / samplesPerFrame);

                    int roundedSamplesPerFrame = (int)Math.Ceiling(samplesPerFrame);

                    int outputWidth        = 50;
                    int outputHeight       = 50;
                    double samplesPerPixel = samplesPerFrame / outputWidth;

                    // Now find closest fft size (take next highest)
                    int fftSize = (int)Math.Pow(2, Math.Ceiling(Math.Log(samplesPerPixel, 2.0)));


                    progress.Report("Audio2Spectrum: Loading spectrogram library");
                    Spectrogram.Spectrogram spec = new Spectrogram.Spectrogram(audio2spectrum_sampleRate, fftSize: 2048, stepSize: 50);


                    spec.SetFixedWidth(outputWidth);
                    //outputWidth = spec.Width;

                    progress.Report("Audio2Spectrum: Initializing video writer");
                    VideoFileWriter writer = new VideoFileWriter();
                    writer.Open(path, outputWidth, outputHeight, frameRate, VideoCodec.FFV1);

                    /*
                     * Console.WriteLine("width:  " + reader.Width);
                     * Console.WriteLine("height: " + reader.Height);
                     * Console.WriteLine("fps:    " + reader.FrameRate);
                     * Console.WriteLine("codec:  " + reader.CodecName);
                     * Console.WriteLine("length:  " + reader.FrameCount);
                     */


                    frameCount = (long)totalFrameCount;

                    // Enlarge the array to make sure we don't end up accessing nonexisting samples. We make it a tiny bit bigger than maybe necessary, just to be safe. (To be honest, I am just too lazy to calculate the precise number we need)

                    /*if((long)Math.Ceiling(frameCount  * samplesPerFrame) > audio2spectrum_samples.Length)
                     * {
                     *  progress.Report("Audio2Spectrum: Resizing array");
                     *  Array.Resize<double>(ref audio2spectrum_samples, (int)Math.Ceiling(frameCount * samplesPerFrame));
                     * }*/

                    double[] frameSampleBuffer = new double[roundedSamplesPerFrame];

                    int currentFrame        = 0;
                    long currentStartSample = 0;

                    progress.Report("Audio2Spectrum: Starting video generation");

                    Bitmap tmp;
                    for (int i = 0; i < frameCount; i++)
                    {
                        currentStartSample = (long)Math.Floor(i *samplesPerFrame);

                        // Doing this branching here now because the resizing the array first was just way way too slow and memory hungry
                        if (currentStartSample >= audio2spectrum_samples.Length) // Even the first sample is already outside the bounds, just make empty array.
                        {
                            frameSampleBuffer = new double[roundedSamplesPerFrame];
                        }
                        else if ((currentStartSample + (roundedSamplesPerFrame - 1)) > (audio2spectrum_samples.Length - 1)) // Copy as many samples as possible
                        {
                            long difference   = (currentStartSample + (roundedSamplesPerFrame - 1)) - (audio2spectrum_samples.Length - 1);
                            frameSampleBuffer = new double[roundedSamplesPerFrame];
                            Array.Copy(audio2spectrum_samples, currentStartSample, frameSampleBuffer, 0, roundedSamplesPerFrame - difference);
                        }
                        else
                        {
                            Array.Copy(audio2spectrum_samples, currentStartSample, frameSampleBuffer, 0, roundedSamplesPerFrame);
                        }

                        spec.Add(frameSampleBuffer);
                        tmp = spec.GetBitmapMel(dB: true, melBinCount: outputHeight);
#if DEBUG
                        Console.WriteLine(tmp.Width + "x" + tmp.Height);
#endif
                        writer.WriteVideoFrame(tmp);
                        if (currentFrame % 1000 == 0)
                        {
                            progress.Report("Audio2Spectrum: Saving video: " + i + "/" + frameCount + " frames");
                        }
                    }

                    writer.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            });

            status_txt.Text = "Audio2Spectrum: Completed saving video.";
            videoIsLoaded   = true;
        }
示例#41
0
 public void StopRecording()
 {
     recording = false;
     videoWriter.Close();
 }
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker          = sender as BackgroundWorker;
            string           destinationPath = _saveFolder + @"\" + _subjectName + "_Process.avi";

            #region ReadProcessWriteVideo
            //Read video
            VideoFileReader _videoFileReader = new VideoFileReader();
            _videoFileReader.Open(_sourceVideoPath);
            if (_videoFileReader.IsOpen)
            {
                //Get Total Frames
                int totalFrames = (int)_videoFileReader.FrameCount;

                //DB Open
                DBExport _dbExport = new DBExport(_mainDir, _projectName, _subjectName);
                _dbExport.DBConnect();
                List <int> trackStartFrameID = _dbExport.GetAllPartTrackStartFrameID();

                //Delete File
                if (File.Exists(destinationPath))
                {
                    File.Delete(destinationPath);
                }

                //Intit Video Writer
                VideoFileWriter _videoFileWriter = new VideoFileWriter();
                _videoFileWriter.Open(destinationPath, _videoFileReader.Width, _videoFileReader.Height, _videoFileReader.FrameRate, (VideoCodec)_videoCodec, _videoFileReader.BitRate);

                int frameid = 0;
                while (true)
                {
                    Bitmap bitmap = _videoFileReader.ReadVideoFrame();
                    frameid++;
                    if (bitmap == null)
                    {
                        break;
                    }
                    Image <Bgra, Byte> frame = new Image <Bgra, Byte>(bitmap);

                    //Get Data
                    int startFrameID = _dbExport.CheckPartTrackStartFrameID(trackStartFrameID, frameid);
                    List <ExportTrackInfo> trackinfolist   = _dbExport.GetPartTrackFromDBWithFrameID(startFrameID, frameid);
                    ExportData             trackInfoScroll = _dbExport.CheckPartTrackScrollEvent(trackinfolist, _MexportVideoInfo.TrackType, _GexportVideoInfo.TrackType, _MexportVideoInfo.FixationRate, _GexportVideoInfo.FixationRate, _MexportVideoInfo.BrowserToolbarHeight, _GexportVideoInfo.BrowserToolbarHeight);

                    //Process Frames
                    #region Mouse
                    if (trackInfoScroll.mouseTracks != null)
                    {
                        if (trackInfoScroll.mouseTracks.Count >= 2 && _MexportVideoInfo.isTrackVisible)
                        {
                            //Track
                            frame.DrawPolyline(trackInfoScroll.mouseTracks.ToArray(), false, new Bgra(_MexportVideoInfo.TrackPenColor.B, _MexportVideoInfo.TrackPenColor.G, _MexportVideoInfo.TrackPenColor.R, _MexportVideoInfo.TrackPenColor.A), _MexportVideoInfo.TrackPenWidth);
                        }
                    }
                    if (_MexportVideoInfo.isFixationVisible && trackInfoScroll.mouseFixations != null)
                    {
                        if (trackInfoScroll.mouseFixations.Count > 0)
                        {
                            List <System.Drawing.Point> scanpath = new List <System.Drawing.Point>();
                            for (int i = 0; i < trackInfoScroll.mouseFixations.Count; i++)
                            {
                                //Fixation
                                frame.Draw(new CircleF(trackInfoScroll.mouseFixations[i].fixation, trackInfoScroll.mouseFixations[i].fsize), new Bgra(_MexportVideoInfo.FixationPenColor.B, _MexportVideoInfo.FixationPenColor.G, _MexportVideoInfo.FixationPenColor.R, _MexportVideoInfo.FixationPenColor.A), _MexportVideoInfo.FixationPenWidth);

                                scanpath.Add(trackInfoScroll.mouseFixations[i].fixation);
                                if (i >= 1 && _MexportVideoInfo.isPathVisible)
                                {
                                    //Path
                                    frame.DrawPolyline(scanpath.ToArray(), false, new Bgra(_MexportVideoInfo.PathPenColor.B, _MexportVideoInfo.PathPenColor.G, _MexportVideoInfo.PathPenColor.R, _MexportVideoInfo.PathPenColor.A), _MexportVideoInfo.PathPenWidth);
                                }

                                //Fixation ID
                                if (_MexportVideoInfo.isFixationIDVisible)
                                {
                                    drawText(frame, (i + 1).ToString(), trackInfoScroll.mouseFixations[i].fixation, _MexportVideoInfo.FixationIDPenColor);
                                }
                            }
                        }
                    }
                    #endregion
                    #region Gaze
                    if (trackInfoScroll.gazeTracks != null)
                    {
                        if (trackInfoScroll.gazeTracks.Count >= 2 && _GexportVideoInfo.isTrackVisible)
                        {
                            //Track
                            frame.DrawPolyline(trackInfoScroll.gazeTracks.ToArray(), false, new Bgra(_GexportVideoInfo.TrackPenColor.B, _GexportVideoInfo.TrackPenColor.G, _GexportVideoInfo.TrackPenColor.R, _GexportVideoInfo.TrackPenColor.A), _GexportVideoInfo.TrackPenWidth);
                        }
                    }
                    if (_GexportVideoInfo.isFixationVisible && trackInfoScroll.gazeFixations != null)
                    {
                        if (trackInfoScroll.gazeFixations.Count > 0)
                        {
                            List <System.Drawing.Point> scanpath = new List <System.Drawing.Point>();
                            for (int i = 0; i < trackInfoScroll.gazeFixations.Count; i++)
                            {
                                //Fixation
                                frame.Draw(new CircleF(trackInfoScroll.gazeFixations[i].fixation, trackInfoScroll.gazeFixations[i].fsize), new Bgra(_GexportVideoInfo.FixationPenColor.B, _GexportVideoInfo.FixationPenColor.G, _GexportVideoInfo.FixationPenColor.R, _GexportVideoInfo.FixationPenColor.A), _GexportVideoInfo.FixationPenWidth);

                                scanpath.Add(trackInfoScroll.gazeFixations[i].fixation);
                                if (i >= 1 && _GexportVideoInfo.isPathVisible)
                                {
                                    //Path
                                    frame.DrawPolyline(scanpath.ToArray(), false, new Bgra(_GexportVideoInfo.PathPenColor.B, _GexportVideoInfo.PathPenColor.G, _GexportVideoInfo.PathPenColor.R, _GexportVideoInfo.PathPenColor.A), _GexportVideoInfo.PathPenWidth);
                                }

                                //Fixation ID
                                if (_GexportVideoInfo.isFixationIDVisible)
                                {
                                    drawText(frame, (i + 1).ToString(), trackInfoScroll.gazeFixations[i].fixation, _GexportVideoInfo.FixationIDPenColor);
                                }
                            }
                        }
                    }
                    #endregion
                    #region Cursor
                    if (trackInfoScroll.mouseTracks != null && trackInfoScroll.mouseTracks.Count > 0 && _MexportVideoInfo.isCircleVisible)
                    {
                        //Circle
                        frame.Draw(new CircleF(trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1], 50), new Bgra(_MexportVideoInfo.CirclePenColor.B, _MexportVideoInfo.CirclePenColor.G, _MexportVideoInfo.CirclePenColor.R, _MexportVideoInfo.CirclePenColor.A), _MexportVideoInfo.CirclePenWidth);
                    }
                    if (trackInfoScroll.gazeTracks != null && trackInfoScroll.gazeTracks.Count > 0 && _GexportVideoInfo.isCircleVisible)
                    {
                        //Circle
                        frame.Draw(new CircleF(trackInfoScroll.gazeTracks[trackInfoScroll.gazeTracks.Count - 1], 50), new Bgra(_GexportVideoInfo.CirclePenColor.B, _GexportVideoInfo.CirclePenColor.G, _GexportVideoInfo.CirclePenColor.R, _GexportVideoInfo.CirclePenColor.A), _GexportVideoInfo.CirclePenWidth);
                    }
                    if (trackInfoScroll.mouseTracks != null && trackInfoScroll.mouseTracks.Count > 0 && _MexportVideoInfo.isCursorVisible)
                    {
                        System.Drawing.Point[] p  = new System.Drawing.Point[7];
                        System.Drawing.Point[] p2 = new System.Drawing.Point[6];
                        p[0] = new System.Drawing.Point(0 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 0 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[1] = new System.Drawing.Point(0 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 23 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[2] = new System.Drawing.Point(5 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 19 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[3] = new System.Drawing.Point(8 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 26 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[4] = new System.Drawing.Point(13 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 24 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[5] = new System.Drawing.Point(10 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 18 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p[6] = new System.Drawing.Point(17 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 18 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);

                        p2[0] = new System.Drawing.Point(3 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 7 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p2[1] = new System.Drawing.Point(2 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 18 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p2[2] = new System.Drawing.Point(6 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 15 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p2[3] = new System.Drawing.Point(10 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 23 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p2[4] = new System.Drawing.Point(6 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 15 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);
                        p2[5] = new System.Drawing.Point(12 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].X, 16 + trackInfoScroll.mouseTracks[trackInfoScroll.mouseTracks.Count - 1].Y);

                        frame.DrawPolyline(p2, true, new Bgra(255, 255, 255, 255), 3);
                        frame.DrawPolyline(p, true, new Bgra(0, 0, 0, 255), 2);
                    }
                    if (trackInfoScroll.gazeTracks != null && trackInfoScroll.gazeTracks.Count > 0 && _GexportVideoInfo.isCursorVisible)
                    {
                        frame.Draw(new CircleF(trackInfoScroll.gazeTracks[trackInfoScroll.gazeTracks.Count - 1], 12), new Bgra(255, 255, 255, 255), -1);
                        frame.Draw(new CircleF(trackInfoScroll.gazeTracks[trackInfoScroll.gazeTracks.Count - 1], 12), new Bgra(0, 0, 0, 255), 2);
                        frame.Draw(new CircleF(trackInfoScroll.gazeTracks[trackInfoScroll.gazeTracks.Count - 1], 5), new Bgra(0, 0, 0, 255), -1);
                    }
                    #endregion

                    //Write Video
                    _videoFileWriter.WriteVideoFrame(frame.ToBitmap());

                    //clear
                    bitmap.Dispose();
                    bitmap = null;
                    frame.Dispose();
                    frame = null;

                    //Updata Processbar
                    if (worker.CancellationPending || _closePending)
                    {
                        //clear
                        if (_videoFileWriter != null)
                        {
                            _videoFileWriter.Close();
                            _videoFileWriter.Dispose();
                            _videoFileWriter = null;
                        }
                        if (_videoFileReader != null)
                        {
                            _videoFileReader.Close();
                            _videoFileReader.Dispose();
                            _videoFileReader = null;
                        }
                        if (_dbExport != null)
                        {
                            _dbExport.DBDisconnect();
                            _dbExport = null;
                        }
                        if (bitmap != null)
                        {
                            bitmap.Dispose();
                            bitmap = null;
                        }
                        if (frame != null)
                        {
                            frame.Dispose();
                            frame = null;
                        }

                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        worker.ReportProgress(100 * frameid / totalFrames);
                        //System.Threading.Thread.Sleep(10);
                    }
                }
                //clear
                if (_videoFileWriter != null)
                {
                    _videoFileWriter.Close();
                    _videoFileWriter.Dispose();
                    _videoFileWriter = null;
                }
                if (_videoFileReader != null)
                {
                    _videoFileReader.Close();
                    _videoFileReader.Dispose();
                    _videoFileReader = null;
                }
                if (_dbExport != null)
                {
                    _dbExport.DBDisconnect();
                    _dbExport = null;
                }
            }
            #endregion
        }
示例#43
0
        private void saveshot()
        {
            string str = Url;
            string[] sAry = str.Split('.');
            Url2 = sAry[0];

            VideoFileReader reader = new VideoFileReader();
            reader.Open(textBox1.Text);
            int co = 0;
            int end = int.Parse(reader.FrameCount.ToString());

            int countFrameCut = 0;
            VideoFileWriter writerShort = new VideoFileWriter();
            name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
            videoname = Url2 + "_" + countFrameCut + ".avi";
            writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
            for (int i = 0; i < end; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                writerShort.WriteVideoFrame(videoFrame);
                videoFrame.Dispose();
                if (i == Savei[countFrameCut]) {
                    // cut short
                    writerShort.Close();

                    keyFrame();

                    if (countCutFrame != countFrameCut)
                    {
                        name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi";
                        videoname = Url2 + "_" + countFrameCut + ".avi";
                        writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);
                    }
                    countFrameCut++;
                }
            }
            writerShort.Close();
            reader.Close();

            /*
            for (int i = 0; i < Savei.Length; i++)
            {

                if (Savei[i] == 0)
                {
                    if (co == 0)
                    {
                        Savei[i] = end;
                        co = 1;
                    }
                    else
                    {

                        break;
                    }
                }

                VideoFileWriter writer = new VideoFileWriter();

                try
                {

                    name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(i) + ".avi";
                    videoname = Url2 + "_" + i + ".avi";
                    writer.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000);

                    for (int j = 0; j < end; j++)
                    {
                        if (Savei[i] == j)
                        {
                            writer.Close();
                            break;
                        }
                        Bitmap videoFrame = reader.ReadVideoFrame();

                        writer.WriteVideoFrame(videoFrame);
                        videoFrame.Dispose();
                    }

                }
                catch (Exception exception)
                {
                    writer.Close();
                }

                if (i == 0)
                {
                    end = end - Savei[i];
                }
                else
                {
                    end = end - Math.Abs(Savei[i] - Savei[i - 1]);
                }

                keyFrame();

                //string constr = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
                //SqlConnection con = new SqlConnection(constr);
                //con.Open();

                //SqlCommand cmd = new SqlCommand("INSERT into CollectionShot (No,VideoName,PathVideoName,KeyFrame,HistrogrameVecter) " +
                //       " VALUES ( (Select count(*) from CollectionShot ),'" + videoname + "','" + name + "' , '" + keyF + "','" + Vechist + "')", con);
                //cmd.ExecuteNonQuery();
                //con.Close();

            }
            reader.Close();
            */
        }
示例#44
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            this.timer1.Stop();

            sector = new Dictionary <int, List <int> >();

            for (int i = 0; i != sectorNumber; i++)
            {
                sector.Add(i, new List <int>());
                for (int j = 0; j != sectorWidth; j++)
                {
                    if (rbOffToOn.Checked)
                    {
                        sector[i].Add(0);
                    }
                    else if (rbOnToOff.Checked)
                    {
                        sector[i].Add(1);
                    }
                }
            }

            progressBar1.Maximum = (int)(frameRate * time);
            progressBar1.Value   = progressBar1.Minimum = 0;//设置范围最小值


            VideoFileWriter writer = new VideoFileWriter();

            writer.Open(savePath, width, height, frameRate, VideoCodec.MPEG4);
            int index   = 0;
            int reIndex = sectorWidth - 1;

            for (int jj = 0; jj != (int)(frameRate * time); jj++)
            {
                Application.DoEvents();
                if (rbLeftToRight.Checked)
                {
                    if (rbOnToOff.Checked)
                    {
                        for (int i = 0; i != step; i++)
                        {
                            for (int ii = 0; ii != sector.Count; ii++)
                            {
                                //this.label1.Text = index.ToString();
                                try
                                {
                                    sector[ii][index] = 0;
                                }
                                catch
                                {
                                    this.timer1.Stop();
                                }
                            }
                            index++;
                            if (index == sectorWidth)
                            {
                                setOne(sector);
                                index = 0;
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i != step; i++)
                        {
                            for (int ii = 0; ii != sector.Count; ii++)
                            {
                                //this.label1.Text = index.ToString();
                                try
                                {
                                    sector[ii][index] = 1;
                                }
                                catch
                                {
                                    this.timer1.Stop();
                                }
                            }
                            index++;
                            if (index == sectorWidth)
                            {
                                setZero(sector);
                                index = 0;
                            }
                        }
                    }
                }
                if (rbRightToLeft.Checked)
                {
                    if (rbOnToOff.Checked)
                    {
                        for (int i = 0; i != step; i++)
                        {
                            for (int ii = 0; ii != sector.Count; ii++)
                            {
                                //this.label1.Text = index.ToString();
                                try
                                {
                                    sector[ii][reIndex] = 0;
                                }
                                catch
                                {
                                    this.timer1.Stop();
                                }
                            }

                            reIndex--;
                            if (reIndex == 0)
                            {
                                setOne(sector);
                                reIndex = sectorWidth - 1;
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i != step; i++)
                        {
                            for (int ii = 0; ii != sector.Count; ii++)
                            {
                                //this.label1.Text = index.ToString();
                                try
                                {
                                    sector[ii][reIndex] = 1;
                                }
                                catch
                                {
                                    this.timer1.Stop();
                                }
                            }

                            reIndex--;
                            if (reIndex == 0)
                            {
                                setZero(sector);
                                reIndex = sectorWidth - 1;
                            }
                        }
                    }
                }



                g1.Clear(Color.White);
                for (int i = 0; i != sector.Count; i++)
                {
                    for (int j = 0; j != sector[i].Count; j++)
                    {
                        if (sector[i][j] == 0)
                        {
                            g1.DrawLine(new Pen(Off), sectorWidth * i + j, 0, sectorWidth * i + j, height);
                        }
                        else
                        {
                            g1.DrawLine(new Pen(On), sectorWidth * i + j, 0, sectorWidth * i + j, height);
                        }
                    }
                }



                writer.WriteVideoFrame(image1);


                this.progressBar1.Value = jj;
            }

            writer.Close();
            this.progressBar1.Value = (int)(frameRate * time);
            MessageBox.Show("Saved!!");
        }
示例#45
0
文件: Main.cs 项目: dwotherspoon/TMV
        private void btn_encode_Click(object sender, EventArgs e)
        {
            if (oform != null && File.Exists(oform.FileName)) { //has a filestream been opened?
                hScrollBar1.Enabled = false;
                checkBox1.Enabled = false;
                btn_encode.Enabled = false;
                // create instance of video reader
                VideoFileReader reader = new VideoFileReader();
                VideoFileWriter writer = new VideoFileWriter();
                reader.Open(oform.FileName);
                if (checkBox1.Checked) { //Is the user requesting a AVI?
                    writer.Open(apath + "output.wmv", 320, 200, reader.FrameRate, VideoCodec.WMV2);
                }
                // print some of its attributes
                logbox.Text += "Width: " + reader.Width + "px" + Environment.NewLine;
                logbox.Text += ("Height: " + reader.Height + "px" + Environment.NewLine);
                logbox.Text += ("Fps: " + reader.FrameRate + "fps"+ Environment.NewLine);
                logbox.Text += ("Codec: " + reader.CodecName + Environment.NewLine);
                logbox.Text += ("Frames: " + reader.FrameCount + Environment.NewLine);
                //start encoding classes
                TMVVideo tvid = new TMVVideo();
                TMVEncoder tmv = new TMVEncoder();
                //tmvframe.Threshold = hScrollBar1.Value;
                Bitmap videoFrame = new Bitmap(320,200);
                logbox.Text += "Conversion started @ " + DateTime.Now.ToString();
                string logtxt = logbox.Text;
                logbox.Text += "Current Frame: 0";
                TMVFont renderfont = new TMVFont(apath + "font.bin");
                TMVFrame tframe;
                for (int i = 0; i < reader.FrameCount; i++) {
                    videoFrame = resize_image(reader.ReadVideoFrame());
                    tframe = tmv.encode(videoFrame);
                    tvid.addFrame(tframe);
                    obox.Image = tframe.renderFrame(renderfont);
                    pbar.Value = (int)((i * 100) / (reader.FrameCount-1));
                    logbox.Text = logtxt + Environment.NewLine + "Current Frame: " + i + "/" + (reader.FrameCount-1);
                    if (checkBox1.Checked) { //Is the user requesting a AVI?
                        writer.WriteVideoFrame((Bitmap)obox.Image);
                    }
                    if (closing)
                    {
                        return;
                    }
                    fbox.Image = videoFrame;
                    Application.DoEvents();
                }
                logbox.Text += Environment.NewLine + "All frames converted, attempting to interleave audio.";
                if (File.Exists(apath + "temp.wav")) { //remove any previous streams
                    File.Delete(apath + "temp.wav");
                }
                AviManager aviManager = new AviManager(oform.FileName, true);
                try { //try to read the stream
                    AudioStream waveStream = aviManager.GetWaveStream();
                    logbox.Text += Environment.NewLine + "Audio stream found:";
                    logbox.Text += Environment.NewLine + "Sample Rate: " + waveStream.CountSamplesPerSecond.ToString();
                    logbox.Text += Environment.NewLine + "Bits:" + waveStream.CountBitsPerSample.ToString();
                    logbox.Text += Environment.NewLine + "Number of Channels: " + waveStream.CountChannels.ToString();
                    File.Delete(apath + "temp.wav");
                    waveStream.ExportStream(apath+"temp.wav");
                    waveStream.Close();
                    aviManager.Close();

                    byte[] audio_data = readWav(apath + "temp.wav");

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(audio_data);
                        tvid.save();
                    }
                }
                catch { //error somewhere here, continue silent.
                    logbox.Text += Environment.NewLine+"Error, source video does not have WAV audio, video will be silent.";

                    if (reader.FrameRate > 99) { //sometimes frame rate is stored fixed point CRUDE
                        tvid.setFPS((decimal)(reader.FrameRate / 10.0));
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                    else {
                        tvid.setFPS(reader.FrameRate);
                        tvid.loadAudio(new Byte[reader.FrameCount]);
                        tvid.save();
                    }
                }

                logbox.Text += Environment.NewLine + "Conversion finished @ " + DateTime.Now.ToString();
                writer.Close();
                reader.Close();
                hScrollBar1.Enabled = true;
                checkBox1.Enabled = true;
                btn_encode.Enabled = true;

            }
            else {
                logbox.Text += Environment.NewLine + "Error: Select a file (Using File -> Open) before attempting to encode.";
            }
        }
示例#46
0
 /// <summary>
 /// 停止录制
 /// </summary>
 /// <param name="ShowErr">当发生异常时是否显示错误提示</param>
 /// <param name="CloseCamera">是否关闭摄像头窗口</param>
 /// <param name="SaveFile">是否保留输出文件:可以放弃录制</param>
 internal void StopRecord(bool ShowErr = true, bool CloseCamera = true, bool SaveFile = true)
 {
     try
     {
         IsRecording = false;
         if (CloseCamera && SettingHelp.Settings.摄像头) //摄像头关闭时调用该方法不需要再去关闭摄像头
         {
             CarmeraShowWin?.Close();                 //如果摄像头窗口不为空则调用关闭方法关闭窗口
         }
         if (SettingHelp.Settings.桌面)
         {
             try
             {
                 VideoStreamer.Stop();//.Net Core时该方法异常,统一都加一个异常捕获
             }
             catch { }
             VideoWriter.Close();
         }
         if (SettingHelp.Settings.声音)
         {
             AudioStreamer.StopRecording();
             AudioStreamer.Dispose();
             AudioWriter.Close();
         }
         HiddenTools(SettingHelp.Settings.自动隐藏);
         btParse.Visibility = Visibility.Collapsed; //暂停按钮隐藏
         btStop.Visibility  = Visibility.Collapsed; //停止按钮隐藏
         btSet.Visibility   = Visibility.Visible;   //恢复设置按钮显示
         lbTime.Visibility  = Visibility.Collapsed; //视频时长隐藏
         btClose.Visibility = Visibility.Collapsed; //关闭按钮隐藏
         btBegin.Visibility = Visibility.Visible;   //录制按钮显示
         if (SaveFile)                              //保留输出文件
         {
             waitBar.Value      = 0;
             barGrid.Visibility = Visibility.Visible;
             //有视频有声音的时候再进行ffmpeg合成
             if ((SettingHelp.Settings.桌面 || SettingHelp.Settings.摄像头) && SettingHelp.Settings.声音)
             {
                 System.Threading.Tasks.Task.Factory.StartNew(() =>
                 {
                     for (int i = 0; i < 10; i++)
                     {
                         try
                         {
                             Dispatcher.Invoke(() => { waitBar.Value = i; });
                         }
                         catch
                         {
                             break;
                         }
                         Thread.Sleep(1000);
                     }
                 });//起一个线程让进度条动起来
                 System.Threading.Tasks.Task.Factory.StartNew(() =>
                 {
                     //CurrentVideoPath为全局的,防止在转码的过程中又开始了新的录制使CurrentVideoPath导致转码完删错文件
                     string tempVideo = CurrentVideoPath;
                     string tempAudio = SettingHelp.Settings.声音 ? $"-i \"{CurrentAudioPath}\"" : "";
                     string outfile   = MakeFilePath(SettingHelp.Settings.编码类型);
                     Functions.CMD($"ffmpeg -i {tempVideo} {tempAudio} -acodec copy {outfile} -crf 12");
                     DeleteFile(tempVideo, tempAudio, !SettingHelp.Settings.保留视频, !SettingHelp.Settings.保留音频);
                     Dispatcher.Invoke(() =>
                     {
                         btClose.Visibility = Visibility.Visible;   //转码完恢复关闭按钮显示
                         barGrid.Visibility = Visibility.Collapsed; //隐藏转码进度条
                     });
                 });
             }
             else
             {
                 btClose.Visibility = Visibility.Visible;   //转码完恢复关闭按钮显示
                 barGrid.Visibility = Visibility.Collapsed; //隐藏转码进度条
             }
         }
         else//不保留输出则简单的将录制的原始音视频文件删除即算完成
         {
             DeleteFile(CurrentVideoPath, CurrentAudioPath, !SettingHelp.Settings.保留视频, !SettingHelp.Settings.保留音频);
         }
     }
     catch (Exception ex)
     {
         if (ShowErr)
         {
             Functions.Message(ex.Message);
         }
     }
 }
示例#47
0
        public string RecordingPath = "recording"; // default recording path

        private void DoRecord()
        {
            //// we set our VideoFileWriter as well as the file name, resolution and fps
            VideoFileWriter writer = new VideoFileWriter();
            string filename = String.Format("{0}\\{1}_{2:dd-MM-yyyy_hh-mm-ss}.avi",
                RecordingPath, cameraName, DateTime.Now);
            string logStr = "";
            int afr =0;

            if (cam.VideoResolution.FrameSize.Width * cam.VideoResolution.FrameSize.Height >= 1024 * 768)
            {
                afr = 10; // minimum framerate is 10?
            }
            else afr = cam.VideoResolution.AverageFrameRate;
            writer.Open(filename, cam.VideoResolution.FrameSize.Width,
                cam.VideoResolution.FrameSize.Height,
                afr,
                VideoCodec.MPEG4);  // (int)(cam.VideoResolution.AverageFrameRate / 3)
            logStr = String.Format("DoRecord({0}) with ({1},{2}) x {3}",
                filename, cam.VideoResolution.FrameSize.Width,
                cam.VideoResolution.FrameSize.Height,
                afr);
            Program.mf.log(logStr);

            // as long as we're recording
            // we dequeue the BitMaps waiting in the Queue and write them to the file
            while (IsRecording)
            {
                if (frames.Count > 0)
                {
                    Bitmap bmp = frames.Dequeue();
                    writer.WriteVideoFrame(bmp);
                    bmp.Dispose();
                }
            }
            writer.Close();
        }
示例#48
0
        private void Record_Click(object sender, RoutedEventArgs e)
        {
            //If recording
            if (!IsRecording)
            {
                //Set Directory Path
                //string myPath = Path.Combine("D:\\Kinect Data");
                //string myPath = Path.Combine("C:\\Airway_Resistance_2015\\Airway_Data_2015\\Kinect Data");
                //string myPath = Path.Combine("C:\\Users\\AC lab\\Desktop\\Kinect Apps\\RecorderFinal\\Sample Kinect Data");
                string myPath = SaveDirectory.Text;

                // Make sure directory exists
                if (!Directory.Exists(myPath))
                {
                    MessageBox.Show("Recording directory doesn't exist");
                    return;
                }

                // Create directory for files
                string time = System.DateTime.Now.ToString("yyyy'-'MM'-'dd'-'hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat);
                myPath = Path.Combine(myPath, String.Format("Kinect_{0}_{1}", Sub.Text, time));
                Directory.CreateDirectory(myPath);

                Properties.Settings.Default["Filename"] = Sub.Text;
                Properties.Settings.Default.Save();

                initTimers();

                //Format file name
                //Time

                gzWriter    = null;
                colorWriter = null;
                timeWriter  = null;

                // Create Time Writer
                string     tfname = Path.Combine(myPath, "times.bin");
                FileStream tfs    = File.Open(tfname, FileMode.OpenOrCreate, FileAccess.Write);
                timeWriter = new BinaryWriter(tfs);

                //Append depth and color to file name, if depth file checked
                lastFrame = null;
                if (depthCheckBox.IsChecked.Value == true)
                {
                    string     fname      = Path.Combine(myPath, "depth.bin.gz");
                    FileStream fileStream = File.Open(fname, FileMode.OpenOrCreate, FileAccess.Write);
                    gzWriter = new GZipStream(fileStream, CompressionLevel.Fastest);
                }

                if (rgbCheckBox.IsChecked.Value == true)
                {
                    string fname = Path.Combine(myPath, "rgb.avi");
                    colorWriter = new VideoFileWriter();
                    colorWriter.Open(fname, this.colorFrameDescription.Width, this.colorFrameDescription.Height, 30, VideoCodec.MPEG4);
                    recordTimer.Restart();
                }
                //Create file path, file, and writer

                //Disable choose file type when start recording
                depthCheckBox.IsEnabled = false;
                rgbCheckBox.IsEnabled   = false;

                //Disable sampling frequency and file name when recording
                Sub.IsEnabled             = false;
                ChangeDirectory.IsEnabled = false;


                //Toggle recording
                IsRecording = !IsRecording;

                //Change button text
                Record.Content = IsRecording ? "Stop" : "Record";
            }
            else
            {
                //Close writer and enable file type boxes
                if (timeWriter != null)
                {
                    timeWriter.Close();
                }
                if (gzWriter != null)
                {
                    gzWriter.Close();
                }
                if (colorWriter != null)
                {
                    colorWriter.Close();
                }
                timeWriter  = null;
                gzWriter    = null;
                colorWriter = null;

                depthCheckBox.IsEnabled = true;
                rgbCheckBox.IsEnabled   = true;

                //Re-enable sampling frequency and file name boxes
                Sub.IsEnabled             = true;
                ChangeDirectory.IsEnabled = true;


                //Toggle recording
                IsRecording = !IsRecording;

                //Change button text
                Record.Content = IsRecording ? "Stop" : "Record";
            }
        }
示例#49
0
        private void Record()
        {
            _stopWrite = false;
            MainForm.RecordingThreads++;
            string previewImage = "";
            DateTime recordingStart = DateTime.MinValue;

            if (!String.IsNullOrEmpty(Camobject.recorder.trigger) && TopLevelControl != null)
            {
                string[] tid = Camobject.recorder.trigger.Split(',');
                switch (tid[0])
                {
                    case "1":
                        VolumeLevel vl = ((MainForm)TopLevelControl).GetVolumeLevel(Convert.ToInt32(tid[1]));
                        if (vl != null)
                            vl.RecordSwitch(true);
                        break;
                    case "2":
                        CameraWindow cw = ((MainForm)TopLevelControl).GetCameraWindow(Convert.ToInt32(tid[1]));
                        if (cw != null)
                            cw.RecordSwitch(true);
                        break;
                }
            }

            try {
                if (_writerBuffer != null)
                    _writerBuffer.Clear();
                _writerBuffer = new QueueWithEvents<FrameAction>();
                _writerBuffer.Changed += WriterBufferChanged;
                DateTime date = DateTime.Now;

                string filename = String.Format("{0}-{1}-{2}_{3}-{4}-{5}",
                                                date.Year, Helper.ZeroPad(date.Month), Helper.ZeroPad(date.Day),
                                                Helper.ZeroPad(date.Hour), Helper.ZeroPad(date.Minute),
                                                Helper.ZeroPad(date.Second));

                var vc = VolumeControl;
                if (vc != null && vc.Micobject.settings.active)
                {
                    vc.ForcedRecording = ForcedRecording;
                    vc.StartSaving();
                }

                VideoFileName = Camobject.id + "_" + filename;
                string folder = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\";
                string avifilename = folder + VideoFileName + CodecExtension;
                bool error = false;
                double maxAlarm = 0;

                try
                {

                    int w, h;
                    GetVideoSize(out w, out h);
                    Program.WriterMutex.WaitOne();

                    try
                    {
                        Writer = new VideoFileWriter();
                        if (vc == null || vc.AudioSource==null)
                            Writer.Open(avifilename, w, h, Camobject.recorder.crf, Codec,
                                        CalcBitRate(Camobject.recorder.quality), CodecFramerate);
                        else
                        {

                            Writer.Open(avifilename, w, h, Camobject.recorder.crf, Codec,
                                        CalcBitRate(Camobject.recorder.quality), CodecAudio, CodecFramerate,
                                        vc.AudioSource.RecordingFormat.BitsPerSample * vc.AudioSource.RecordingFormat.SampleRate * vc.AudioSource.RecordingFormat.Channels,
                                        vc.AudioSource.RecordingFormat.SampleRate, vc.AudioSource.RecordingFormat.Channels);
                        }
                    }
                    catch
                    {
                        ForcedRecording = false;
                        if (vc != null)
                        {
                            vc.ForcedRecording = false;
                            vc.StopSaving();
                        }
                        throw;
                    }
                    finally
                    {
                        Program.WriterMutex.ReleaseMutex();
                    }

                    FrameAction? peakFrame = null;

                    foreach(FrameAction fa in _videoBuffer.OrderBy(p=>p.Timestamp))
                    {
                        try
                        {
                            using (var ms = new MemoryStream(fa.Frame))
                            {
                                using (var bmp = (Bitmap)Image.FromStream(ms))
                                {
                                    if (recordingStart == DateTime.MinValue)
                                    {
                                        recordingStart = fa.Timestamp;
                                    }
                                    Writer.WriteVideoFrame(ResizeBitmap(bmp), fa.Timestamp - recordingStart);
                                }

                                if (fa.MotionLevel > maxAlarm || peakFrame == null)
                                {
                                    maxAlarm = fa.MotionLevel;
                                    peakFrame = fa;
                                }
                                _motionData.Append(String.Format(CultureInfo.InvariantCulture,
                                                                "{0:0.000}", Math.Min(fa.MotionLevel*1000, 100)));
                                _motionData.Append(",");
                                ms.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
                        }

                    }
                    _videoBuffer.Clear();

                    if (vc != null && vc.AudioBuffer != null)
                    {
                        foreach (VolumeLevel.AudioAction aa in vc.AudioBuffer.OrderBy(p=>p.TimeStamp))
                        {
                            unsafe
                            {
                                fixed (byte* p = aa.Decoded)
                                {
                                    if ((aa.TimeStamp - recordingStart).TotalMilliseconds>=0)
                                        Writer.WriteAudio(p, aa.Decoded.Length);
                                }
                            }
                        }
                        vc.AudioBuffer.Clear();
                    }

                    if (recordingStart == DateTime.MinValue)
                        recordingStart = DateTime.Now;

                    while (!_stopWrite)
                    {
                        while (_writerBuffer.Count > 0)
                        {
                            var fa = _writerBuffer.Dequeue();
                            try
                            {
                                using (var ms = new MemoryStream(fa.Frame))
                                {

                                    var bmp = (Bitmap) Image.FromStream(ms);
                                    Writer.WriteVideoFrame(ResizeBitmap(bmp), fa.Timestamp - recordingStart);
                                    bmp.Dispose();
                                    bmp = null;

                                    if (fa.MotionLevel > maxAlarm || peakFrame == null)
                                    {
                                        maxAlarm = fa.MotionLevel;
                                        peakFrame = fa;
                                    }
                                    _motionData.Append(String.Format(CultureInfo.InvariantCulture,
                                                                    "{0:0.000}",
                                                                    Math.Min(fa.MotionLevel*1000, 100)));
                                    _motionData.Append(",");
                                    ms.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
                            }
                            if (vc != null && vc.WriterBuffer != null)
                            {
                                try
                                {
                                    while (vc.WriterBuffer.Count > 0)
                                    {

                                        var b = vc.WriterBuffer.Dequeue();
                                        unsafe
                                        {
                                            fixed (byte* p = b.Decoded)
                                            {
                                                Writer.WriteAudio(p, b.Decoded.Length);
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                    //can fail if the control is switched off/removed whilst recording

                                }
                            }

                        }
                        _newRecordingFrame.WaitOne(200);
                    }

                    if (!Directory.Exists(folder + @"thumbs\"))
                        Directory.CreateDirectory(folder + @"thumbs\");

                    if (peakFrame != null)
                    {
                        using (var ms = new MemoryStream(peakFrame.Value.Frame))
                        {
                            using (var bmp = (Bitmap)Image.FromStream(ms))
                            {
                                bmp.Save(folder + @"thumbs\" + VideoFileName + "_large.jpg", MainForm.Encoder,
                                         MainForm.EncoderParams);
                                Image.GetThumbnailImageAbort myCallback = ThumbnailCallback;
                                using (var myThumbnail = bmp.GetThumbnailImage(96, 72, myCallback, IntPtr.Zero))
                                {
                                    myThumbnail.Save(folder + @"thumbs\" + VideoFileName + ".jpg", MainForm.Encoder,
                                                     MainForm.EncoderParams);
                                }
                            }
                            previewImage = folder + @"thumbs\" + VideoFileName + ".jpg";
                            ms.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    error = true;
                    Log.Error("Camera " + Camobject.id, ex);
                }
                finally
                {
                    _stopWrite = false;
                    if (Writer != null)
                    {
                        Program.WriterMutex.WaitOne();
                        try
                        {

                            Writer.Close();
                            Writer.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
                        }
                        finally
                        {
                            Program.WriterMutex.ReleaseMutex();
                        }

                        Writer = null;
                    }

                    try
                    {
                        _writerBuffer.Clear();
                    }
                    catch
                    {
                    }

                    _writerBuffer = null;
                    _recordingTime = 0;
                    if (vc != null && vc.Micobject.settings.active)
                        VolumeControl.StopSaving();
                }
                if (error)
                {
                    try
                    {
                        FileOperations.Delete(filename + CodecExtension);
                    }
                    catch
                    {
                    }
                    MainForm.RecordingThreads--;
                    return;
                }

                string path = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\" +
                              VideoFileName;

                bool yt = Camobject.settings.youtube.autoupload && MainForm.Conf.Subscribed;

                string[] fnpath = (path + CodecExtension).Split('\\');
                string fn = fnpath[fnpath.Length - 1];
                var fpath = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\thumbs\\";
                var fi = new FileInfo(path + CodecExtension);
                var dSeconds = Convert.ToInt32((DateTime.Now - recordingStart).TotalSeconds);

                FilesFile ff = FileList.FirstOrDefault(p => p.Filename.EndsWith(fn));
                bool newfile = false;
                if (ff == null)
                {
                    ff = new FilesFile();
                    newfile = true;
                }

                ff.CreatedDateTicks = DateTime.Now.Ticks;
                ff.Filename = fn;
                ff.MaxAlarm = Math.Min(maxAlarm * 1000, 100);
                ff.SizeBytes = fi.Length;
                ff.DurationSeconds = dSeconds;
                ff.IsTimelapse = false;
                ff.AlertData = Helper.GetMotionDataPoints(_motionData);
                _motionData.Clear();
                ff.TriggerLevel = (100-Camobject.detector.minsensitivity); //adjusted

                if (newfile)
                {
                    FileList.Insert(0, ff);

                    if (!MainForm.MasterFileList.Any(p => p.Filename.EndsWith(fn)))
                    {
                        MainForm.MasterFileList.Add(new FilePreview(fn, dSeconds, Camobject.name, DateTime.Now.Ticks, 2,
                                                                    Camobject.id, ff.MaxAlarm));
                        if (TopLevelControl != null)
                        {
                            string thumb = fpath + fn.Replace(CodecExtension, ".jpg");

                            ((MainForm)TopLevelControl).AddPreviewControl(thumb, path + CodecExtension, dSeconds,
                                                                           DateTime.Now, true);
                        }
                    }

                    if (yt)
                    {
                        if (CodecExtension!=".mp4")
                            Log.Info("Skipped youtube upload (only upload mp4 files).");
                        else
                        {
                            try
                            {
                                YouTubeUploader.AddUpload(Camobject.id, fn, Camobject.settings.youtube.@public, "", "");
                            }
                            catch (Exception ex)
                            {
                                Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
            }
            MainForm.RecordingThreads--;
            Camobject.newrecordingcount++;

            if (!String.IsNullOrEmpty(Camobject.recorder.trigger) && TopLevelControl != null)
            {
                string[] tid = Camobject.recorder.trigger.Split(',');
                switch (tid[0])
                {
                    case "1":
                        VolumeLevel vl = ((MainForm)TopLevelControl).GetVolumeLevel(Convert.ToInt32(tid[1]));
                        if (vl != null)
                            vl.RecordSwitch(false);
                        break;
                    case "2":
                        CameraWindow cw = ((MainForm)TopLevelControl).GetCameraWindow(Convert.ToInt32(tid[1]));
                        if (cw != null)
                            cw.RecordSwitch(false);
                        break;
                }
            }

            if (Notification != null)
                Notification(this, new NotificationType("NewRecording", Camobject.name, previewImage));
        }
示例#50
0
        private void CreateVideo()
        {
            // Start a new video file
            VideoFileWriter vfw = new VideoFileWriter();
            vfw.Open("Test.avi", mat.Width, mat.Height, 30, VideoCodec.Default);

            // create an image that we are going to use for the buffering of the next frame
            Bitmap bitmap = new Bitmap(mat.Width, mat.Height);
            FxMaths.Images.FxImages nextFrameImage = FxMaths.Images.FxTools.FxImages_safe_constructors(bitmap);

            // Start the simulation
            simulation.Start();

            var imTarget = imPerson * 0.1f + 0.5f;

            for (int i = 0; i < 2000; i++)
            {
                // Set to zero value
                mat.DrawMatrix(shopPlan, new FxVector2f(0, 0), new FxVector2f(mat.Width, mat.Height), FxMatrixF.DrawInterpolationMethod.Linear);
                //mat.SetValue(1); // white

                // Draw the target points
                if(true)
                    foreach(var t in targetList)
                    {
                        var size = new FxVector2f(20 * resize.x, 20 * resize.y);
                        var center = size / 2;

                        // Draw a circle per person
                        mat.DrawMatrix(imTarget,
                            imPersonMask,
                            t - center,
                            size,
                            FxMatrixF.DrawInterpolationMethod.Linear);

                    }

                lock (shop)
                {
                    var size = new FxVector2f(50 * resize.x, 50 * resize.y);
                    var center = size / 2;
                    // move the blobs in random directions
                    foreach (var person in shop.personList)
                    {
                        // Draw a circle per person
                        mat.DrawMatrix(imPerson,
                            imPersonMask,
                            person.Position - center,
                            size,
                            FxMatrixF.DrawInterpolationMethod.Linear);
                    }
                }

                // Update the bitmap that we write to image
                nextFrameImage.Load(mat, new FxMaths.Images.ColorMap(FxMaths.Images.ColorMapDefaults.Gray));
                vfw.WriteVideoFrame(bitmap);

                // Update showing image
                im.UpdateInternalImage(mat, new FxMaths.Images.ColorMap(FxMaths.Images.ColorMapDefaults.Gray));
                canvas1.ReDraw();

                if (i % 10 == 0)
                    Console.WriteLine("Write Frame:" + i.ToString());
            }

            // Stop the simulation
            simulation.Stop();
            vfw.Close();
        }
示例#51
-1
        /// <summary>
        /// Method for rendering  and saving the video to a new file. All settings are set in the ProjectSettings class.
        /// </summary>
        // TODO add sound, use constructor with parameters in a factory patern
        public static void RenderVideo()
        {
            ProjectSettings settings = ProjectSettings.GetSettings();

            // TODO moove to Widget
            if (string.IsNullOrEmpty(settings.GPXPath))
            {
                throw new ArgumentNullException("No track file was selected!");
            }

            new GPXFileLoader().LoadPoints(settings.GPXPath);

            List<Widget> activeWidgets = UpdateActiveWidgets();

            VideoFileWriter writer = new VideoFileWriter();

            // open video file
            reader.Open(settings.VideoInputPath);
            VideoDimensions = new Size(reader.Width, reader.Height);
            float framerate = reader.FrameRate;

            // create new AVI file and open it
            var encoding = (VideoCodec)Enum.Parse(typeof(VideoCodec), settings.Format.ToString());

            if (string.IsNullOrEmpty(settings.VideoOutputPath))
            {
                throw new ArgumentNullException("No output video file was specified!");
            }

            writer.Open(settings.VideoOutputPath, reader.Width, reader.Height, reader.FrameRate, encoding, settings.VideoQuality * 1000000);

            videoEnd = (int)(settings.VideoEnd * reader.FrameRate);
            videoStart = (int)(settings.VideoStart * reader.FrameRate);
            if (videoEnd == 0 || videoEnd > reader.FrameCount)
            {
                videoEnd = reader.FrameCount;
            }

            int speed = settings.VideoSpeed;
            for (long currentFrameNumber = 0; currentFrameNumber < videoEnd - speed; currentFrameNumber++)
            {
                Bitmap videoFrame = GetFrame(reader, speed, ref currentFrameNumber);

                RenderFrame(currentFrameNumber / framerate, videoFrame, activeWidgets);

                writer.WriteVideoFrame(videoFrame);
                videoFrame.Dispose();
                ////string progress = string.Format("{0} {1}", (int)(100 * n / videoEnd), '%');
            }

            reader.Close();
            writer.Close();
        }