예제 #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 void StartRecording(String filenameToSave)
 {
     videoWriter = new VideoFileWriter();
     videoWriter.Open(filenameToSave, screenSize.Width, screenSize.Height, 25, VideoCodec.MPEG2);
     frameTimer.Start();
     isRecording = true;
     StartEyeStream();
 }
예제 #6
0
 public WriteVideoFile(string filePath, string codec, int frameRate, int width, int height)
 {
     VideoFile = new VideoFileWriter();
     VideoFile.Open(filePath, width, height, frameRate, VideoCodec.MPEG4);
     Codec = VideoCodec.MPEG4;
     FrameRate = frameRate;
     Width = width;
     Height = height;
 }
예제 #7
0
 public RecordSkeleton()
 {
     videoFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Video");
     if (!Directory.Exists(videoFolder))
     {
         Directory.CreateDirectory(videoFolder);
     }
     Count++;
     writer1 = new VideoFileWriter();
     writer1.Open(System.IO.Path.Combine(videoFolder, Count.ToString() + "_color.avi"), videoWidthColor, videoHeightColor, 25, VideoCodec.MPEG4);
 }
예제 #8
0
 private static void WriteFranes(IEnumerable<string> grouping, string path, VideoFileWriter videoFileWriter, int frameRate)
 {
     int index = 0;
     var images = grouping.Select(s => Path.Combine(path, s + ImgExtentsion)).ToArray();
     foreach (var image in images){
         index++;
         using (var bitmap = new Bitmap(image)){
             var timeSpan = TimeSpan.FromSeconds((double)index/frameRate);
             videoFileWriter.WriteVideoFrame(bitmap, timeSpan);
         }
     }
     Console.WriteLine("Found " + images.Count() + " images");
 }
예제 #9
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;
            }

        }
예제 #10
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();
        }
예제 #11
0
        public MiniScreenRecorder()
        {
            InitializeComponent();

            this.screenWidth = SystemInformation.VirtualScreen.Width;
            this.screenHight = SystemInformation.VirtualScreen.Height;
            this.frameRate = DEFAULT_FRAME_RATE;
            this.isRecording = false;
            this.framesCount = default(int);
            this.SaveFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            this.pathTextBox.Text = this.SaveFolderPath;
            this.stopWatch = new Stopwatch();
            this.screenArea = Rectangle.Empty;
            this.videoWriter = new VideoFileWriter();
            this.folderBrowser = new FolderBrowserDialog();

            InitializeDropDownMenus();
        }
예제 #12
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();
 }
예제 #13
0
 public YAMDDetector(IVideoSource source, Magnitude low, Magnitude medium, Magnitude high)
 {
     detector = new MotionDetector(
         new SimpleBackgroundModelingDetector(),
         new BlobCountingObjectsProcessing(true));
     //async video source processes images in a separate thread and uses the NewFrame event
     inputStream = new AsyncVideoSource(source);
     inputStream.NewFrame += inputStream_NewFrame;
     this.low = low;
     this.medium = medium;
     this.high = high;
     timer = new Stopwatch();
     stoptimer = new Stopwatch();
     videoRecorder = new VideoFileWriter();
     Running = false;
     buffer = new FixedSizeQueue<Bitmap>();
     buffer.Limit = 50;
     magnitudes = new Queue<int>();
 }
예제 #14
0
        public VideoRecorder(Queue<Bitmap> frameBuffer, Size resolution)
        {
            this.frameBuffer = frameBuffer;
            this.writer = new VideoFileWriter();

            string filepath = Environment.CurrentDirectory + "\\videos\\";

            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(Path.GetDirectoryName(filepath));

            string name = Guid.NewGuid().ToString() + ".avi";
            string filename = Path.Combine(filepath, name);
            try
            {
                if (!writer.IsOpen)
                    writer.Open(filename, resolution.Width, resolution.Height, 24, VideoCodec.MPEG2, 10000000);
            }
            catch (AccessViolationException)
            {

            }
        }
예제 #15
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();
         }
     }
 }
