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(); }
//开始录像按钮响应函数 private void button_start_Click(object sender, EventArgs e) { int width = 640; //录制视频的宽度 int height = 480; //录制视频的高度 int fps = 9; //创建一个视频文件 String video_format = this.comboBox_videoecode.Text.Trim(); //获取选中的视频编码 if (this.videoSource.IsRunning && this.videoSourcePlayer.IsRunning) { if (-1 != video_format.IndexOf("MPEG")) { writer.Open("test.avi", width, height, fps, VideoCodec.MPEG4); } else if (-1 != video_format.IndexOf("WMV")) { writer.Open("test.wmv", width, height, fps, VideoCodec.WMV1); } else { writer.Open("test.mkv", width, height, fps, VideoCodec.Default); } } else { MessageBox.Show("没有视频源输入,无法录制视频。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } timer_count.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件; this.label5.Visible = true; this.label5.Text = "REC"; this.is_record_video = true; }
/// <summary> /// 开始录像 /// </summary> public void StartRecording() { if (RecordStatus == VideoRecordStatus.End) { //打开摄像头 Dispatcher.CurrentDispatcher.Invoke(() => { OpenCamera(); }); _writer = new VideoFileWriter(); if (Camera == CameraSource.Desktop) { //获取当前屏幕尺寸,开始录制 var rect = System.Windows.Forms.Screen.AllScreens.First().Bounds; _writer.Open(VideoFilePath, rect.Width, rect.Height); } else { if (Camera == CameraSource.LocalCamera && VideoDevices.Count <= 0) { return; } //等待摄像头准备完毕 while (Image == null) { Thread.Sleep(100); } //传入摄像头录制的图片尺寸,开始录制 _writer.Open(VideoFilePath, Image.PixelWidth, Image.PixelHeight, 120); } RecordStatus = VideoRecordStatus.Recording; } }
/// <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; int framerate = 1000 / screenStream.FrameInterval; int videoBitRate = 1200 * 1000; int audioBitRate = 320 * 1000; OutputPath = Path.Combine(main.CurrentDirectory, fileName); RecordingStartTime = DateTime.MinValue; videoWriter = new VideoFileWriter(); // 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.Format16Bit; device.SampleRate = Settings.Default.SampleRate; device.DesiredFrameSize = 2 * 4098; device.Start(); audioDevices.Add(device); } if (audioDevices.Count > 0) // Check if we need to record audio { audioDevice = new AudioSourceMixer(audioDevices); audioDevice.AudioSourceError += device_AudioSourceError; audioDevice.NewFrame += audioDevice_NewFrame; audioDevice.Start(); videoWriter.Open(OutputPath, width, height, framerate, VideoCodec.H264, videoBitRate, AudioCodec.MP3, audioBitRate, audioDevice.SampleRate, audioDevice.Channels); } else { videoWriter.Open(OutputPath, width, height, framerate, VideoCodec.H264, videoBitRate); } HasRecorded = false; IsRecording = true; }
/// <summary> /// 根据索引打开相机 /// </summary> /// <param name="index"></param> public void Start(int index = 0) { Camera = new VideoCaptureDevice(Devices[index].MonikerString); //通过索引找到指定摄像头 Camera.VideoResolution = Camera.VideoCapabilities[0]; ////配置录像参数(宽,高,帧率,比特率等参数) Camera.NewFrame += Camera_NewFrame; //设置回调,aforge会不断从这个回调推出图像数据 Camera.Start(); //打开摄像头 VideoOutPut.Open("E:/VIDEO.MP4", Camera.VideoResolution.FrameSize.Width, Camera.VideoResolution.FrameSize.Height, Camera.VideoResolution.AverageFrameRate, VideoCodec.MPEG4, Camera.VideoResolution.BitCount); //打开录像文件(如果没有则创建,如果有也会清空) }
public void SetUpRecordingEngine(double width, double height, string cameraName) { var dialog = new SaveFileDialog(); Width = width; Height = height; CameraName = cameraName; var proceededCameraName = cameraName.GetVideoFileName(); dialog.FileName = AppDomain.CurrentDomain.BaseDirectory + "SurvellianceMaterials\\" + $"{proceededCameraName}" + ".avi"; FilePath = dialog.FileName; dialog.AddExtension = true; _writer.Open(dialog.FileName, (int)Math.Round(Width, 0), (int)Math.Round(Height, 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(); }
public void Start(Rectangle position) { _position = position; //resolution can't be odd _position.Width = _position.Width % 2 == 0 ? _position.Width : _position.Width - 1; _position.Height = _position.Height % 2 == 0 ? _position.Height : _position.Height - 1; CreateInputDirectoryIfNotExists(); try { _watermarkImage = Image.FromFile(Properties.Settings.Default.WatermarkPath); } catch (FileNotFoundException e) { } _videoSource = new ScreenCaptureStream(_position); _videoSource.NewFrame += CaptureFrame; _videoSource.Start(); _videoWriter = new VideoFileWriter(); var inputFilePath = $"{Properties.Settings.Default.SaveToPath}\\{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.{FILE_CONTAINER}"; _videoWriter.Open(inputFilePath, _position.Width, _position.Height, FRAME_RATE, VideoCodec.H264, BIT_RATE); _isRecording = true; _firstFrameTime = null; }
private void StartRec(string path) { if (_isRecording == false) { this.SetScreenArea(); this.SetVisible(true); this._frameCount = 0; this.tb_SaveFolder.Text = path; string fullName = string.Format(@"{0}\{1}_{2}.avi", path, Environment.UserName.ToUpper(), DateTime.Now.ToString("d_MMM_yyyy_HH_mm_ssff")); // Save File option _writer.Open( fullName, this._width, this._height, ( int )nud_FPS.Value, ( VideoCodec )cb_VideoCodec.SelectedValue, ( int )( BitRate )this.cb_BitRate.SelectedValue); // Start main work this.StartRecord(); } }
/*END OF COPIED CODE BLOCK*/ private void CreateMovie(DateTime startDate, DateTime endDate) { int width = 320; int height = 240; var framRate = 200; using (var container = new ImageEntitiesContainer()) { //a LINQ-query for getting the desired images var query = from d in container.ImageSet where d.Date >= startDate && d.Date <= endDate select d; // create instance of video writer using (var vFWriter = new VideoFileWriter()) { // create new video file vFWriter.Open("nameOfMyVideoFile.avi", width, height, framRate, VideoCodec.Raw); var imageEntities = query.ToList(); //loop throught all images in the collection foreach (var imageEntity in imageEntities) { //what's the current image data? var imageByteArray = imageEntity.Data; var bmp = ToBitmap(imageByteArray); var bmpReduced = ReduceBitmap(bmp, width, height); vFWriter.WriteVideoFrame(bmpReduced); } vFWriter.Close(); } } }
private void recordPic_MouseClick(object sender, MouseEventArgs e) { if (imgRun) { if (recordStatus == ON) { recordStatus = COMPLETE; recordPic.Image = System.Drawing.Image.FromFile("button\\recordon.png"); } else if (recordStatus == OFF) { recordStatus = ON; if (!Directory.Exists(videoPath)) { Directory.CreateDirectory(videoPath); } writer = new VideoFileWriter(); ct = System.DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss.avi"); writer.Open(videoPath + "\\" + ct, 320, 240, 10, VideoCodec.MPEG4, 10000000); recordPic.Image = System.Drawing.Image.FromFile("button\\recordoff.png"); UpdateChatMsg("녹화시작\r\n"); } } else { MessageBox.Show("Error"); } }
private void SaveBitmaps(object state) { //using (var appScope = IsolatedStorageFile.GetUserStoreForApplication()) //{ // using (var stream = new IsolatedStorageFileStream("results.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, appScope)) // { // BinaryFormatter bin = new BinaryFormatter(); // bin.Serialize(stream, resultList); // } //} using (var writer = new VideoFileWriter()) { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); writer.Open(Path.Combine(path, "video.mp4"), 720, 576, 25, VideoCodec.H264); while (bitmaps != null) { if (bitmaps.Count == 0 && !isRecording) { bitmaps.Clear(); bitmaps = null; } else if (bitmaps.Count > 0 && isRecording) { var bitmap = bitmaps.Dequeue(); writer.WriteVideoFrame(bitmap); bitmap.Dispose(); } } writer.Close(); } }
public void CreateVideo() { Bitmap newFrame; string[] frames = Frames(); video = new Video(filename, img); int length = frames.Length; int width = video.Width; int height = video.Height; int framerate = video.FrameRate; int bitrate = video.BitRate; string filepath = @"D:\Files\Tugas Akhir\TA\Folder Video\stego1.avi"; int x = 0; while (File.Exists(filepath)) { x++; filepath = @"D:\Files\Tugas Akhir\TA\Folder Video\stego" + x + ".avi"; } string stegovideo = Path.Combine(filepath); writer.Open(stegovideo, width, height, reader.FrameRate, VideoCodec.Raw, bitrate); for (int i = 0; i < reader.FrameCount; i++) { newFrame = (Bitmap)Image.FromFile(frames[i]); writer.WriteVideoFrame(newFrame); newFrame.Dispose(); } }
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)); }
public void write_video_test() { var videoWriter = new VideoFileWriter(); int width = 800; int height = 600; int framerate = 24; string path = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "output.avi")); int videoBitRate = 1200 * 1000; videoWriter.Open(path, width, height, framerate, VideoCodec.H264, videoBitRate); Assert.AreEqual(videoBitRate, videoWriter.BitRate); 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)); }
public async void WriteVideo(string outputPath, int fps, byte[] fileBytes, byte[] filenameBytes, int boxSize, ProgressBar progressBar, RichTextBox storeInfoTextBox) { storeInfoTextBox.Text = "Storing file to a video..."; progressBar.Value = 1; int totalProgressCount = 0; var progress = new Progress <int>(progressIncrement => { totalProgressCount += progressIncrement; storeInfoTextBox.Text = totalProgressCount + "/" + fileBytes.Length + " bytes stored."; progressBar.Value = Math.Min(100, (int)(((float)totalProgressCount / (float)fileBytes.Length) * 100.0f)); }); VideoFileWriter writer = new VideoFileWriter(); writer.Open(outputPath, Width, Height, fps, VideoCodec.Default); Task drawImagesTask = Task.Factory.StartNew(() => { ImageDrawer filenameImageDrawer = new ImageDrawer(writer, filenameBytes); filenameImageDrawer.DrawImages(0, filenameBytes.Length, Width, Height, boxSize); ImageDrawer fileImageDrawer = new ImageDrawer(writer, fileBytes, progress); fileImageDrawer.DrawImages(0, fileBytes.Length, Width, Height, boxSize); }); await drawImagesTask; progressBar.Value = 100; storeInfoTextBox.Text = "Video was sucessfully stored!"; writer.Close(); }
/// <summary> /// Call to make video of world with time /// </summary> #pragma warning disable IDE0051 // Remove unused private members static void MakeVideo() #pragma warning restore IDE0051 // Remove unused private members { int frames = 6000; WorldRenderer worldRenderer = new WorldRenderer(); using (VideoFileWriter vFWriter = new VideoFileWriter()) { const int RENDERSIZE = World.World.WORLD_SIZE * 4; int framRate = 15; // create new video file vFWriter.Open("output.mp4", RENDERSIZE, RENDERSIZE, framRate, VideoCodec.MPEG4, 163840000); try { for (int i = 0; i < frames; i++) { Bitmap imageFrame = worldRenderer.Render(RENDERSIZE, RENDERSIZE, 4, false); Thread thread = new Thread(() => { vFWriter.WriteVideoFrame(imageFrame); imageFrame.Dispose(); }); thread.Start(); World.World.Instance.ProgressTime(); thread.Join(); } } catch (Exception e) { Trace.TraceError(e.ToString()); vFWriter.Close(); } } }
private void StartCapture() { if (movieMode) { if (this.InvokeRequired) { Invoke(new FormCallback(FormStateCapturing)); } else { FormStateCapturing(); } } filename = DateTime.Now.ToString(setting.toStringFormat) + "." + (mp4Mode ? ".Mp4" : imageFormat.ToString()); filepath = (mp4Mode && setting.doDeleteMp4File && setting.doUploadMp4FileToConvertToGif) ? Path.Combine(Path.GetTempPath(), filename) : Path.Combine(setting.saveLocalLocation, filename); if (mp4Mode) { videoWriter = new VideoFileWriter(); videoWriter.Open(filepath, width, height, 1000 / setting.milliseconds, VideoCodec.MPEG4); } else { imageMemoryStreams = new List <MemoryStream>(); } mode = Mode.Capturing; }
public static void Generate() { var reader = new VideoFileReader(); reader.Open(VideoPath + VideoName); var writer = new VideoFileWriter(); var numberOfFrames = (int)reader.FrameCount; Bitmap probeBitmap = reader.ReadVideoFrame(0); if (numberOfFrames > probeBitmap.Width) //if user want -> fit to original width { numberOfFrames = probeBitmap.Width; } writer.Open(VideoPath + "out.mp4", numberOfFrames, probeBitmap.Height, OutputFps, VideoCodec.H265); for (var x = 0; x < probeBitmap.Width; x++) { var convertedBitmap = new Bitmap(numberOfFrames, probeBitmap.Height); reader.Open(VideoPath + VideoName); for (var f = 0; f < numberOfFrames; f++) { var currentBitmap = reader.ReadVideoFrame(); for (var y = 0; y < probeBitmap.Height; y++) { convertedBitmap.SetPixel(f, y, currentBitmap.GetPixel(x, y)); } currentBitmap.Dispose(); } writer.WriteVideoFrame(convertedBitmap); convertedBitmap.Dispose(); } reader.Dispose(); writer.Close(); }
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(); }
private void btnGenerate_Click(object sender, EventArgs e) { g1.Clear(Color.White); for (int i = 0; i != width; i++) { if (g.simpleCanvas[i] == 1) { g1.DrawLine(Pens.Black, i, widthUp, i, widthDown); } } progressBar1.Maximum = (int)(frameRate * time); progressBar1.Value = progressBar1.Minimum = 0;//设置范围最小值 VideoFileWriter writer = new VideoFileWriter(); writer.Open(savePath, width, height, frameRate, VideoCodec.MPEG4); for (int i = 0; i != frameRate * time; i++) { Application.DoEvents(); writer.WriteVideoFrame(image1); this.progressBar1.Value = i; } this.progressBar1.Value = (int)(frameRate * time); writer.Close(); MessageBox.Show("Saved!!"); }
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(); }
public void GuardarVideo(string nombreArchivo) { if (framesBmp.Count != 0) { int width = 640; int height = 480; //FinGrabacion = DateTime.Now.Ticks; int Duracion = (int)(new TimeSpan(FinGrabacion - InicioGrabacion)).TotalSeconds; int framRate = this.framesBmp.Count / Duracion; Console.WriteLine($"Frames por segundo {framRate}"); // create instance of video writer using (var vFWriter = new VideoFileWriter()) { // create new video file vFWriter.Open($"C://Users//Public/Videos//{nombreArchivo}.avi", width, height, framRate, VideoCodec.Default); //loop throught all images in the collection foreach (var frame in framesBmp) { //what's the current image data? var bmpReduced = ReduceBitmap(frame, width, height); vFWriter.WriteVideoFrame(bmpReduced); } vFWriter.Close(); } //this.framesBmp = new List<Bitmap>(); } }
private void btnStart_Click(object sender, EventArgs e) { VideoCaptureDeviceForm videoSettings = new VideoCaptureDeviceForm(); var result = videoSettings.ShowDialog(this); if (result == System.Windows.Forms.DialogResult.Cancel) { return; } // create video source videoSource = videoSettings.VideoDevice; // set NewFrame event handler videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame); // start the video source videoSource.Start(); var fileName = string.Format(@"C:\temp\capv\{0}.flv", Guid.NewGuid().ToString()); FileInfo fInfo = new FileInfo(fileName); if (!Directory.Exists(fInfo.DirectoryName)) { Directory.CreateDirectory(fInfo.DirectoryName); } // create new video file writer.Open(fileName, 640, 480, 30, VideoCodec.FLV1); //start a timer to sync the video timeline timer = System.Diagnostics.Stopwatch.StartNew(); ShowCurrentStatus("running"); }
private void CaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap frame = eventArgs.Frame; lock (locker) { if (writerSet) { try { fileWriter.WriteVideoFrame(frame); } catch (Exception e) { } return; } DateTime dateTime = DateTime.Now; int width = frame.Width; int height = frame.Height; string name = dateTime.ToString("dd/MM/yyyy_hh-mm-ss"); Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Captures"); fileWriter.Open(Directory.GetCurrentDirectory() + "\\Captures\\" + name + ".avi", width, height); writerSet = true; } }
public static void createHeadHidedMovie(List <MyColorFrame> colorframes, List <MySkeletonFrame> skeletonframes, string path) { int width = 640; int height = 480; var framRate = 30; // create instance of video writer using (var vFWriter = new VideoFileWriter()) { // create new video file vFWriter.Open(path, width, height, framRate, VideoCodec.MPEG4, 2000000); for (int i = 0; i < colorframes.Count; i++) { if (skeletonframes.Count > i) { MyOverlayFrame ovframe = new MyOverlayFrame(skeletonframes.ElementAt(i), colorframes.ElementAt(i)); MemoryStream frame_memstream = ovframe.getHeadHidedMemoryStream(); System.Drawing.Bitmap imageEntity = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(frame_memstream); vFWriter.WriteVideoFrame(imageEntity); } } vFWriter.Close(); } }
private async void CreateDesktopRecordThread() { var targetDirectory = Path.Combine(Environment.CurrentDirectory, VideoAppAdapterHandler.OriginName); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } var fileName = Path.Combine(targetDirectory, $"摄像头查看_{VideoAppAdapterHandler.OriginName}_{DateTime.Now.ToString("yyyy-MM-dd hhmmss")}.avi"); var videoWriter = new VideoFileWriter(); videoWriter.Open(fileName, _videoFrameWidth, _videoFrameHeight, 10, VideoCodec.H264); do { if (!_videoFrame.IsNull()) { lock (this) videoWriter.WriteVideoFrame(_videoFrame); GC.Collect(); } await Task.Delay(100); //帧率控制,每秒10帧,防止写入过快 } while (!_stop); videoWriter.Close(); }
private void buttonRecordingCamOne_Click(object sender, EventArgs e) { if (cameraOne.IsRunning) { try { var dialog = new SaveFileDialog(); dialog.FileName = "Video1"; dialog.DefaultExt = ".avi"; dialog.AddExtension = true; var dialogresult = dialog.ShowDialog(); if (dialogresult != DialogResult.OK) { return; } firstFrameTime = null; isRecording1 = true; writer = new VideoFileWriter(); writer.Open(dialog.FileName, pbCam1.Image.Width, pbCam1.Image.Height, 30, VideoCodec.MPEG4); buttonRecordingCamOne.Enabled = false; buttonEndRecordingCamOne.Enabled = true; } catch { } } }
static void Main(string[] args) { var options = new PicToAsciiOptions() { FixedDimension = PicToAsciiOptions.Fix.Vertical, FixedSize = 54, SymbolAspectRatio = 7f / 12f, AsciiTable = PicToAsciiOptions.ASCIITABLE_SYMBOLIC_LIGHT }; pic2ascii = new PicToAscii(options); font = new Font("Lucida Console", 12, FontStyle.Regular, GraphicsUnit.Pixel); writer = new VideoFileWriter( ); writer.Open($"{MOV_PATH}~test.avi", width, height, 30, VideoCodec.MPEG4, 6000000); VideoFileSource videoSource = new VideoFileSource(MOVIESAMPLE_PATH); videoSource.NewFrame += VideoSource_NewFrame; videoSource.PlayingFinished += VideoSource_PlayingFinished; videoSource.Start(); Console.ReadLine(); if (videoSource.IsRunning) { videoSource.SignalToStop(); Console.ReadLine(); } }
public void captureStart(String filePath) { isRecording = true; this.filePath = filePath; vf = new VideoFileWriter(); startCaptureTime = DateTime.Now; filename = filePath + "/" + DateTime.Now.ToString("yyyy-MM-dd-") + DateTime.Now.Hour.ToString() + "H" + DateTime.Now.Minute.ToString() + "M" + DateTime.Now.Second.ToString() + "S_video.mp4"; int screenWidth = (int)System.Windows.SystemParameters.PrimaryScreenWidth * 2; int screenHeight = (int)System.Windows.SystemParameters.PrimaryScreenHeight * 2; bmpScreenShot = new Bitmap(screenWidth, screenHeight); //vf.Width = screenWidth; //vf.Height = screenHeight; //vf.FrameSize = 25; //vf.VideoCodec = VideoCodec.Default; //vf.BitRate = 1000000; //vf.Open(filename); vf.Open(filename, screenWidth, screenHeight, 25, VideoCodec.Default, 500000); myCaptureThread = new Thread(new ThreadStart(captureFunction)); myCaptureThread.Start(); }
private void CreateMovie(string videoName, string ImageName) { int width = 400; int height = 224; var framRate = 29; try { // create instance of video writer using (var vFWriter = new VideoFileWriter()) { // create new video file vFWriter.Open(videoName, width, height, framRate, VideoCodec.MPEG4); Bitmap map = new Bitmap(ImageName); //what's the current image data? // var bmp = ToBitmap(imageByte); var bmpReduced = ReduceBitmap(map, width, height); vFWriter.WriteVideoFrame(bmpReduced); vFWriter.Close(); } } catch (Exception e) { MessageBox.Show(e.Message); } }
private void btnStartVideo_Click(object sender, EventArgs e) { //创建一个视频文件 String picName = @GetVideoPath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss"); picName = picName + ".avi"; is_record_video = true; videoWriter = new VideoFileWriter(); if (GlobeVal.cam1.IsRunning) { videoWriter.Open(picName, GlobeVal.cam1.VideoCapabilities[0].FrameSize.Width, GlobeVal.cam1.VideoCapabilities[0].FrameSize.Height, fps, VideoCodec.MPEG4); } else { MessageBox.Show("没有视频源输入,无法录制视频。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } tick_num = 0; timer1.Enabled = true; ifCam1 = true; btnStartVideo.Enabled = false; btnStopVideo.Enabled = true; btnTakePic.Enabled = true; }
private void ImageStartRecording_MouseDown(object sender, MouseButtonEventArgs e) { if (comboBoxFrameRate.Text != "Select frequency") { string dateStempel = DateTime.Now.ToString("d MMM yyyy, hh.mm.ss"); videoPath = "C://Users//admin//Videos//Captures//" + dateStempel + ".mp4"; labelMessageSavingFile.Visibility = Visibility.Visible; videoFileWriter = new VideoFileWriter(); labelMessageSavingFile.Content = "Recording a screen in process"; timerLabelMessageSavingFile.Start(); timerLabelMessageSavingFile.Tick += TimerLabelMessageSavingFile_Tick; try { videoFileWriter.Open(videoPath, width, height, Int16.Parse(comboBoxFrameRate.SelectedItem.ToString()), VideoCodec.H265); //RecordAudio(); timerRecording.Interval = TimeSpan.FromSeconds(1 / Int64.Parse(comboBoxFrameRate.SelectedItem.ToString())); timerRecording.Tick += TimerRecording_Tick; //records video with demanded frequency timerRecording.Start(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } else { MessageBox.Show("Choose frame rate number", "Info", MessageBoxButton.OK, MessageBoxImage.Information); } }
static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); VideoFileReader reader = new VideoFileReader(); reader.Open(fileName); for (int i = 0; i < reader.FrameCount; i++) { read.Add(reader.ReadVideoFrame()); write.Add(NegativGeneralas(read[i])); } VideoFileWriter writer = new VideoFileWriter(); writer.Open("eredmeny_" + fileName, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, reader.BitRate); for (int i = 0; i < write.Count; i++) { writer.WriteVideoFrame(write[i]); } reader.Close(); writer.Close(); stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed); Console.ReadLine(); }
public void StartRecording(String filenameToSave) { videoWriter = new VideoFileWriter(); videoWriter.Open(filenameToSave, screenSize.Width, screenSize.Height, 25, VideoCodec.MPEG2); frameTimer.Start(); isRecording = true; StartEyeStream(); }
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; }
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); }
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; } }
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(); }
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(); }
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) { } }
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(); } } }
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; }
/// <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; int framerate = 1000 / screenStream.FrameInterval; int videoBitRate = 10 * 1000 * 1000; int audioBitRate = 320 * 1000; OutputPath = Path.Combine(main.CurrentDirectory, fileName); RecordingStartTime = DateTime.MinValue; videoWriter = new VideoFileWriter(); if (CaptureAudioDevice != null) { audioDevice = new AudioCaptureDevice(CaptureAudioDevice.Guid); audioDevice.Format = SampleFormat.Format16Bit; audioDevice.SampleRate = Settings.Default.SampleRate; audioDevice.DesiredFrameSize = 4096; audioDevice.NewFrame += audioDevice_NewFrame; audioDevice.Start(); videoWriter.Open(OutputPath, width, height, framerate, VideoCodec.H264, videoBitRate, AudioCodec.MP3, audioBitRate, audioDevice.SampleRate, 1); } else { videoWriter.Open(OutputPath, width, height, framerate, VideoCodec.H264, videoBitRate); } HasRecorded = false; IsRecording = true; }
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(); }
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 = ""; } } }
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); } }
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; }
public static void NewWriter(string filename, int w, int h) { writer = new VideoFileWriter(); // create new AVI file and open it writer.Open(filename, w, h,30, VideoCodec.Default , 5500000); }
static void Main(string[] args) { int width = 512; int height = width; int[] framerates = {60, 120, 180}; double preamblePostamble = 0.5; // seconds double movieLength = 60.0; // seconds foreach (var framerate in framerates) { VideoFileWriter writer = new VideoFileWriter(); VideoCodec codec = VideoCodec.WMV2; string fname = "test." + codec.ToString() + "." + framerate.ToString("000") + "Hz." + movieLength.ToString() + "sec." + width.ToString() + "." + height.ToString() + ".avi"; writer.Open(fname, width, height, framerate, codec); RectangleF rectText = new RectangleF(width / 2, 0, width / 2, height); RectangleF rectBlock = new RectangleF(0, 0, width / 2, height); Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); SolidBrush brushWhite = new SolidBrush(Color.White); SolidBrush brushBlack = new SolidBrush(Color.Black); var font = new Font("Tahoma", width <= 64 ? 8 : width <= 128 ? 12 : width <=256 ? 16 : 20); // Preamble for (int i = 0; i < (int)(framerate * preamblePostamble); i++) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Black); g.Flush(); } writer.WriteVideoFrame(bmp); } for (int i = 0; i < (int)(framerate * movieLength); i++) { bmp.SetPixel(i % width, i % height, Color.Blue); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Black); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawString(i.ToString(), font, Brushes.White, rectText); g.FillRectangle(((i & 1) == 0) ? brushWhite : brushBlack, rectBlock); g.Flush(); } writer.WriteVideoFrame(bmp); } // Postamble for (int i = 0; i < (int)(framerate * preamblePostamble); i++) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Black); g.Flush(); } writer.WriteVideoFrame(bmp); } writer.Close(); } }
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)); }
private void StartInternal( RecordSettings settings ) { try { _stopwatch = _stopwatch ?? new Stopwatch(); _stopwatch.Reset(); _stopwatch.Start(); StopWaiter.Reset(); if ( !Directory.Exists( settings.OutputPath ) ) Directory.CreateDirectory( settings.OutputPath ); while ( Recording ) { var outfile = Path.Combine( settings.OutputPath, DateTime.Now.ToFileTime().ToString() + ".avi" ); using (var outstream = new VideoFileWriter()) { var sourceRect = settings.CaptureRectangle; var w = sourceRect.Width; var h = sourceRect.Height; outstream.Open( outfile, w, h, settings.Fps, settings.Codec, settings.Bitrate ); var mpf = settings.SplitInterval * 60000 / settings.Interval; using ( var bmp = new Bitmap( w, h ) ) { using ( var gr = Graphics.FromImage( bmp ) ) { for ( var i = 0; (mpf==null||i < mpf) && Recording; i++ ) { try { gr.CopyFromScreen( sourceRect.X, sourceRect.Y, 0, 0, sourceRect.Size ); PreprocessFrame( gr, settings ); gr.Flush(); outstream.WriteVideoFrame( bmp ); settings.OnFrameWritten?.Invoke( _stopwatch.Elapsed ); } catch { } Thread.Sleep( settings.Interval ); } } } } } } catch(Exception ex) { //global } finally { _stopwatch?.Stop(); StopWaiter.Set(); } }
static void Main(string[] args) { var parserResults = Parser.Default.ParseArguments<Options>(args); if (parserResults.Tag == ParserResultType.NotParsed) { Console.WriteLine( new HelpText { AddDashesToOption = true } .AddPreOptionsLine("HeatMapVideoBuilder") .AddPreOptionsLine("") .AddOptions(parserResults).ToString()); return; } var options = (parserResults as Parsed<Options>).Value; bool hasArgumentErrors = false; Image backgroundImage = null; IList<Image> spriteImages = new List<Image>(); IList<SizeF> halfSpriteSize = new List<SizeF>(); Image residualSpriteImage = null; Point mapOrigin = Point.Empty; Size mapSize = Size.Empty; Point dataOrigin = Point.Empty; Size dataSize = Size.Empty; IList<HeatMapData> heatMapData = new List<HeatMapData>(); try { backgroundImage = Bitmap.FromFile(options.Background); } catch (Exception e) { Console.Error.WriteLine("Failed to load background image \"{0}\":\n\n{1}\n\n", options.Background, e); hasArgumentErrors = true; } try { mapOrigin = string.IsNullOrWhiteSpace(options.MapOrigin) ? Point.Empty : ParsePoint(options.MapOrigin); } catch (Exception e) { Console.Error.WriteLine("Failed to parse map origin \"{0}\":\n\n{1}\n\n", options.MapOrigin, e); hasArgumentErrors = true; } try { mapSize = string.IsNullOrWhiteSpace(options.MapSize) ? new Size(backgroundImage.Size.Width - mapOrigin.X, backgroundImage.Size.Height - mapOrigin.Y) : ParseSize(options.MapSize); } catch (Exception e) { Console.Error.WriteLine("Failed to parse map size \"{0}\":\n\n{1}\n\n", options.MapSize, e); hasArgumentErrors = true; } try { dataOrigin = string.IsNullOrWhiteSpace(options.DataOrigin) ? mapOrigin : ParsePoint(options.DataOrigin); } catch (Exception e) { Console.Error.WriteLine("Failed to parse data origin \"{0}\":\n\n{1}\n\n", options.DataOrigin, e); hasArgumentErrors = true; } try { dataSize = string.IsNullOrWhiteSpace(options.DataSize) ? mapSize : ParseSize(options.DataSize); } catch (Exception e) { Console.Error.WriteLine("Failed to parse data size \"{0}\":\n\n{1}\n\n", options.DataSize, e); hasArgumentErrors = true; } foreach (var spriteFile in options.SpriteFiles) { try { var sprite = Bitmap.FromFile(spriteFile); spriteImages.Add(sprite); halfSpriteSize.Add(new SizeF(sprite.Width / 2.0f, sprite.Height / 2.0f)); } catch (Exception e) { Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", spriteFile, e); hasArgumentErrors = true; } } if (string.IsNullOrWhiteSpace(options.ResidualSpriteFile)) { residualSpriteImage = spriteImages.First(); } else { try { residualSpriteImage = Bitmap.FromFile(options.ResidualSpriteFile); } catch (Exception e) { Console.Error.WriteLine("Failed to load heat map sprite image \"{0}\":\n\n{1}\n\n", options.ResidualSpriteFile, e); hasArgumentErrors = true; } } foreach (var inputFile in options.InputFile) { try { var json = File.ReadAllText(inputFile); var currentHeatMapData = JsonConvert.DeserializeObject<HeatMapData>(json); if ((currentHeatMapData.Timestamps == null)) { throw new Exception("Heat map data is missing a times array. This must be an array in a root object and contain time in milliseconds."); } if ((currentHeatMapData.X == null)) { throw new Exception("Heat map data is missing an x coordinate array. This must be an array in a root object."); } if ((currentHeatMapData.Y == null)) { throw new Exception("Heat map data is missing an y coordinate array. This must be an array in a root object."); } if ((currentHeatMapData.Timestamps.Count != currentHeatMapData.X.Count) || (currentHeatMapData.Timestamps.Count != currentHeatMapData.Y.Count)) { throw new Exception("Heat map data arrays are not equal length."); } heatMapData.Add(currentHeatMapData); } catch (Exception e) { Console.Error.WriteLine("Failed to load heat map data from \"{0}\":\n\n{1}\n\n", options.InputFile, e); hasArgumentErrors = true; } } if (hasArgumentErrors) { return; } var frameRate = 25; var scaledFrameRate = options.TimeScale / frameRate; var timeDelta = (int) (1000 * scaledFrameRate); var width = backgroundImage.Width; var height = backgroundImage.Height; var fullRect = new Rectangle(0, 0, width, height); var xScaling = mapSize.Width / (float) dataSize.Width; var yScaling = mapSize.Height / (float) dataSize.Height; var compositeImage = new Bitmap(width, height, PixelFormat.Format32bppArgb); var compositeImageGraphics = Graphics.FromImage(compositeImage); compositeImageGraphics.CompositingMode = CompositingMode.SourceOver; compositeImageGraphics.CompositingQuality = CompositingQuality.HighSpeed; var heatMapBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb); var heatMapBufferGraphics = Graphics.FromImage(heatMapBuffer); heatMapBufferGraphics.CompositingMode = CompositingMode.SourceOver; heatMapBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed; var residualBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb); var residualBufferGraphics = Graphics.FromImage(residualBuffer); residualBufferGraphics.CompositingMode = CompositingMode.SourceOver; residualBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed; var tempBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb); var tempBufferGraphics = Graphics.FromImage(tempBuffer); tempBufferGraphics.CompositingMode = CompositingMode.SourceOver; tempBufferGraphics.CompositingQuality = CompositingQuality.HighSpeed; var currentTime = 0; var currentIndices = Enumerable.Repeat(0, heatMapData.Count).ToArray(); var heatMapDataDone = Enumerable.Repeat(false, heatMapData.Count).ToArray(); var outputDirectory = Path.GetDirectoryName(options.OutputFile); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } var videoWriter = new VideoFileWriter(); if (options.BitRate == 0) { videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4); } else { videoWriter.Open(options.OutputFile, width, height, frameRate, VideoCodec.MPEG4, options.BitRate); } compositeImageGraphics.DrawImage(backgroundImage, Point.Empty); compositeImageGraphics.Save(); videoWriter.WriteVideoFrame(compositeImage); var alphaFade = frameRate / options.Duration; var heatMapFadeMatrix = new ColorMatrix(); heatMapFadeMatrix.Matrix33 = 0.95f;// alphaFade; var heatMapFadeImageAttributes = new ImageAttributes(); heatMapFadeImageAttributes.SetColorMatrix(heatMapFadeMatrix); var residualFadeMatrix = new ColorMatrix(); residualFadeMatrix.Matrix00 = 0.45f; residualFadeMatrix.Matrix01 = 0.45f; residualFadeMatrix.Matrix02 = 0.45f; residualFadeMatrix.Matrix10 = 0.45f; residualFadeMatrix.Matrix11 = 0.45f; residualFadeMatrix.Matrix12 = 0.45f; residualFadeMatrix.Matrix20 = 0.45f; residualFadeMatrix.Matrix21 = 0.45f; residualFadeMatrix.Matrix22 = 0.45f; var residualFadeImageAttributes = new ImageAttributes(); residualFadeImageAttributes.SetColorMatrix(residualFadeMatrix); var lastTime = 0u; var endPadding = 8 * options.Duration * frameRate; var font = new Font("Consolas", 10.0f); var pens = new[] { new Pen(Color.FromArgb(unchecked((int) 0x080000FF))), new Pen(Color.FromArgb(unchecked((int) 0x08FF0000))) }; residualBufferGraphics.CompositingMode = CompositingMode.SourceOver; while ((heatMapDataDone.Any(isDone => !isDone)) || (currentTime < (lastTime + endPadding))) { // Process the accumulation buffer. //tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height); //tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy; //tempBufferGraphics.DrawImage(residualBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, residualFadeImageAttributes); //tempBufferGraphics.Save(); //residualBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height); //residualBufferGraphics.CompositingMode = CompositingMode.SourceCopy; //residualBufferGraphics.DrawImage(tempBuffer, Point.Empty); //residualBufferGraphics.CompositingMode = CompositingMode.SourceOver; // Process the accumulation buffer. tempBufferGraphics.FillRectangle(Brushes.White, 0, 0, width, height); tempBufferGraphics.CompositingMode = CompositingMode.SourceCopy; tempBufferGraphics.DrawImage(heatMapBuffer, fullRect, 0, 0, width, height, GraphicsUnit.Pixel, heatMapFadeImageAttributes); tempBufferGraphics.Save(); heatMapBufferGraphics.FillRectangle(Brushes.Transparent, 0, 0, width, height); heatMapBufferGraphics.CompositingMode = CompositingMode.SourceCopy; heatMapBufferGraphics.DrawImage(tempBuffer, Point.Empty); heatMapBufferGraphics.CompositingMode = CompositingMode.SourceOver; // Write the new heat map data into the heat map buffer. for (var i = 0; i < timeDelta; ++i) { ++currentTime; var heatMapIndex = 0; var spriteIndex = 0; foreach (var heatMapDataInstance in heatMapData) { var currentIndex = currentIndices[heatMapIndex]; while ((currentIndex < heatMapDataInstance.Timestamps.Count) && (heatMapDataInstance.Timestamps[currentIndex] < currentTime)) { lastTime = heatMapDataInstance.Timestamps[currentIndex]; var x = (heatMapDataInstance.X[currentIndex] - dataOrigin.X) * xScaling + mapOrigin.X; var y = (heatMapDataInstance.Y[currentIndex] - dataOrigin.Y) * yScaling + mapOrigin.Y; //residualBufferGraphics.DrawImage(residualSpriteImage, x, y); residualBufferGraphics.DrawRectangle(pens[heatMapIndex], x -1, y -1, 3, 3); x -= halfSpriteSize[spriteIndex].Width; y -= -halfSpriteSize[spriteIndex].Height; heatMapBufferGraphics.DrawImage(spriteImages[spriteIndex], x, y); ++currentIndex; } currentIndices[heatMapIndex] = currentIndex; if (currentIndex >= heatMapDataInstance.Timestamps.Count) { heatMapDataDone[heatMapIndex] = true; } if (spriteIndex < spriteImages.Count - 1) { ++spriteIndex; } ++heatMapIndex; } } residualBufferGraphics.Save(); heatMapBufferGraphics.Save(); compositeImageGraphics.DrawImage(backgroundImage, Point.Empty); compositeImageGraphics.DrawImage(residualBuffer, Point.Empty); //compositeImageGraphics.DrawImage(heatMapBuffer, Point.Empty); var text = new TimeSpan(0, 0, 0, 0, currentTime).ToString(@"h\:mm\:ss"); for (var i = -1; i <= 1; ++i) { for (var j = -1; j <= 1; ++j) { compositeImageGraphics.DrawString(text, font, Brushes.Black, 2 + i, 2 + j); } } compositeImageGraphics.DrawString(text, font, Brushes.White, 2, 2); compositeImageGraphics.Save(); videoWriter.WriteVideoFrame(compositeImage); } videoWriter.Close(); }
private void saveshot() { string str = Url; string[] sAry = str.Split('.'); Url2 = sAry[0]; VideoFileReader reader = new VideoFileReader(); reader.Open(textBox1.Text); int co = 0; int end = int.Parse(reader.FrameCount.ToString()); int countFrameCut = 0; VideoFileWriter writerShort = new VideoFileWriter(); name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi"; videoname = Url2 + "_" + countFrameCut + ".avi"; writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000); for (int i = 0; i < end; i++) { Bitmap videoFrame = reader.ReadVideoFrame(); writerShort.WriteVideoFrame(videoFrame); videoFrame.Dispose(); if (i == Savei[countFrameCut]) { // cut short writerShort.Close(); keyFrame(); if (countCutFrame != countFrameCut) { name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(countFrameCut) + ".avi"; videoname = Url2 + "_" + countFrameCut + ".avi"; writerShort.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000); } countFrameCut++; } } writerShort.Close(); reader.Close(); /* for (int i = 0; i < Savei.Length; i++) { if (Savei[i] == 0) { if (co == 0) { Savei[i] = end; co = 1; } else { break; } } VideoFileWriter writer = new VideoFileWriter(); try { name = "..\\..\\..\\VideoName\\" + Url2 + "_" + Convert.ToString(i) + ".avi"; videoname = Url2 + "_" + i + ".avi"; writer.Open(name, reader.Width, reader.Height, reader.FrameRate, VideoCodec.MPEG4, 1000000); for (int j = 0; j < end; j++) { if (Savei[i] == j) { writer.Close(); break; } Bitmap videoFrame = reader.ReadVideoFrame(); writer.WriteVideoFrame(videoFrame); videoFrame.Dispose(); } } catch (Exception exception) { writer.Close(); } if (i == 0) { end = end - Savei[i]; } else { end = end - Math.Abs(Savei[i] - Savei[i - 1]); } keyFrame(); //string constr = ConfigurationManager.ConnectionStrings["Db"].ConnectionString; //SqlConnection con = new SqlConnection(constr); //con.Open(); //SqlCommand cmd = new SqlCommand("INSERT into CollectionShot (No,VideoName,PathVideoName,KeyFrame,HistrogrameVecter) " + // " VALUES ( (Select count(*) from CollectionShot ),'" + videoname + "','" + name + "' , '" + keyF + "','" + Vechist + "')", con); //cmd.ExecuteNonQuery(); //con.Close(); } reader.Close(); */ }
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."; } }
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; }
private void startRecordRgb() { startRecordingRgb = null; if (colorFrameDescription != null) { rgbStreamedFrame = 0; rgbWritenFrame = 0; Thread thread = new Thread(new ThreadStart(ColorRecordingFunction)); thread.Start(); try { //rgbWriter = new VideoWriter(tempRgbFileName, -1, FRAME_PER_SECOND, new Size(colorFrameDescription.Width / scaleVideo, colorFrameDescription.Height / scaleVideo), true); //Console.WriteLine("Finish create writer"); writer = new VideoFileWriter(); writer.Open(tempRgbFileName, colorFrameDescription.Width / scaleVideo, colorFrameDescription.Height / scaleVideo, fps, VideoCodec.MPEG4, quality); //writer.Open(tempRgbFileName, colorFrameDescription.Width / scaleVideo, colorFrameDescription.Height / scaleVideo); } catch (Exception e) { Console.WriteLine(e); } } }
private void OpenVideoWriters(string filePathBase, VideoCodec codec, int bitrate) { lock (lockObj) { if (Context.IsKinectActive) { // color videoWriterKinectColor = new VideoFileWriter(); int colorWidth = Context.ColorResizedWidth; int colorHeight = Context.ColorResizedHeight; if (Context.ProcessColorMapping) colorHeight *= 2; videoWriterKinectColor.Open(filePathBase + "_Color.avi", colorWidth, colorHeight, 30, codec, bitrate); //depth videoWriterKinectDepth = new VideoFileWriter(); int depthWidth = Context.DepthWidth; int depthHeight = Context.DepthHeight; if (Context.ProcessDepthMapping) depthHeight *= 2; videoWriterKinectDepth.Open(filePathBase + "_Depth.avi", depthWidth, depthHeight, 30, VideoCodec.Raw, bitrate); // body bufferBody = new List<float[]>(); } if (Context.IsPS3EyeActive) { int fps = Context.IsKinectActive ? 30 : Context.GUI.PS3EyePanel.FrameRate; // fps depends on devices !! videoWriterPS3Eye = new VideoFileWriter(); videoWriterPS3Eye.Open(filePathBase + "_PS3Eye.avi", 640, 480 * 2, fps, codec, bitrate); } currFilePathBase = filePathBase; } }
public void OpenVideo() { Writer = new VideoFileWriter(); Writer.Open(DateTime.Today.ToShortDateString() + ".avi", 1920, 1080, 1, VideoCodec.MPEG4); }
/// <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(); }