예제 #16
0
        static void Main()
        {
            Console.Write("Path to folder with frames: ");
            string          path = Console.ReadLine();
            VideoFileWriter vw   = new VideoFileWriter();

            Console.Write("Output File Name(with avi for example file.avi): ");
            string filename = Console.ReadLine();

            Console.Write("Enter FrameRate: ");
            int framerate = Int32.Parse(Console.ReadLine());

            Console.Write("Enter Width: ");
            int Width = Int32.Parse(Console.ReadLine());

            Console.Write("Enter Height: ");
            int Height = Int32.Parse(Console.ReadLine());

            Console.Write("Path to folder with output frames: ");
            string pathout = Console.ReadLine();

            Console.Write("black background or White(b/w): ");
            string back = Console.ReadLine();

            if (!Directory.Exists(pathout))
            {
                Directory.CreateDirectory(pathout);
            }
            Bitmap frame = new Bitmap($@"{path}\0.jpg");

            if (frame.Width < Width && frame.Height < Height || frame.Width < Width || frame.Height < Height)
            {
                Width  = frame.Width;
                Height = frame.Height;
            }
            vw.Open(filename, Width, Height, framerate);

            if (back.StartsWith("B") || back.StartsWith("b"))
            {
                for (int i = 0; i < Directory.GetFiles(path).Length; i++)
                {
                    Console.WriteLine("\t\t" + Directory.GetFiles(path).Length);
                    Bitmap image = new Bitmap($@"{path}\{i}.jpg");
                    EdgeDetection(image, 10);
                    Bitmap pixels = new Bitmap(image);
                    pixels = ImageBmpBlack(pixels);
                    pixels.Save($@"{pathout}\{i}.jpg");
                    vw.WriteVideoFrame(pixels);
                }
            }
            if (back.StartsWith("W") || back.StartsWith("w"))
            {
                for (int i = 0; i < Directory.GetFiles(path).Length; i++)
                {
                    Console.WriteLine("\t\t" + Directory.GetFiles(path).Length);
                    Bitmap image = new Bitmap($@"{path}\{i}.jpg");
                    EdgeDetection(image, 10);
                    Bitmap pixels = new Bitmap(image);
                    pixels = ImageBmpWhite(pixels);
                    pixels.Save($@"{pathout}\{i}.jpg");
                    vw.WriteVideoFrame(pixels);
                }
            }
            if (!back.StartsWith("B") || !back.StartsWith("b") || !back.StartsWith("W") || !back.StartsWith("w"))
            {
                Console.WriteLine("Incorect try again...");
                Console.Read();
                Main();
            }
            vw.Close();
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
예제 #17
0
 public ImageDrawer(VideoFileWriter writer, byte[] fileBytes, IProgress <int> progress = null)
 {
     _writer    = writer;
     _fileBytes = fileBytes;
     _progress  = progress;
 }
예제 #18
0
파일: AppForm.cs 프로젝트: Plugway/UVEA
        public AppForm()
        {
            //
            //Main window settings
            //
            Size            = new Size(800, 450);
            FormBorderStyle = FormBorderStyle.FixedDialog;
            Text            = "UVEC"; //???
            Icon            = new Icon(@"mmfiles\icon.ico");

            //
            //Top subspace of main window
            //
            ChosenFile.Enabled  = false;
            ChosenFile.Location = new Point(10, 10);
            ChosenFile.Size     = new Size(ClientSize.Width - 5 - 30 - 20,// 10*2 - отступ справа и слева
                                           Size.Height);
            ChosenFile.TextAlign = HorizontalAlignment.Center;
            ChosenFile.Text      = "Choose file ->";
            ChosenFile.ReadOnly  = true;

            OpenFile.Title            = "Open file";
            OpenFile.Filter           = "Video Files|*.mp4;*.avi";
            OpenFile.RestoreDirectory = true;

            OpenFileButton.Size     = new Size(30, ChosenFile.Size.Height + 2);
            OpenFileButton.Text     = "...";
            OpenFileButton.Location = new Point(ChosenFile.Right + 5, ChosenFile.Top - 1);

            Controls.Add(ChosenFile);
            Controls.Add(OpenFileButton);

            //
            //Left middle subspace
            //
            PreviewPictureBox.Location = new Point(10, ChosenFile.Bottom + 10);
            PreviewPictureBox.Size     =
                new Size(
                    (ClientRectangle.Height - ChosenFile.Bottom + 10 - 100) / 9 * 16, // /9 & *16 - соотношение сторон 16 на 9
                    ClientRectangle.Height - ChosenFile.Bottom + 10 - 100);           // 50 - отступ снизу
            PreviewPictureBox.Image = new Bitmap(PreviewPictureBox.Width, PreviewPictureBox.Height);
            using (Graphics g = Graphics.FromImage(PreviewPictureBox.Image)){ g.Clear(Color.Black); } //заливка черным

            PreviewLabel.Text      = "Preview";
            PreviewLabel.ForeColor = Color.White;
            PreviewLabel.BackColor = Color.Transparent;

            Controls.Add(PreviewPictureBox);
            PreviewPictureBox.Controls.Add(PreviewLabel);

            //
            //Left bottom subspace
            //
            TimeLineLabel.Text      = "Time Line";
            TimeLineLabel.BackColor = Color.Transparent;
            TimeLineLabel.TextAlign = ContentAlignment.TopCenter;
            TimeLineLabel.Location  = new Point(10, PreviewPictureBox.Bottom + 10);
            TimeLineLabel.Size      = new Size(PreviewPictureBox.Width, ClientSize.Height - PreviewPictureBox.Bottom - 10 - 10);

            TimeLineStart.Location  = new Point(0, 0);
            TimeLineStart.BackColor = Color.Transparent;
            TimeLineStart.Text      = "00.00";

            TimeLineEnd.Location  = new Point(TimeLineLabel.Width - 100, 0); //100 - отступ справа
            TimeLineEnd.BackColor = Color.Transparent;
            TimeLineEnd.Text      = "00.00";
            TimeLineEnd.TextAlign = ContentAlignment.TopRight;

            TimeLine.TickStyle     = TickStyle.Both;
            TimeLine.TickFrequency = 5;
            TimeLine.Maximum       = 100;
            TimeLine.Minimum       = 0;
            TimeLine.Location      = new Point(0, 20);
            TimeLine.Width         = TimeLineLabel.Width;
            TimeLine.Enabled       = false;

            Controls.Add(TimeLineLabel);
            TimeLineLabel.Controls.Add(TimeLine);
            TimeLineLabel.Controls.Add(TimeLineStart);
            TimeLineLabel.Controls.Add(TimeLineEnd);

            //
            //Progress second layout
            //
            ProgressLabel.Text      = "Progress";
            ProgressLabel.BackColor = Color.Transparent;
            ProgressLabel.TextAlign = ContentAlignment.TopLeft;
            ProgressLabel.Location  = new Point(10, PreviewPictureBox.Bottom + 10);
            ProgressLabel.Size      = new Size(PreviewPictureBox.Width, ClientSize.Height - PreviewPictureBox.Bottom - 10 - 5);

            ProgressVisualBar.Location = new Point(0, 25);
            ProgressVisualBar.Width    = ProgressLabel.Width;
            ProgressVisualBar.Maximum  = 1000;
            ProgressVisualBar.Minimum  = 0;

            ProgressTimeRemaining.Location  = new Point(ProgressVisualBar.Right - 150, ProgressVisualBar.Top - 15);
            ProgressTimeRemaining.BackColor = Color.Transparent;
            ProgressTimeRemaining.Size      = new Size(150, 15);
            ProgressTimeRemaining.Text      = "Time remaining: 00:00:00.00";

            ProgressTimeElapsed.Location  = new Point(ProgressTimeRemaining.Left - 10 - 150, ProgressTimeRemaining.Top);
            ProgressTimeElapsed.BackColor = Color.Transparent;
            ProgressTimeElapsed.Size      = ProgressTimeRemaining.Size;
            ProgressTimeElapsed.Text      = "Time elapsed: 00:00:00.00";

            ProgressPercent.Location  = new Point(ProgressVisualBar.Right - 145, ProgressVisualBar.Bottom);
            ProgressPercent.BackColor = Color.Transparent;
            ProgressPercent.Text      = "Percent completed: 0%";
            ProgressPercent.Size      = new Size(145, 15);

            ProgressLabel.Controls.Add(ProgressVisualBar);
            ProgressLabel.Controls.Add(ProgressTimeElapsed);
            ProgressLabel.Controls.Add(ProgressTimeRemaining);
            ProgressLabel.Controls.Add(ProgressPercent);

            //
            //Right subspace
            //
            EffectsPanelLabel.Location = new Point(PreviewPictureBox.Right + 10, PreviewPictureBox.Top);
            EffectsPanelLabel.Size     = new Size(ClientSize.Width - PreviewPictureBox.Right - 10 - 10,
                                                  ClientSize.Height - PreviewPictureBox.Top - 10 - 10);//10 - отступы
            EffectsPanelLabel.BackColor = Color.Transparent;
            EffectsPanelLabel.TextAlign = ContentAlignment.TopCenter;
            EffectsPanelLabel.Text      = "Effects Control";

            EpEffectClassChoose.Location   = new Point(10, 20);
            EpEffectClassChoose.Width      = (EffectsPanelLabel.Width - 30) / 2;
            EpEffectClassChoose.DataSource = Enum.GetValues(typeof(EffectClass));

            //
            //One frame settings
            EpOneFrameFuncChoose.Location   = new Point(EpEffectClassChoose.Right + 10, 20);
            EpOneFrameFuncChoose.Width      = EpEffectClassChoose.Width;
            EpOneFrameFuncChoose.DataSource = Enum.GetValues(typeof(Functions));

            MultiplierFromLabel.Location  = new Point(EpEffectClassChoose.Left, EpEffectClassChoose.Bottom + 10);
            MultiplierFromLabel.Size      = new Size(EffectsPanelLabel.Width - 20, 20);
            MultiplierFromLabel.Text      = "Multiplier from:";
            MultiplierFromLabel.TextAlign = ContentAlignment.MiddleLeft;

            MultiplierFromTextBox.Location  = new Point(EpEffectClassChoose.Width - 20, 0);
            MultiplierFromTextBox.Width     = EpEffectClassChoose.Width + 30;
            MultiplierFromTextBox.Text      = "0.0";
            MultiplierFromTextBox.BackColor = Color.White;

            MultiplierToLabel.Location  = new Point(EpEffectClassChoose.Left, MultiplierFromLabel.Bottom + 10);
            MultiplierToLabel.Size      = new Size(EffectsPanelLabel.Width - 20, 20);
            MultiplierToLabel.Text      = "Multiplier to:";
            MultiplierToLabel.TextAlign = ContentAlignment.MiddleLeft;

            MultiplierToTextBox.Location  = new Point(EpEffectClassChoose.Width - 20, 0);
            MultiplierToTextBox.Width     = EpEffectClassChoose.Width + 30;
            MultiplierToTextBox.Text      = "0.0";
            MultiplierToTextBox.BackColor = Color.White;

            //
            //Multi frame settings
            EpMultiFrameFuncChoose.Location   = new Point(EpEffectClassChoose.Right + 10, 20);
            EpMultiFrameFuncChoose.Width      = EpEffectClassChoose.Width;
            EpMultiFrameFuncChoose.DataSource = Enum.GetValues(typeof(MultiFrameFunctions));

            //
            //Start
            StartButton.Location = new Point(EffectsPanelLabel.Width - 70, EffectsPanelLabel.Height - 30);
            StartButton.Size     = new Size(60, 30);
            StartButton.Text     = "Start";
            StartButton.Enabled  = false;

            _renderWorker.WorkerReportsProgress = true;

            ShowRenderedCheckBox.Location = new Point(10, EffectsPanelLabel.Height - 27);
            ShowRenderedCheckBox.Text     = "Show rendered(slower)";
            ShowRenderedCheckBox.Checked  = ShowRendered;
            ShowRenderedCheckBox.Width    = 140;

            Controls.Add(EffectsPanelLabel);
            EffectsPanelLabel.Controls.Add(EpEffectClassChoose);
            EffectsPanelLabel.Controls.Add(EpOneFrameFuncChoose);
            EffectsPanelLabel.Controls.Add(MultiplierFromLabel);
            MultiplierFromLabel.Controls.Add(MultiplierFromTextBox);
            EffectsPanelLabel.Controls.Add(MultiplierToLabel);
            MultiplierToLabel.Controls.Add(MultiplierToTextBox);
            EffectsPanelLabel.Controls.Add(StartButton);
            EffectsPanelLabel.Controls.Add(ShowRenderedCheckBox);
            //effectsPanelLabel.Controls.Add(epMultiFrameFuncChoose);

            //
            //Handlers
            //
            //Top
            //
            OpenFileButton.Click += (sender, args) => { OpenFileButtonHandler(); };

            //
            //Left bottom subspace
            //
            TimeLine.ValueChanged += (sender, args) => { TimeLineHandler(); };

            //
            //Right subspace
            //
            EpEffectClassChoose.SelectionChangeCommitted += (sender, args) => { EpEffectClassChooseHandler(); };

            //
            //One frame settings
            EpOneFrameFuncChoose.SelectionChangeCommitted += (sender, args) =>
            {
                Function = (Functions)EpOneFrameFuncChoose.SelectedItem;
                Distorter.ResetMaxMinValues();
                if (StartButton.Enabled)
                {
                    DrawImage(PreviewPictureBox, Distorter.RunOneFrame(Reader, TimeLine.Value,
                                                                       MultiplierFrom, MultiplierTo, Function, PreviewPictureBox.Width, PreviewPictureBox.Height));
                }
            };
            MultiplierFromTextBox.TextChanged += (sender, args) => { MultiplierTextBoxHandler(MultiplierFromTextBox, ref MultiplierFrom); };
            MultiplierToTextBox.TextChanged   += (sender, args) => { MultiplierTextBoxHandler(MultiplierToTextBox, ref MultiplierTo); };

            //
            //Multi frame settings
            EpMultiFrameFuncChoose.SelectionChangeCommitted += (sender, args) =>
            {
                MFFunction = (MultiFrameFunctions)EpMultiFrameFuncChoose.SelectedItem;
            };

            //
            //Start
            ShowRenderedCheckBox.CheckedChanged += (sender, args) => { ShowRendered = ShowRenderedCheckBox.Checked; };
            _renderWorker.DoWork += (sender, args) =>
            {
                if (EffectClass == EffectClass.SingleFrame)
                {
                    OneFrameDistorter.Run(Reader, Writer, MultiplierFrom, MultiplierTo, Function, _renderWorker);
                }
                else if (EffectClass == EffectClass.MultiFrame)
                {
                    MultiFrameDistorter.Run(Reader, Writer, MFFunction, _renderWorker);
                }
            };
            _renderWorker.ProgressChanged += (sender, args) =>
            {
                if (ShowRendered)
                {
                    DrawImage(PreviewPictureBox, PreviewBitmap);
                }
                ProgressVisualBar.Value         = args.ProgressPercentage;
                ProgressPercent.Text            = $"Percent completed: {args.ProgressPercentage/10.0}%";
                var(timeRemaining, timeElapsed) = _progressTimer.GetTimeElapsed(args.ProgressPercentage);
                ProgressTimeRemaining.Text      = $"Time remaining: {timeRemaining:hh\\:mm\\:ss\\.ff}";
                ProgressTimeElapsed.Text        = $"Time elapsed: {timeElapsed:hh\\:mm\\:ss\\.ff}";
            };
            _renderWorker.RunWorkerCompleted += (sender, args) =>
            {
                Writer.Close();
                Writer.Dispose();
                Writer            = new VideoFileWriter();
                Writer.BitRate    = Reader.BitRate;   //конфигурируем writer
                Writer.VideoCodec = VideoCodec.Mpeg4; //Reader videoCodec
                Writer.FrameRate  = Reader.FrameRate;
                Writer.Height     = Reader.Height;
                Writer.Width      = Reader.Width;
                Writer.Open(GetNameToSave(VideoPath, VideoName, VideoExtension));
                OpenFileButton.Enabled         = true;
                EpEffectClassChoose.Enabled    = true;
                EpMultiFrameFuncChoose.Enabled = true;
                EpOneFrameFuncChoose.Enabled   = true;
                MultiplierFromTextBox.Enabled  = true;
                MultiplierToTextBox.Enabled    = true;
                ShowRenderedCheckBox.Enabled   = true;
                StartButton.Enabled            = true;
                _progressTimer.ResetAverageTime();
                ProgressVisualBar.Value    = 0;
                ProgressTimeRemaining.Text = "Time remaining: 00:00:00.00";
                ProgressTimeElapsed.Text   = "Time elapsed: 00:00:00.00";
                ProgressPercent.Text       = "Percent completed: 0%";
                Controls.Remove(ProgressLabel);
                Controls.Add(TimeLineLabel);
            };
            StartButton.Click += (sender, args) =>
            {
                OpenFileButton.Enabled         = false;
                EpEffectClassChoose.Enabled    = false;
                EpMultiFrameFuncChoose.Enabled = false;
                EpOneFrameFuncChoose.Enabled   = false;
                MultiplierFromTextBox.Enabled  = false;
                MultiplierToTextBox.Enabled    = false;
                ShowRenderedCheckBox.Enabled   = false;
                StartButton.Enabled            = false;
                Controls.Remove(TimeLineLabel);
                Controls.Add(ProgressLabel);
                _renderWorker.RunWorkerAsync();
            };
        }
예제 #19
0
        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            //Graphics gr = Graphics.FromImage(image);

            //SolidBrush drawBrush = new SolidBrush(Color.Red);

            //Font drawFont = new Font("Arial", 4, System.Drawing.FontStyle.Bold, GraphicsUnit.Millimeter);

            //int xPos = 5;

            //int yPos = 3;

            //string date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//得到写到屏上的时间
            //gr.DrawString(date, drawFont, drawBrush, xPos, yPos);

            //if (stopREC)
            //{
            //    stopREC = true;
            //    createNewFile = true;

            //    if (videoWriter != null)
            //    {
            //        videoWriter.Close();
            //    }
            //}
            //else
            //{
            //    if (createNewFile)
            //    {

            //        createNewFile = false;
            //        if (videoWriter != null)
            //        {
            //            videoWriter.Close();
            //            videoWriter.Dispose();
            //        }
            //        videoWriter = new VideoFileWriter();
            //        videoWriter.Open(DateTime.Now.ToString("yyMMddHH")+".avi", 320, 240, 20, VideoCodec.MPEG4);

            //        // add the image as a new frame of video file
            //        videoWriter.WriteVideoFrame(image);
            //        videoWriter.Dispose();
            //    }
            //    else
            //    {
            //        videoWriter.WriteVideoFrame(image);
            //    }
            //}
            //录像
            Graphics   g         = Graphics.FromImage(image);
            SolidBrush drawBrush = new SolidBrush(Color.Yellow);

            Font drawFont = new Font("Arial", 6, System.Drawing.FontStyle.Bold, GraphicsUnit.Millimeter);
            int  xPos     = image.Width - (image.Width - 15);
            int  yPos     = 10;

            //写到屏幕上的时间
            drawDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            g.DrawString(drawDate, drawFont, drawBrush, xPos, yPos);
            if (!Directory.Exists(videoPath))
            {
                Directory.CreateDirectory(videoPath);
            }

            //创建文件路径
            //fileFullPath = path + fileName;

            if (stopREC)
            {
                stopREC       = true;
                createNewFile = true;  //这里要设置为true表示要创建新文件
                if (videoWriter != null)
                {
                    videoWriter.Close();
                }
            }
            else
            {
                //开始录像
                if (createNewFile)
                {
                    videoFileName     = DateTime.Now.ToString("yyyyMMddHH") + ".avi";
                    videoFileFullPath = videoPath + videoFileName;
                    createNewFile     = false;
                    if (videoWriter != null)
                    {
                        videoWriter.Close();
                        videoWriter.Dispose();
                    }
                    videoWriter = new VideoFileWriter();
                    //这里必须是全路径,否则会默认保存到程序运行根据录下了
                    videoWriter.Open(videoFileFullPath, image.Width, image.Height, frameRate, VideoCodec.MPEG4);
                    videoWriter.WriteVideoFrame(image);
                }
                else
                {
                    videoWriter.WriteVideoFrame(image);
                }
            }
        }
예제 #20
0
 private void InitVideoFile()
 {
     writer = new VideoFileWriter();
     writer.Open(fileName, format.Width, format.Height, fps, VideoCodec.MPEG4, bitRate);
 }
예제 #21
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\Abdelrahman\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\Abdelrahman\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
             * }      */
        }
예제 #22
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);
            }
        }
예제 #23
0
        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);
            }
        }
예제 #24
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;
        }
예제 #25
0
        public static bool Record(int fps, int codec)
        {
            GetWindowRect(ClientCommunication.FindUOWindow(), out RECT lpRect);
            Rectangle screenArea = new Rectangle(lpRect.Left, lpRect.Top, (lpRect.Right - lpRect.Left), (lpRect.Bottom - lpRect.Top));

            foreach (System.Windows.Forms.Screen screen in
                     System.Windows.Forms.Screen.AllScreens)
            {
                screenArea = Rectangle.Union(screenArea, screen.Bounds);
            }

            m_ResX = (lpRect.Right - lpRect.Left) - 5;
            m_ResY = (lpRect.Bottom - lpRect.Top) - 5;

            if (m_ResX % 2 != 0)
            {
                m_ResX--;
            }

            if (m_ResY % 2 != 0)
            {
                m_ResY--;
            }

            string filename;
            string name = "Unknown";
            string path = RazorEnhanced.Settings.General.ReadString("VideoPath");

            if (!Directory.Exists(path))
            {
                path = Path.GetDirectoryName(Application.ExecutablePath);
                RazorEnhanced.Settings.General.WriteString("VideoPath", path);
                Assistant.Engine.MainWindow.VideoPathTextBox.Text = path;
            }

            if (World.Player != null)
            {
                name = World.Player.Name;
            }
            if (name == null || name.Trim() == "" || name.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                name = "Unknown";
            }

            name = String.Format("{0}_{1}", name, DateTime.Now.ToString("M-d_HH.mm"));

            int count = 0;

            do
            {
                filename = Path.Combine(path, String.Format("{0}{1}.avi", name, count != 0 ? count.ToString() : ""));
                count--;                 // cause a - to be put in front of the number
            }while (File.Exists(filename));

            try
            {
                m_recording  = true;
                m_filewriter = new VideoFileWriter();
                m_filewriter.Open(filename, m_ResX, m_ResY, fps, (VideoCodec)codec, 30000000);

                // create screen capture video source
                m_videostream = new ScreenCaptureStream(screenArea, fps);
                // set NewFrame event handler
                m_videostream.NewFrame += new NewFrameEventHandler(video_NewFrame);
                // start the video source
                m_videostream.Start();
                return(true);
            }
            catch
            {
                MessageBox.Show("Video Codec not installed on your system.");
                return(false);
            }
        }
예제 #26
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
            {
                szfileNames = szfileNames + (szfileNames == "" ? "" : "|") + fileName + (rotate ? "" : "NO") + random + "ROTATE__fr_40_PART" + part + ".avi";
                String outputFileName = outDir + fileName + (rotate ? "" : "NO") + random + "ROTATE__fr_" + framRate + "_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)
                            {
                                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;
            }
        }
예제 #27
0
 public Recording()
 {
     writer = new VideoFileWriter();
 }
예제 #28
0
        public void Convert(Form1 form, string pathToTheImages, int frameRate)
        {
            // Example: 1,200 images with frameRate equal to 30 -> 1,200 / 30 => Video length will be exact 40 seconds.

            var minWidth = int.MaxValue;
            var minHeight = int.MaxValue;

            var directoryInfo = new DirectoryInfo(pathToTheImages);
            var images = directoryInfo.GetFiles("*.jpg");

            var videoFileName = $"_{images.Length}_ImagesToOneVideo__{directoryInfo.Name}.avi";

            var divisionResult = (double)images.Length / frameRate;
            form.SetP2TxtBoxInfoText($"Start to convert {images.Length} images to one video!");
            form.SetP2TxtBoxInfoText($"File name will be {videoFileName}");
            form.SetP2TxtBoxInfoText(string.Empty);
            form.SetP2TxtBoxInfoText($"Info:");
            form.SetP2TxtBoxInfoText($"\tBased on the given frame rate of {frameRate} fps and {images.Length} found images");
            form.SetP2TxtBoxInfoText($"\twill the video be have a length of around ({images.Length} / {frameRate} =) {divisionResult:N2} seconds.");
            form.SetP2TxtBoxInfoText(string.Empty);
            form.SetP2TxtBoxInfoText("Searching for the smallest image dimensions ...");

            for (int i = 0; i < images.Length; i++)
            {
                using (var oneBitmap = new Bitmap(images[i].FullName))
                {
                    if (oneBitmap.Width < minWidth)
                    {
                        minWidth = oneBitmap.Width;
                    }
                    if (oneBitmap.Height < minHeight)
                    {
                        minHeight = oneBitmap.Height;
                    }
                }
            }
            form.SetP2TxtBoxInfoText($"Smallest dimension: Width: {minWidth}, Height: {minHeight}.");
            form.SetP2TxtBoxInfoText(string.Empty);
            form.SetP2TxtBoxInfoText("Any to the video added image will be resized to this dimension - if necessary.");
            form.SetP2TxtBoxInfoText("Start to create video ... Be patient. This will take its time!");

            var pathAndFileNameNewVideo = Path.Combine(pathToTheImages, videoFileName);
            using (var vFWriter = new VideoFileWriter())
            {
                vFWriter.Open(pathAndFileNameNewVideo, minWidth, minHeight, frameRate, VideoCodec.MPEG2);

                for (int i = 0; i < images.Length; i++)
                {
                    using (var oneBitmap = new Bitmap(images[i].FullName))
                    {
                        if (oneBitmap.Width != minWidth || oneBitmap.Height != minHeight)
                        {
                            vFWriter.WriteVideoFrame(ReduceBitmap(oneBitmap, minWidth, minHeight));
                        }
                        else
                        {
                            vFWriter.WriteVideoFrame(oneBitmap);
                        }
                    }
                }
                vFWriter.Close();
            }
            form.SetP2TxtBoxInfoText("Video successful created and in the image folder stored!");
        }
예제 #29
0
 public void SetWriter(VideoFileWriter _videoFileWriter)
 {
     mWriter = _videoFileWriter;
 }
예제 #30
0
파일: CameraWindow.cs 프로젝트: tdhieu/iSpy
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Invalidate();
            }
            LocationChanged -= CameraWindowLocationChanged;
            Resize-=CameraWindowResize;

            _toolTipCam.RemoveAll();
            _toolTipCam.Dispose();
            _timeLapseWriter = null;
            _writer = null;
            base.Dispose(disposing);
        }
예제 #31
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";
        }
예제 #32
0
파일: CameraWindow.cs 프로젝트: tdhieu/iSpy
        private void CloseTimeLapseWriter()
        {
            _timeLapseTotal = 0;
            _timeLapseFrameCount = 0;

            if (_timeLapseWriter == null)
                return;

            try
            {
                Program.FfmpegMutex.WaitOne();
                _timeLapseWriter.Dispose();
            }
            catch (Exception ex)
            {
                ErrorHandler?.Invoke(ex.Message);
            }
            finally
            {
                try
                {
                    Program.FfmpegMutex.ReleaseMutex();
                }
                catch (ObjectDisposedException)
                {
                    //can happen on shutdown
                }
            }

            _timeLapseWriter = null;

            var fpath = Dir.Entry + "video\\" + Camobject.directory + "\\" + TimeLapseVideoFileName + CodecExtension;

            var fi = new FileInfo(fpath);
            var dSeconds = Convert.ToInt32((Helper.Now - TimelapseStart).TotalSeconds);

            FilesFile ff = _filelist.FirstOrDefault(p => p.Filename.EndsWith(TimeLapseVideoFileName + CodecExtension));
            bool newfile = false;
            if (ff == null)
            {
                ff = new FilesFile();
                newfile = true;
            }

            ff.CreatedDateTicks = DateTime.Now.Ticks;
            ff.Filename = TimeLapseVideoFileName + CodecExtension;
            ff.MaxAlarm = 0;
            ff.SizeBytes = fi.Length;
            ff.DurationSeconds = dSeconds;
            ff.IsTimelapse = true;
            ff.IsMergeFile = false;
            ff.AlertData = "";
            ff.TriggerLevel = 0;
            ff.TriggerLevelMax = 0;


            if (newfile)
            {
                lock (_lockobject)
                    _filelist.Insert(0, ff);

                MainForm.MasterFileAdd(new FilePreview(TimeLapseVideoFileName + CodecExtension, dSeconds,
                                                            Camobject.name, DateTime.Now.Ticks, 2, Camobject.id,
                                                            ff.MaxAlarm,false,false));
                
                MainForm.NeedsMediaRefresh = Helper.Now;
            }
        }
예제 #33
0
        public async Task <bool> WriteVideoFrames(string path, List <DrawableMessage> lines, int start_frame, int end_frame, IProgress <VideoProgress> progress = null, CancellationToken ct = default(CancellationToken))
        {
            var drawable_messages = new Stack <DrawableMessage>();
            var last_chat         = 0;

            return(await Task.Run(() =>
            {
                using (var writer = new VideoFileWriter())
                {
                    if (Width % 2 != 0)
                    {
                        Width -= 1;
                    }
                    if (Height % 2 != 0)
                    {
                        Height -= 1;
                    }
                    using (var bmp = new Bitmap(Width, Height))
                    {
                        writer.Open(path, Width, Height, FPS, Codec);
                        var bounds = new Rectangle(0, 0, Width, Height);
                        TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);

                        for (int i = start_frame; i <= end_frame; i++)
                        {
                            if (ct.IsCancellationRequested)
                            {
                                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Paused);
                                TaskbarManager.Instance.SetProgressValue(0, 1);
                                progress?.Report(new VideoProgress(0, 1, VideoProgress.VideoStatus.Idle));
                                return false;
                            }

                            TaskbarManager.Instance.SetProgressValue(i, end_frame);
                            progress?.Report(new VideoProgress(i, end_frame, VideoProgress.VideoStatus.Rendering));

                            if (last_chat < lines.Count)
                            {
                                // Note that this intentionally pulls at most one chat per frame
                                var chat = lines.ElementAt(last_chat);
                                if (!chat.Live && !VodChat)
                                {
                                    last_chat++;
                                }
                                else if (chat.StartFrame < i)
                                {
                                    drawable_messages.Push(chat);
                                    last_chat++;
                                }
                            }

                            DrawFrame(bmp, drawable_messages, i);
                            writer.WriteVideoFrame(bmp);
                        }

                        TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Paused);


                        return true;
                    }
                }
            }));
        }
        public MainWindow()
        {
            InitializeComponent();

            this._isRecording = false;
            this._frameCount  = 0;
            this._width       = SystemInformation.VirtualScreen.Width;
            this._height      = SystemInformation.VirtualScreen.Height;
            this._stopWatch   = new Stopwatch();
            this._screenArea  = Rectangle.Empty;

            this.bt_Save.IsEnabled = false;
            this._writer           = new VideoFileWriter();

            _screenNames = new List <string>();
            _screenNames.Add(@"Select ALL");
            foreach (var screen in Screen.AllScreens)
            {
                _screenNames.Add(screen.DeviceName);
            }
            this.cb_screenSelector.ItemsSource   = _screenNames;
            this.cb_screenSelector.SelectedIndex = 0;

            // Codec ComboBox
            this.cb_VideoCodec.ItemsSource   = Enum.GetValues(typeof(VideoCodec));
            this.cb_VideoCodec.SelectedIndex = 0;

            // BitRate 2000kbit/s 2000000 1000000
            this.cb_BitRate.ItemsSource   = Enum.GetValues(typeof(BitRate));
            this.cb_BitRate.SelectedIndex = 5;

            // Eye Device Selection
            this.cb_eyeDevice.ItemsSource   = Enum.GetValues(typeof(EyeDeviceType));
            this.cb_eyeDevice.SelectedIndex = 0;
            _EyeDeviceType = EyeDeviceType.None;

            //URL ReadWriter
            _URLReadWriteThread = new Thread(URLReadWriter);

            // Mouse and Eye Timer
            this._MouseGazeTimer          = new System.Timers.Timer();
            this._MouseGazeTimer.Elapsed += new ElapsedEventHandler(OnMouseGazeTimedEvent);

            //Lock DB data
            _MKEventLock  = new object();
            _URLEventLock = new object();
            _RawdataLock  = new object();
            //DB Event ID
            _MKEventID  = 0;
            _URLEventID = 0;
            _RawdataID  = 1;
            //_FirstRaw = true;
            _FixationID = 0;
            //FPS and Video time(ms)
            _FPS       = 10;
            _VideoTime = 0;
            //Get data
            _isGettingData = false;
            //Get URL data
            _URLData  = new string[] { null, null };
            _getURL   = false;
            _isNewURL = false;
            //_WebPos = new System.Windows.Point();
            _WebPos           = null;
            _WebPosTemp       = null;
            _isNewStartScroll = false;
            _isNextURLSave    = false;
            _WinPos           = null;

            Console.SetOut(TextWriter.Null);
        }
        public VedioGenerator(string savePath, int frameRate, int width, int height)
        {
            VideoFileWriter writer = new VideoFileWriter();

            writer.Open(savePath, width, height, frameRate, VideoCodec.MPEG4);
        }
예제 #36
0
 private void InitVideoFileWriter(int height, int width)
 {
     videoFileWriter = new VideoFileWriter();
     videoFileWriter.Open(videoOutputFile, width, height, 60, VideoCodec.Default, 5000000);
 }
예제 #37
0
파일: Program.cs 프로젝트: Zed-Rustam/NNLD
        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");
            }
        }
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            this.timer1.Stop();


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

            VideoFileWriter writer = new VideoFileWriter();

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


            for (int ii = 0; ii != (int)(frameRate * time); ii++)
            {
                Application.DoEvents();



                int startDegree = getPositionOfBar(0) - barSize / 2;
                g1.Clear(Color.White);
                for (int i = 0; i != width; i++)
                {
                    if (i >= startDegree & i < startDegree + barSize)
                    {
                        for (int j = 0; j != height; j++)
                        {
                            if (j >= widthUp & j <= widthDown)
                            {
                                if (rg.bar.randomCanvasBackground[i - startDegree][j] == 0)
                                {
                                    image1.SetPixel(i, j, Color.Black);
                                }
                            }
                            else
                            {
                                if (rg.background.randomCanvasBackground[i][j] == 0)
                                {
                                    image1.SetPixel(i, j, Color.Black);
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j != height; j++)
                        {
                            if (rg.background.randomCanvasBackground[i][j] == 0)
                            {
                                image1.SetPixel(i, j, Color.Black);
                            }
                        }
                    }
                }


                if (rbLeftToRight.Checked)
                {
                    rg.background.MoveRightForSimpleCanvas(stepForBackGround);
                }
                else if (rbRightToLeft.Checked)
                {
                    rg.background.MoveLeftForSimpleCanvas(stepForBackGround);
                }
                else
                {
                    if (orientation == 1)
                    {
                        positiondegree += step;
                        rg.background.MoveLeftForSimpleCanvas(stepForBackGround);
                        if (positiondegree > degree)
                        {
                            orientation = -1;
                        }
                    }

                    if (orientation == -1)
                    {
                        positiondegree -= step;
                        rg.background.MoveRightForSimpleCanvas(stepForBackGround);
                        if (positiondegree < -degree)
                        {
                            orientation = 1;
                        }
                    }
                }

                this.progressBar1.Value = ii;
                writer.WriteVideoFrame(image1);
            }
            writer.Close();
            this.progressBar1.Value = (int)(frameRate * time);
            MessageBox.Show("Saved!!");
        }
예제 #39
0
        private void b_Record_Click(object sender, EventArgs e)
        {
            if (bVideoConnected)
            {
                if (bVideoRecording == false)
                {
                    if (vfwWriter != null) { vfwWriter.Close(); }

                    l_capture_file.Text = "capture" + String.Format("-{0:yymmdd-hhmm}", DateTime.Now);
                    vfwWriter = new VideoFileWriter();
                    //create new video file
                    vfwWriter.Open(gui_settings.sCaptureFolder + "\\capture" + String.Format("-{0:yyMMdd-hhmm}", DateTime.Now) + ".avi", 640, 480, (int)nFrameRate.Value, (VideoCodec)cb_codec.SelectedIndex, (int)(1000000 * nBitRate.Value));
                    b_Record.Text = "Recording";
                    b_Record.BackColor = Color.Red;
                    tsFrameTimeStamp = new TimeSpan(0);
                    tsFrameRate = new TimeSpan(10000000 / (long)nFrameRate.Value);
                    bVideoRecording = true;
                }
                else
                {
                    bVideoRecording = false;
                    System.Threading.Thread.Sleep(50);
                    b_Record.Text = "Start Recording";
                    b_Record.BackColor = Color.Transparent;
                    vfwWriter.Close();
                    l_capture_file.Text = "";
                }
            }
        }
예제 #40
0
        private void bgWorkerSave_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.CurrentThread.Name = "Saving";
            BackgroundWorker bgWorker = sender as BackgroundWorker;

            if (!(e.Argument is SavingSettings))
            {
                saveResult = SaveResult.UnknownError;
                e.Result   = 0;
                return;
            }

            SavingSettings settings = (SavingSettings)e.Argument;

            if (settings.ImageRetriever == null || settings.InputFrameInterval < 0 || bgWorker == null)
            {
                saveResult = SaveResult.UnknownError;
                e.Result   = 0;
                return;
            }

            try
            {
                log.DebugFormat("Saving selection [{0}]->[{1}] to: {2}", settings.Section.Start, settings.Section.End, Path.GetFileName(settings.File));

                // TODO it may actually make more sense to split the saving methods for regular
                // save, paused video and diaporama. It will cause inevitable code duplication but better encapsulation and simpler algo.
                // When each save method has its own class and UI panel, it will be a better design.

                if (!settings.PausedVideo)
                {
                    // Take special care for slowmotion, the frame interval can not go down indefinitely.
                    // Use frame duplication when under 8fps.
                    settings.Duplication         = (int)Math.Ceiling(settings.InputFrameInterval / 125.0);
                    settings.KeyframeDuplication = settings.Duplication;
                    settings.OutputFrameInterval = settings.InputFrameInterval / settings.Duplication;
                    if (settings.KeyframesOnly)
                    {
                        settings.EstimatedTotal = metadata.Count * settings.Duplication;
                    }
                    else
                    {
                        settings.EstimatedTotal = videoReader.EstimatedFrames * settings.Duplication;
                    }
                }
                else
                {
                    // For paused video, slow motion is not supported.
                    // InputFrameInterval will have been set to a multiple of the original frame interval.
                    settings.Duplication         = 1;
                    settings.KeyframeDuplication = (int)(settings.InputFrameInterval / metadata.UserInterval);
                    settings.OutputFrameInterval = metadata.UserInterval;

                    long regularFramesTotal = videoReader.EstimatedFrames - metadata.Count;
                    long keyframesTotal     = metadata.Count * settings.KeyframeDuplication;
                    settings.EstimatedTotal = regularFramesTotal + keyframesTotal;
                }

                log.DebugFormat("interval:{0}, duplication:{1}, kf duplication:{2}", settings.OutputFrameInterval, settings.Duplication, settings.KeyframeDuplication);

                videoReader.BeforeFrameEnumeration();
                IEnumerable <Bitmap> images = EnumerateImages(settings);

                VideoFileWriter w            = new VideoFileWriter();
                string          formatString = FilenameHelper.GetFormatString(settings.File);
                saveResult = w.Save(settings, videoReader.Info, formatString, images, bgWorker);
                videoReader.AfterFrameEnumeration();
            }
            catch (Exception exp)
            {
                saveResult = SaveResult.UnknownError;
                log.Error("Unknown error while saving video.");
                log.Error(exp.StackTrace);
            }

            e.Result = 0;
        }
예제 #41
0
        private void button1_Click(object sender, EventArgs e)
        {
            int key_R = 0;
            int key_G = 128;
            int key_B = 0;

            Color Key = new Color();

            Key = Color.FromArgb(key_R, key_G, key_B);

            double KCb = -(0.168736 * Key.R) - (0.331264 * Key.G) + (0.5 * Key.B);
            double KCr = 0.5 * Key.R - 0.418688 * Key.G - 0.081312 * Key.B;

            VideoFileWriter writer = new VideoFileWriter();

            VideoFileReader reader = new VideoFileReader();     //point

            reader.Open(@"D:\Github\GiM\chicken.mp4");

            int height = reader.Height;
            int width  = reader.Width;

            writer.Open("chicken.mp4", width, height, 25, VideoCodec.MPEG4);

            Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb);

            for (int i = 0; i < 1000; i++)
            {
                image = reader.ReadVideoFrame();
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        Color c = image.GetPixel(x, y);

                        double Pb = -0.168736 * c.R - 0.331264 * c.G + 0.5 * c.B;
                        double Pr = 0.5 * c.R - 0.418688 * c.G - 0.081312 * c.B;

                        // Obliczanie dystansu i punktu na wykresie funkcji
                        double dist  = Math.Sqrt((KCb - Pb) * (KCb - Pb) + (KCr - Pr) * (KCr - Pr));
                        double point = 1;
                        // Przedziały
                        int a1 = 40;
                        int a2 = 60;

                        if (dist <= a1)
                        {
                            point = 0;
                        }
                        else if (dist >= a2)
                        {
                            point = 1;
                        }
                        else if (dist > a1 && dist < a2)
                        {
                            point = (dist - a1) / (a2 - a1);
                        }

                        double q = 1 - point;

                        double PwR = Math.Min(Math.Max(c.R - q * Key.R, 0) + q * Color.White.R, 255);
                        double PwG = Math.Min(Math.Max(c.G - q * Key.G, 0) + q * Color.White.G, 255);
                        double PwB = Math.Min(Math.Max(c.B - q * Key.B, 0) + q * Color.White.B, 255);

                        Color FColor = new Color();
                        FColor = Color.FromArgb((int)PwR, (int)PwG, (int)PwB);

                        image.SetPixel(x, y, FColor);
                    }
                }
                writer.WriteVideoFrame(image);
                image.Dispose();
            }
            writer.Close();
            reader.Close();
        }
예제 #42
0
        private void TimerRecording_Tick(object sender, System.EventArgs e)
        {
            lock (syncObj)
            {
                if (IsRecording)
                {
                    // **************************************************
                    //System.DateTime now = System.DateTime.Now;
                    //System.DateTime currentFrameTime = now;

                    //if (RecordingStartTime == System.DateTime.MinValue)
                    //{
                    //	RecordingStartTime = now;
                    //}

                    //System.TimeSpan timestamp =
                    //	currentFrameTime - RecordingStartTime;

                    //if (timestamp > System.TimeSpan.Zero)
                    //{
                    //	System.Drawing.Rectangle rectangle =
                    //		new System.Drawing.Rectangle(x: 0, y: 0, width: CaptureRegionWidth, height: CaptureRegionHeight);

                    //	System.Drawing.Region region = new System.Drawing.Region(rect: rectangle);

                    //	System.Drawing.Bitmap bitmap =
                    //		new System.Drawing.Bitmap(width: CaptureRegionWidth, height: CaptureRegionHeight);

                    //	System.Drawing.Graphics graphics =
                    //		System.Drawing.Graphics.FromImage(bitmap);

                    //	graphics.CopyFromScreen
                    //		(sourceX: 0, sourceY: 0,
                    //		destinationX: 0, destinationY: 0,
                    //		blockRegionSize: new System.Drawing.Size(width: CaptureRegionWidth, height: CaptureRegionHeight));

                    //	VideoFileWriter.WriteVideoFrame
                    //		(frame: bitmap, timestamp: timestamp);

                    //	//VideoFileWriter.WriteVideoFrame
                    //	//	(frame: bitmap, timestamp: timestamp, region: rectangle);
                    //}
                    // **************************************************

                    // **************************************************
                    //var bp = new System.Drawing.Bitmap(800, 600);
                    //var gr = System.Drawing.Graphics.FromImage(bp);

                    //gr.CopyFromScreen
                    //	(0, 0, 0, 0, new System.Drawing.Size(bp.Width, bp.Height));

                    //VideoFileWriter.WriteVideoFrame(frame: bp);
                    // **************************************************

                    // **************************************************
                    System.Drawing.Bitmap bitmap =
                        new System.Drawing.Bitmap
                            (width: CaptureRegionWidth, height: CaptureRegionHeight);

                    System.Drawing.Graphics graphics =
                        System.Drawing.Graphics.FromImage(bitmap);

                    graphics.CopyFromScreen
                        (sourceX: 0, sourceY: 0,
                        destinationX: 0, destinationY: 0,
                        blockRegionSize: new System.Drawing.Size(width: CaptureRegionWidth, height: CaptureRegionHeight));

                    graphics.Dispose();
                    graphics = null;

                    VideoFileWriter.WriteVideoFrame(frame: bitmap);

                    bitmap.Dispose();
                    bitmap = null;
                    // **************************************************
                }
            }
        }
예제 #43
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.";
            }
        }
 public VideoRecordingService()
 {
     _writer = new VideoFileWriter();
     _videoDurationTracker = 0;
 }
예제 #45
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;
        }
예제 #46
0
        private async Task StartInternal(RecordSettings settings)
        {
            try
            {
                try
                {
                    Thread.CurrentThread.Priority = ThreadPriority.Highest;
                }
                catch (Exception ex) { }
                _stopwatch = _stopwatch ?? new Stopwatch();
                _stopwatch.Reset();
                _stopwatch.Start();
                _stopWaiter.Reset();

                if (!Directory.Exists(settings.OutputPath))
                {
                    Directory.CreateDirectory(settings.OutputPath);
                }

                const double second            = 1000;
                const double minute            = second * 60;
                const int    quant             = 10;                                                                                //timeouts don't include process switching
                var          inputSnapInterval = (int)Math.Max((settings.Realtime ? second / settings.Fps : settings.Interval), 0); //snap every N ms
                var          splitInterval     = settings.SplitInterval * minute / inputSnapInterval;                               //split every N frames
                var          inputExpectedFps  = inputSnapInterval > 0 ? second / inputSnapInterval : 0;
                var          sourceRect        = settings.CaptureRectangle;

                var framesWritten = 0L;
                using (var tmr = new Timer())
                {
                    tmr.Interval = 100;
                    tmr.Elapsed += (a, b) => settings.OnFrameWritten(_stopwatch.Elapsed);
                    tmr.Start();
                    while (Recording)
                    {
                        var outfile = Path.Combine(settings.OutputPath, DateTime.Now.ToFileTime().ToString() + ".avi");
                        using (var outstream = new VideoFileWriter())
                        {
                            outstream.Open(outfile, sourceRect.Width, sourceRect.Height, settings.Fps, settings.Codec, settings.Bitrate);
                            using (ISnapper snapper = GetSnapper(settings))
                            {
                                using (var processingSemaphore = new SemaphoreSlim(snapper.MaxProcessingThreads))
                                {
                                    using (var writeSemaphore = new SemaphoreSlim(1))
                                    {
                                        snapper.SetSource(sourceRect);
                                        var    dropNextNFrames            = 0;
                                        var    lastSyncFrames             = framesWritten;
                                        double lastSyncTime               = _stopwatch.ElapsedMilliseconds;
                                        var    emptyFramesSinceLastSync   = 0;
                                        var    crashedFramesSinceLastSync = 0;
                                        var    slowFramewsSinceLastSync   = 0;

                                        for (var i = 0L; (splitInterval == null || i < splitInterval) && Recording; i++)
                                        {
                                            Task   tsk          = null;
                                            Bitmap currentFrame = null;
                                            try
                                            {
                                                framesWritten++;

                                                //drop frame if required
                                                if (dropNextNFrames > 0 && currentFrame != null)
                                                {
                                                    dropNextNFrames--;
                                                    lastSyncTime   = _stopwatch.ElapsedMilliseconds;
                                                    lastSyncFrames = framesWritten;
                                                    outstream.WriteVideoFrame(currentFrame);
                                                    continue;
                                                }
                                                tsk = Task.Delay(inputSnapInterval - quant);

                                                /*
                                                 * these bitmaps are actually the same object or null -> we only have to dispose it once
                                                 */
                                                var elapsedBeforeCurrentSnap = _stopwatch.Elapsed.TotalMilliseconds;
                                                await processingSemaphore.WaitAsync().ConfigureAwait(false);

                                                var tmp = await snapper.Snap(inputSnapInterval).ConfigureAwait(false);

                                                var elapsedAfterCurrentSnap = _stopwatch.Elapsed.TotalMilliseconds;
                                                if (elapsedAfterCurrentSnap - elapsedBeforeCurrentSnap > inputSnapInterval)
                                                {
                                                    //Debug.WriteLine($"[F**K] slow snap: {elapsedAfterCurrentSnap - elapsedBeforeCurrentSnap}ms");
                                                    slowFramewsSinceLastSync++;
                                                }
                                                if (tmp == null)
                                                {
                                                    //Debug.WriteLine("[F**K] empty snap");
                                                    emptyFramesSinceLastSync++;
                                                }
                                                currentFrame = tmp ?? currentFrame;
                                                //Debug.WriteLine($"[SNAP] {_stopwatch.ElapsedMilliseconds} ms");
                                                //settings.OnFrameWritten?.Invoke(_stopwatch.Elapsed);
                                            }
                                            catch (Exception ex)
                                            {
                                                //Debug.WriteLine($"[F**K] crashed on snap: {ex.Message}");
                                                crashedFramesSinceLastSync++;
                                            }
                                            try
                                            {
                                                Task.Run(async() =>
                                                {
                                                    try
                                                    {
                                                        if (currentFrame != null)
                                                        {//offload to separate thread
                                                            PreprocessFrame(currentFrame, settings);
                                                            await writeSemaphore.WaitAsync().ConfigureAwait(false);
                                                            try
                                                            {
                                                                outstream.WriteVideoFrame(currentFrame);
                                                            }
                                                            finally
                                                            {
                                                                writeSemaphore.Release();
                                                            }
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        processingSemaphore.Release();
                                                    }
                                                }).ConfigureAwait(false);
                                            }
                                            catch (Exception ex)
                                            {
                                                //todo: crashed frame logging
                                            }

                                            double elapsedNow           = _stopwatch.ElapsedMilliseconds;
                                            var    elapsedSinceLastSync = elapsedNow - lastSyncTime;
                                            if (elapsedSinceLastSync >= second)
                                            {
                                                var framesSinceLastSync = framesWritten - lastSyncFrames;
                                                //only relevant for realtime+ recordings
                                                var recentFps      = framesSinceLastSync * second / elapsedSinceLastSync;
                                                var recentFpsDelta = recentFps - inputExpectedFps;
                                                Console.WriteLine($"{framesSinceLastSync} frames({emptyFramesSinceLastSync} empty, {crashedFramesSinceLastSync} crashed, {slowFramewsSinceLastSync} slow) in last {elapsedSinceLastSync.ToString("F")} ms ({recentFps.ToString("F")} fps). Total FPS: {(framesWritten * second / elapsedNow).ToString("F")}. Expected: {inputExpectedFps.ToString("F")}");
#if !PERF
                                                if (recentFpsDelta > 1) //faster than expected && at least one actual frame
                                                {
                                                    tsk.Wait();         //wait for the current loop
                                                                        //Debug.WriteLine($"[F**K] Slow down, fella: {recentFpsDelta} frames");
                                                    Task.Delay((int)(inputSnapInterval * recentFpsDelta - quant)).Wait();
                                                }
                                                else if (recentFpsDelta < -1)//too slow
                                                {
                                                    dropNextNFrames = -(int)recentFpsDelta;
                                                    //Debug.WriteLine($"[F**K] dropping {dropNextNFrames} frames");
                                                }
#endif
                                                lastSyncFrames             = framesWritten;
                                                lastSyncTime               = elapsedNow;
                                                emptyFramesSinceLastSync   = 0;
                                                crashedFramesSinceLastSync = 0;
                                                slowFramewsSinceLastSync   = 0;
                                            }
#if !PERF
                                            tsk?.Wait();
#endif
                                        }
                                        await writeSemaphore.WaitAsync().ConfigureAwait(false);
                                    }
                                }
                            }
                        }
                    }
                    tmr.Stop();
                }
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(ex.Message);
                //global
            }
            finally
            {
                _stopwatch?.Stop();
                _stopWaiter.Set();
            }
        }
예제 #47
0
파일: CameraWindow.cs 프로젝트: tdhieu/iSpy
        private bool OpenTimeLapseWriter()
        {
            DateTime date = DateTime.Now;
            String filename =
                $"TimeLapse_{date.Year}-{Helper.ZeroPad(date.Month)}-{Helper.ZeroPad(date.Day)}_{Helper.ZeroPad(date.Hour)}-{Helper.ZeroPad(date.Minute)}-{Helper.ZeroPad(date.Second)}";
            TimeLapseVideoFileName = Camobject.id + "_" + filename;
            string folder = Dir.Entry + "video\\" + Camobject.directory + "\\";

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

            filename = folder + TimeLapseVideoFileName;


            Bitmap bmpPreview = LastFrame;

            if (bmpPreview != null)
            {

                bmpPreview.Save(folder + @"thumbs/" + TimeLapseVideoFileName + "_large.jpg", MainForm.Encoder,
                    MainForm.EncoderParams);
                Image.GetThumbnailImageAbort myCallback = ThumbnailCallback;
                Image myThumbnail = bmpPreview.GetThumbnailImage(96, 72, myCallback, IntPtr.Zero);

                Graphics g = Graphics.FromImage(myThumbnail);
                var strFormat = new StringFormat
                                {
                                    Alignment = StringAlignment.Center,
                                    LineAlignment = StringAlignment.Far
                                };
                var rect = new RectangleF(0, 0, 96, 72);

                g.DrawString(LocRm.GetString("Timelapse"), MainForm.Drawfont, MainForm.OverlayBrush,
                    rect, strFormat);
                strFormat.Dispose();

                myThumbnail.Save(folder + @"thumbs/" + TimeLapseVideoFileName + ".jpg", MainForm.Encoder,
                    MainForm.EncoderParams);

                g.Dispose();
                myThumbnail.Dispose();
                bmpPreview.Dispose();
            }


            _timeLapseWriter = null;
            bool success = false;

            try
            {
                try
                {
                    Program.FfmpegMutex.WaitOne();
                    _timeLapseWriter = new VideoFileWriter();
                    _timeLapseWriter.Open(filename + CodecExtension, _videoWidth, _videoHeight, Codec,
                                          CalcBitRate(Camobject.recorder.quality), Camobject.recorder.timelapseframerate);

                    success = true;
                    TimelapseStart = Helper.Now;
                }
                catch (Exception ex)
                {
                    ErrorHandler?.Invoke(ex.Message);
                    _timeLapseWriter = null;
                    //Camobject.recorder.timelapse = 0;
                }
                finally
                {
                    try
                    {
                        Program.FfmpegMutex.ReleaseMutex();
                    }
                    catch (ObjectDisposedException)
                    {
                        //can happen on shutdown
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandler?.Invoke(ex.Message);
            }
            return success;
        }
예제 #48
0
        public static void Run(string videoPath, string videoName)
        {
            var reader = new VideoFileReader();

            reader.Open(videoPath + videoName);
            var writer         = new VideoFileWriter();
            var numberOfFrames = (int)reader.FrameCount;
            var probeBitmap    = new FastBitmap(reader.ReadVideoFrame(0));

            probeBitmap.LockBits();
            var maxValues = CalcMaxValues(probeBitmap.Width, probeBitmap.Height);
            var maxX      = maxValues.Item1;
            var maxY      = maxValues.Item2;

            //Console.WriteLine($"{maxX}:{maxY}");
            writer.Height     = probeBitmap.Height;
            writer.Width      = probeBitmap.Width;
            writer.FrameRate  = 30;
            writer.VideoCodec = VideoCodec.Mpeg4;
            writer.BitRate    = reader.BitRate;
            writer.Open(videoPath + "out.avi");
            for (var t = 70; t < numberOfFrames; t++)
            {
                var        convertedBitmap = new FastBitmap(new Bitmap(probeBitmap.Width, probeBitmap.Height));
                FastBitmap currentBitmap;
                try
                {
                    currentBitmap = new FastBitmap(reader.ReadVideoFrame(t));
                }
                catch (Exception ignored)
                {
                    break;
                }
                convertedBitmap.LockBits();
                currentBitmap.LockBits();
                for (var x = 0; x < probeBitmap.Width; x++)
                {
                    for (var y = 0; y < probeBitmap.Height; y++)
                    {
                        var pixel = ConvertToPolar(x - probeBitmap.Width / 2, y - probeBitmap.Height / 2);
                        var convX = FastUtils.FastAbs((int)(pixel.Item2 / maxY * (probeBitmap.Width - 1)));
                        var convY = FastUtils.FastAbs((int)(pixel.Item1 / maxX * (probeBitmap.Height - 1)));
                        convertedBitmap.SetPixel(convX, convY, currentBitmap.GetPixel(x, y));
                    }
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();
                for (int i = 0; i < 4; i++)
                {
                    convertedBitmap = CompleteBitmap(convertedBitmap);
                }
                sw.Stop();
                Console.WriteLine(sw.Elapsed);
                currentBitmap.UnlockBits();
                currentBitmap.DisposeSource();
                convertedBitmap.GetSource().Save(videoPath + "test.png");
                break;
                //convertedBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
                writer.WriteVideoFrame(convertedBitmap.GetSource());
                convertedBitmap.DisposeSource();
            }
            probeBitmap.UnlockBits();
            writer.Flush();
        }
예제 #49
0
파일: CameraWindow.cs 프로젝트: tdhieu/iSpy
        private void Record()
        {
            try
            {
                MainForm.RecordingThreads++;
                AbortedAudio = false;
                LogToPlugin("Recording Started");
                string linktofile = "";
                
                
                string previewImage = "";
                try
                {

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

                    try
                    {
                        DateTime date = DateTime.Now.AddHours(Convert.ToDouble(Camobject.settings.timestampoffset));

                        string filename =
                            $"{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;
                        bool bAudio = vc?.AudioSource != null && vc.Micobject.settings.active;

                        if (bAudio)
                        {
                            vc.StartSaving();
                            vc.ForcedRecording = ForcedRecording;
                        }

                        VideoFileName = Camobject.id + "_" + filename;
                        string folder = Dir.Entry + "video\\" + Camobject.directory + "\\";

                        string videopath = folder + VideoFileName + CodecExtension;
                        bool error = false;
                        double maxAlarm = 0;
                        long lastvideopts = -1, lastaudiopts = -1;
                        DateTime recordingStart = Helper.Now;
                        try
                        {
                            if (!Directory.Exists(folder))
                                Directory.CreateDirectory(folder);

                            try
                            {

                                Program.FfmpegMutex.WaitOne();
                                _writer = new VideoFileWriter();

                                bool bSuccess;
                                if (bAudio)
                                {
                                    bSuccess = _writer.Open(videopath, _videoWidth, _videoHeight, Codec,
                                        CalcBitRate(Camobject.recorder.quality), CodecAudio, CodecFramerate,
                                        vc.Micobject.settings.bits*
                                        vc.Micobject.settings.samples*
                                        vc.Micobject.settings.channels,
                                        vc.Micobject.settings.samples, vc.Micobject.settings.channels);
                                }
                                else
                                {
                                    bSuccess = _writer.Open(videopath, _videoWidth, _videoHeight, Codec,
                                        CalcBitRate(Camobject.recorder.quality), CodecFramerate);
                                }

                                if (!bSuccess)
                                {
                                    throw new Exception("Failed to open up a video writer");
                                }
                                else
                                {
                                    try
                                    {
                                        bool success;
                                        linktofile = HttpUtility.UrlEncode(MainForm.ExternalURL(out success) + "loadclip.mp4?oid=" + Camobject.id + "&ot=2&fn=" + VideoFileName + CodecExtension + "&auth=" + MainForm.Identifier);
                                        if (!success)
                                        {
                                            linktofile = "";
                                            throw new Exception("External IP unavailable");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.LogExceptionToFile(ex, "Generating external link to file");
                                    }
                                    DoAlert("recordingstarted", linktofile);
                                }

                            }
                            finally
                            {
                                try
                                {
                                    Program.FfmpegMutex.ReleaseMutex();
                                }
                                catch (ObjectDisposedException)
                                {
                                    //can happen on shutdown
                                }
                            }


                            Helper.FrameAction? peakFrame = null;
                            bool first = true;

                            while (!_stopWrite.WaitOne(5))
                            {
                                Helper.FrameAction fa;
                                if (Buffer.TryDequeue(out fa))
                                {
                                    if (first)
                                    {
                                        recordingStart = fa.TimeStamp;
                                        first = false;
                                    }

                                    WriteFrame(fa, recordingStart, ref lastvideopts, ref maxAlarm, ref peakFrame,
                                        ref lastaudiopts);
                                }
                                if (bAudio)
                                {
                                    if (vc.Buffer.TryDequeue(out fa))
                                    {
                                        if (first)
                                        {
                                            recordingStart = fa.TimeStamp;
                                            first = false;
                                        }

                                        WriteFrame(fa, recordingStart, ref lastvideopts, ref maxAlarm, ref peakFrame,
                                            ref lastaudiopts);
                                    }
                                }
                            }

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

                            if (peakFrame != null && peakFrame.Value.Content != null)
                            {
                                try
                                {
                                    using (var ms = new MemoryStream(peakFrame.Value.Content))
                                    {
                                        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)
                                {
                                    ErrorHandler?.Invoke(ex.Message + ": " + ex.StackTrace);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            error = true;
                            ErrorHandler?.Invoke(ex.Message + " (" + ex.StackTrace + ")");
                        }
                        finally
                        {
                            if (_writer != null && _writer.IsOpen)
                            {
                                try
                                {
                                    Program.FfmpegMutex.WaitOne();
                                    _writer.Dispose();
                                }
                                catch (Exception ex)
                                {
                                    ErrorHandler?.Invoke(ex.Message);
                                }
                                finally
                                {
                                    try
                                    {
                                        Program.FfmpegMutex.ReleaseMutex();
                                    }
                                    catch (ObjectDisposedException)
                                    {
                                        //can happen on shutdown
                                    }
                                }

                                _writer = null;
                            }
                            if (bAudio)
                                vc.StopSaving();
                        }
                        if (_firstFrame)
                        {
                            error = true;
                        }
                        if (error)
                        {
                            try
                            {
                                if (File.Exists(videopath))
                                    FileOperations.Delete(videopath);
                            }
                            catch
                            {
                                // ignored
                            }
                            MainForm.RecordingThreads--;
                            ClearBuffer();

                            goto end;
                        }


                        string path = Dir.Entry + "video\\" + Camobject.directory + "\\" +
                                      VideoFileName;

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

                        var 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*100, 100);
                        ff.SizeBytes = fi.Length;
                        ff.DurationSeconds = dSeconds;
                        ff.IsTimelapse = false;
                        ff.IsMergeFile = false;
                        ff.AlertData = Helper.GetMotionDataPoints(_motionData);
                        _motionData.Clear();
                        ff.TriggerLevel = (100 - Camobject.detector.minsensitivity); //adjusted
                        ff.TriggerLevelMax = (100 - Camobject.detector.maxsensitivity);

                        if (newfile)
                        {
                            lock (_lockobject)
                                _filelist.Insert(0, ff);

                            MainForm.MasterFileAdd(new FilePreview(fn, dSeconds, Camobject.name, DateTime.Now.Ticks, 2,
                                Camobject.id, ff.MaxAlarm, false, false));
                            MainForm.NeedsMediaRefresh = Helper.Now;
                            if (Camobject.settings.cloudprovider.recordings)
                            {
                                CloudGateway.Upload(2, Camobject.id, path + CodecExtension);
                            }
                            if (Camobject.recorder.ftpenabled)
                            {
                                FtpRecording(path + CodecExtension);
                            }
                        }
                        AbortedAudio = false;

                    }
                    catch (Exception ex)
                    {
                        ErrorHandler?.Invoke(ex.Message);
                    }

                    if (!string.IsNullOrEmpty(Camobject.recorder.trigger))
                    {
                        string[] tid = Camobject.recorder.trigger.Split(',');
                        switch (tid[0])
                        {
                            case "1":
                                VolumeLevel vl = MainForm.InstanceReference.GetVolumeLevel(Convert.ToInt32(tid[1]));
                                if (vl != null)
                                    vl.ForcedRecording = false;
                                break;
                            case "2":
                                CameraWindow cw = MainForm.InstanceReference.GetCameraWindow(Convert.ToInt32(tid[1]));
                                if (cw != null)
                                {
                                    cw.ForcedRecording = false;
                                    var vc = cw.VolumeControl;
                                    if (vc != null)
                                    {
                                        vc.ForcedRecording = false;
                                    }
                                }
                                break;
                        }
                    }
                }
                finally
                {
                    MainForm.RecordingThreads--;
                }
                Camobject.newrecordingcount++;

                Notification?.Invoke(this, new NotificationType("NewRecording", Camobject.name, previewImage));

                end:

                LogToPlugin("Recording Stopped");
                DoAlert("recordingstopped", linktofile);
            }
            catch (Exception ex)
            {
                Logger.LogExceptionToFile(ex);
            }
        }
예제 #50
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 ii = 0; ii != (int)(frameRate * time); ii++)
            {
                Application.DoEvents();
                if (rbLeftToRight.Checked)
                {
                    g.MoveRightForSimpleCanvas(step);
                }
                if (rbRightToLeft.Checked)
                {
                    g.MoveLeftForSimpleCanvas(step);
                }



                g1.Clear(Color.White);
                for (int i = 0; i != width; i++)
                {
                    if (g.simpleCanvas[i] == 0)
                    {
                        g1.DrawLine(new Pen(staticColor), i, 0, i, height);
                    }
                    else
                    {
                        if (switchState)
                        {
                            g1.DrawLine(new Pen(revColor_1), i, 0, i, height);
                        }
                        else
                        {
                            g1.DrawLine(new Pen(revColor_2), i, 0, i, height);
                        }
                    }
                }
                switchState = !switchState;


                writer.WriteVideoFrame(image1);


                this.progressBar1.Value = ii;
            }

            writer.Close();
            this.progressBar1.Value = (int)(frameRate * time);
            MessageBox.Show("Saved!!");
        }
예제 #51
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();
        }
예제 #52
0
        /// <summary>
        ///   Starts recording. Only works if the player has
        ///   already been started and is grabbing frames.
        /// </summary>
        ///
        public void StartRecording()
        {
            if (IsRecording || !IsPlaying)
            {
                return;
            }

            Rectangle area     = CaptureRegion;
            string    fileName = NewFileName();

            int      height         = area.Height;
            int      width          = area.Width;
            Rational framerate      = new Rational(1000, screenStream.FrameInterval);
            int      videoBitRate   = 1200 * 1000;
            int      audioBitRate   = 320 * 1000;
            int      audioFrameSize = 10 * 4096;

            OutputPath                           = Path.Combine(main.CurrentDirectory, fileName);
            RecordingStartTime                   = DateTime.MinValue;
            videoWriter                          = new VideoFileWriter();
            videoWriter.BitRate                  = videoBitRate;
            videoWriter.FrameRate                = framerate;
            videoWriter.Width                    = width;
            videoWriter.Height                   = height;
            videoWriter.VideoCodec               = VideoCodec.H264;
            videoWriter.VideoOptions["crf"]      = "18"; // visually lossless
            videoWriter.VideoOptions["preset"]   = "veryfast";
            videoWriter.VideoOptions["tune"]     = "zerolatency";
            videoWriter.VideoOptions["x264opts"] = "no-mbtree:sliced-threads:sync-lookahead=0";

            // Create audio devices which have been checked
            var audioDevices = new List <AudioCaptureDevice>();

            foreach (var audioViewModel in AudioCaptureDevices)
            {
                if (!audioViewModel.Checked)
                {
                    continue;
                }

                var device = new AudioCaptureDevice(audioViewModel.DeviceInfo);
                device.AudioSourceError += Device_AudioSourceError;
                device.Format            = SampleFormat.Format32BitIeeeFloat;
                device.SampleRate        = Settings.Default.SampleRate;
                device.DesiredFrameSize  = audioFrameSize;
                device.Start();

                audioDevices.Add(device);
            }

            if (audioDevices.Count > 0) // Check if we need to record audio
            {
                audioMixer = new AudioSourceMixer(audioDevices);
                audioMixer.AudioSourceError += Device_AudioSourceError;
                audioMixer.NewFrame         += AudioDevice_NewFrame;
                audioMixer.Start();

                videoWriter.AudioBitRate = audioBitRate;
                videoWriter.AudioCodec   = AudioCodec.Aac;
                videoWriter.AudioLayout  = audioMixer.NumberOfChannels == 1 ? AudioLayout.Mono : AudioLayout.Stereo;
                videoWriter.FrameSize    = audioFrameSize;
                videoWriter.SampleRate   = audioMixer.SampleRate;
            }

            //this.lastFrameTime = DateTime.MinValue;

            videoWriter.Open(OutputPath);

            HasRecorded = false;
            IsRecording = true;
        }
예제 #53
0
파일: CameraWindow.cs 프로젝트: vmail/main
        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));
        }
예제 #54
0
파일: CameraWindow.cs 프로젝트: vmail/main
        private bool OpenTimeLapseWriter()
        {
            DateTime date = DateTime.Now;
            String filename = String.Format("TimeLapse_{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));
            TimeLapseVideoFileName = Camobject.id + "_" + filename;
            string folder = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\";

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

            filename = folder+TimeLapseVideoFileName;

            Bitmap bmpPreview = Camera.LastFrame;

            bmpPreview.Save(folder + @"thumbs/" + TimeLapseVideoFileName + "_large.jpg", MainForm.Encoder, MainForm.EncoderParams);
            Image.GetThumbnailImageAbort myCallback = ThumbnailCallback;
            Image myThumbnail = bmpPreview.GetThumbnailImage(96, 72, myCallback, IntPtr.Zero);
            bmpPreview.Dispose();

            Graphics g = Graphics.FromImage(myThumbnail);
            var strFormat = new StringFormat {Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Far};
            var rect = new RectangleF(0, 0, 96, 72);

            g.DrawString(LocRm.GetString("Timelapse"), MainForm.Drawfont, MainForm.OverlayBrush,
                         rect, strFormat);
            strFormat.Dispose();

            myThumbnail.Save(folder + @"thumbs/" + TimeLapseVideoFileName + ".jpg", MainForm.Encoder, MainForm.EncoderParams);

            g.Dispose();
            myThumbnail.Dispose();

            _timeLapseWriter = null;
            bool success = false;

            try
            {

                int w, h;
                GetVideoSize(out w, out h);

                Program.WriterMutex.WaitOne();
                try
                {
                    _timeLapseWriter = new VideoFileWriter();
                    _timeLapseWriter.Open(filename + CodecExtension, w, h, Camobject.recorder.crf, Codec,
                                          CalcBitRate(Camobject.recorder.quality), Camobject.recorder.timelapseframerate);

                    success = true;
                    TimelapseStart = DateTime.Now;
                }
                catch (Exception ex)
                {
                    Log.Error("Camera " + Camobject.id, ex);
                    _timeLapseWriter = null;
                    Camobject.recorder.timelapse = 0;
                }
                finally
                {
                    Program.WriterMutex.ReleaseMutex();
                }
            }
            catch (Exception ex)
            {
                Log.Error("Camera " + Camobject.id, ex);
            }
            return success;
        }
예제 #55
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 outputDirectory = Path.GetDirectoryName(options.OutputFile);

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

            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 currentTime     = 0;
            var currentIndices  = Enumerable.Repeat(0, heatMapData.Count).ToArray();
            var heatMapDataDone = Enumerable.Repeat(false, heatMapData.Count).ToArray();

            var drawSpriteColorMatrix = new ColorMatrix();

            drawSpriteColorMatrix.Matrix33 = 1.0f / ((options.CompositeImageFactor == 0.0f) ? 256.0f : options.CompositeImageFactor);
            var drawSpriteImageAttributes = new ImageAttributes();

            drawSpriteImageAttributes.SetColorMatrix(drawSpriteColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            var spriteBounds = spriteImages.Select(si => new Rectangle(0, 0, si.Width, si.Height)).ToArray();

            // Fast track that just generates a final composite image.
            if (options.GenerateCompositeImage)
            {
                compositeImageGraphics.DrawImage(backgroundImage, Point.Empty);

                while (heatMapDataDone.Any(isDone => !isDone))
                {
                    // Write the new heat map data into the heat map buffer.
                    ++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))
                        {
                            var x = (heatMapDataInstance.X[currentIndex] - dataOrigin.X) * xScaling + mapOrigin.X - halfSpriteSize[spriteIndex].Width;
                            var y = (heatMapDataInstance.Y[currentIndex] - dataOrigin.Y) * yScaling + mapOrigin.Y - halfSpriteSize[spriteIndex].Height;

                            var spriteWidth  = spriteBounds[spriteIndex].Width;
                            var spriteHeight = spriteBounds[spriteIndex].Height;
                            var destPoints   = new[] { new PointF(x, y), new PointF(x + spriteWidth, y), new PointF(x, y + spriteHeight) };
                            heatMapBufferGraphics.DrawImage(spriteImages[spriteIndex], destPoints, spriteBounds[spriteIndex], GraphicsUnit.Pixel, drawSpriteImageAttributes);

                            ++currentIndex;
                        }

                        currentIndices[heatMapIndex] = currentIndex;

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

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

                        ++heatMapIndex;
                    }
                }

                compositeImageGraphics.DrawImage(heatMapBuffer, Point.Empty);
                compositeImage.Save(options.OutputFile);
                return;
            }

            var frameRate       = 25;
            var scaledFrameRate = options.TimeScale / frameRate;
            var timeDelta       = (int)(1000 * scaledFrameRate);

            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 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);

            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 - halfSpriteSize[spriteIndex].Width;
                            var y = (heatMapDataInstance.Y[currentIndex] - dataOrigin.Y) * yScaling + mapOrigin.Y - halfSpriteSize[spriteIndex].Height;

                            residualBufferGraphics.DrawImage(residualSpriteImage, x, y);
                            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();
        }
예제 #56
0
파일: CameraWindow.cs 프로젝트: vmail/main
        private void CloseTimeLapseWriter()
        {
            _timeLapseTotal = 0;
            _timeLapseFrameCount = 0;

            if (_timeLapseWriter == null)
                return;

            Program.WriterMutex.WaitOne();
            try
            {

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

            _timeLapseWriter = null;

            var fpath = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\"+TimeLapseVideoFileName+CodecExtension;

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

            var fi = new FileInfo(fpath);
            var dSeconds = Convert.ToInt32((DateTime.Now - TimelapseStart).TotalSeconds);

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

            ff.CreatedDateTicks = DateTime.Now.Ticks;
            ff.Filename = TimeLapseVideoFileName + CodecExtension;
            ff.MaxAlarm = 0;
            ff.SizeBytes = fi.Length;
            ff.DurationSeconds = dSeconds;
            ff.IsTimelapse = true;
            ff.AlertData = "";
            ff.TriggerLevel = 0;

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

                if (MainForm.MasterFileList.Count(p => p.Filename.EndsWith(TimeLapseVideoFileName + CodecExtension)) == 0)
                {
                    MainForm.MasterFileList.Add(new FilePreview(TimeLapseVideoFileName + CodecExtension, dSeconds, Camobject.name, DateTime.Now.Ticks, 2,
                                                                Camobject.id, ff.MaxAlarm));
                    if (TopLevelControl != null)
                    {
                        string thumbname = MainForm.Conf.MediaDirectory + "video\\" + Camobject.directory + "\\thumbs\\" +
                                           TimeLapseVideoFileName + ".jpg";
                        ((MainForm)TopLevelControl).AddPreviewControl(thumbname, fpath, dSeconds,
                                                                       DateTime.Now, true);
                    }
                }

                if (yt && CodecExtension==".mp4")
                {
                    YouTubeUploader.AddUpload(Camobject.id,fpath, Camobject.settings.youtube.@public, "",
                                              "");
                }
            }
        }
예제 #57
0
파일: CameraWindow.cs 프로젝트: vmail/main
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         Invalidate();
     }
     _toolTipCam.RemoveAll();
     _toolTipCam.Dispose();
     _timeLapseWriter = null;
     Writer = null;
     base.Dispose(disposing);
 }
예제 #58
0
파일: CameraWindow.cs 프로젝트: vmail/main
        public void StopSaving()
        {
            _stopWrite = true;
            if (_recordingThread != null)
                _recordingThread.Join(2000);
            if (_recordingThread!=null && _recordingThread.Join(0))
            {
                _recordingThread.Abort();
                _recordingThread.Join(2000);
                _stopWrite = false;
                if (Writer != null)
                {
                    Program.WriterMutex.WaitOne();
                    try
                    {

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

                _writerBuffer = null;
                _recordingTime = 0;
                var vc = VolumeControl;
                if (vc != null && vc.Micobject.settings.active)
                    vc.StopSaving();
            }
        }
예제 #59
-1
 private void Clear()
 {
     if (_reader != null) _reader.Close();
     if (_writer != null) _writer.Close();
     _reader = null;
     _writer = null;
 }
예제 #60
-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();
        }