private void CloseWriter() { if (_isAsync) { try { _writerSemaphore.Wait(); _writer.Close(); _writer.Dispose(); Debug.WriteLine("Writer closed"); } catch (Exception ex) { Debug.WriteLine(ex); } finally { _writerSemaphore.Dispose(); } } else { _writer.Close(); _writer.Dispose(); } }
/// <summary> /// Stops recording. /// </summary> /// public void StopRecording() { if (!IsRecording) { return; } lock (syncObj) { IsRecording = false; if (videoWriter != null) { videoWriter.Close(); videoWriter.Dispose(); videoWriter = null; } if (audioDevice != null) { audioDevice.Stop(); audioDevice.Dispose(); audioDevice = null; } HasRecorded = true; } }
/// <summary> /// Stops recording. /// </summary> /// public void StopRecording() { if (!IsRecording) { return; } lock (syncObj) { IsRecording = false; if (videoWriter != null) { videoWriter.Close(); videoWriter.Dispose(); videoWriter = null; } if (audioMixer != null) { audioMixer.Stop(); foreach (IAudioSource source in audioMixer.Sources) { source.Stop(); source.Dispose(); } audioMixer.Dispose(); audioMixer = null; } HasRecorded = true; } }
private void button1_Click(object sender, EventArgs e) { if (button1.Text == "录像") { button1.Text = "停止"; var dialog = new SaveFileDialog(); dialog.FileName = "Video"; dialog.DefaultExt = ".avi"; dialog.AddExtension = true; DialogResult dialogresult = dialog.ShowDialog(); if (dialogresult != DialogResult.OK) { return; } _firstFrameTime = null; _writer = new VideoFileWriter(); _writer.Open(dialog.FileName, 1280, 720, 25, VideoCodec.MPEG4, 4000 * 1000); isNeedRecord = true; } else { isNeedRecord = false; button1.Text = "录像"; _writer.Close(); _writer.Dispose(); } }
private void StopVideo() { videoRequested = false; if (vfw != null) { // try to obtain lock, frame capture should always complete within 100 ms if (Monitor.TryEnter(lockobj, 100)) { try { vfw.Close(); vfw.Dispose(); } finally { videoState.Visible = false; // release the lock Monitor.Exit(lockobj); } } else { Console.Error.WriteLine("Unable to close video stream!"); } } }
private void StopRecording() { _recording = false; StopMindWaveConnection(); _writer.Close(); _writer.Dispose(); }
void StopRecording() { isRecording = false; writer.Close(); writer.Dispose(); buttonRecStart.Text = "Start Rec"; }
public void combineFiles() { try { // Process.Start("ffmpeg", "-i " + filename + " -i " + filenameAudio + " -c:v copy -c:a aac -strict experimental " + filenameCombined + ""); string FFmpegFilename; string[] text = File.ReadAllLines(MainWindow.executingDirectory + "\\Config\\FFMPEGLocation.txt"); FFmpegFilename = text[0]; process = new Process(); process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.FileName = FFmpegFilename; // process.StartInfo.FileName = @"C:\FFmpeg\bin\ffmpeg.exe"; process.StartInfo.Arguments = "-i " + filename + " -i " + filenameAudio + " -c:v copy -c:a aac -strict experimental " + filenameCombined + " -shortest"; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); process.WaitForExit(); vf.Dispose(); AudioSource.Dispose(); } catch (Exception xx) { int x = 0; x++; } }
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 VideoRecorder(string fileName, int width, int height) { CheckUnmanagedReference("avcodec-53.dll"); CheckUnmanagedReference("avformat-53.dll"); CheckUnmanagedReference("avutil-51.dll"); CheckUnmanagedReference("swscale-2.dll"); _fileName = Path.GetFullPath(fileName); _width = width; _height = height; _writer = new VideoFileWriter(); try { var ext = Path.GetExtension(_fileName).ToUpperInvariant(); var codec = GetCodec(ext); _writer.Open(_fileName, _width, _height, 50, codec, 200000000); _bitmap = new Bitmap(_width, _height, PixelFormat.Format32bppRgb); } catch { _writer.Dispose(); throw; } _threadRecord = new Thread(RecordProc); _threadRecord.Name = "Record"; _threadRecord.IsBackground = true; _threadRecord.Start(); }
public void Stop() { if (!_isRecording) { return; } lock (_syncObj) { _isRecording = false; _videoWriter.Close(); _videoWriter.Dispose(); if (_videoSource != null && _videoSource.IsRunning) { _videoSource.Stop(); _videoSource.NewFrame -= CaptureFrame; } if (_watermarkImage != null) { _watermarkImage.Dispose(); } } }
//Function triggered by button press of end record //This function uses the Aforge library to convery videoBitmapArr into video public void CreateVideo(object sender, RoutedEventArgs e) { refresh.Stop(); refresh.Dispose(); vFWriter.Close(); vFWriter.Dispose(); }
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); try { if (Camera != null) { isParsing = true; System.Threading.Tasks.Task.Factory.StartNew(() => { Camera.SignalToStop();//用其他的stop会长时间卡住,必须用这个 Camera = null; }); //停摄像头 if (!SettingHelp.Settings.桌面) { VideoOutPut.Close();//关闭录像文件,如果忘了不关闭,将会得到一个损坏的文件,无法播放 VideoOutPut.Dispose(); } if (Owner is MainWindow) { var main = Owner as MainWindow; if (main.Visibility != Visibility.Visible)//只录摄像头时,关闭摄像头录制回调主窗体的停录函数,进行音视频合成 { main.Visibility = Visibility.Visible; main.StopRecord(CloseCamera: false); } } } } catch { } }
public MediaRecorder(string fileName, int width, int height, int sampleRate) { CheckUnmanagedReference("avcodec-53.dll"); CheckUnmanagedReference("avformat-53.dll"); CheckUnmanagedReference("avutil-51.dll"); CheckUnmanagedReference("swscale-2.dll"); _fileNameMP4 = Path.GetFullPath(fileName); _fileNameWAV = Path.ChangeExtension(_fileNameMP4, ".wav"); _width = width; _height = height; _sampleRate = sampleRate; _writerMP4 = new VideoFileWriter(); _writerWAV = new WavSampleWriter(_fileNameWAV, sampleRate); try { var ext = Path.GetExtension(_fileNameMP4).ToUpperInvariant(); var codec = GetCodec(ext); _writerMP4.Open(_fileNameMP4, _width, _height, 50, codec, 200000000);//200000000); _bitmap = new Bitmap(_width, _height, PixelFormat.Format32bppRgb); } catch { _writerMP4.Dispose(); throw; } _threadRecord = new Thread(RecordProc); _threadRecord.Name = "Record"; _threadRecord.IsBackground = true; _threadRecord.Start(); }
/// <summary> /// 录制视频 /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public void Camera_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap img = (Bitmap)eventArgs.Frame.Clone(); if (_stopREC) { _stopREC = true; _createNewFile = true; //这里要设置为true表示要创建新文件 if (_videoWriter != null) { _videoWriter.Close(); } } else { //开始录像 if (_createNewFile) { if (_videoWriter != null) { _videoWriter.Close(); _videoWriter.Dispose(); } _videoWriter = new VideoFileWriter(); //这里必须是全路径,否则会默认保存到程序运行根据录下了 _videoWriter.Open(_videoFileFullPath, img.Width, img.Height, _frameRate, VideoCodec.FLV1); _createNewFile = false; } _videoWriter.WriteVideoFrame(img); } }
public void birlestir() { string FileName = "C://Users//BegovicTeam//Desktop//video sıkıştırma//frameBirlestir//birlesmis" + uzanti2; int width = 100; int height = 100; width = videoGenislik; height = videoYukseklik; VideoFileWriter writer = new VideoFileWriter(); writer.Open(FileName, width, height, this._VideoFPS, VideoCodec.MPEG4); Bitmap image = new Bitmap(width, height, PixelFormat.Format24bppRgb); DirectoryInfo dir = new DirectoryInfo(fbdFramePath.SelectedPath + "\\"); progressBar1.Maximum = FrameSayisi; progressBar1.Value = 0; foreach (Bitmap frame in videoFrameList) { image = frame; writer.WriteVideoFrame(image); progressBar1.Value += 1; } writer.Close(); writer.Dispose(); }
private async void OnStartSessionsOfRecording(object sender, EventArgs e) { int secondsInterval = (int)_intervalBetweenRecordingSessionsSecNumericUpDown.Value; int secondsWrite = (int)_recordingSessionTimeSecNumericUpDown.Value; butStop.Enabled = false; goButton.Enabled = false; _startButton.Enabled = false; if (_inputDeviceFrameReader == null) { OnSelectVideoInputDevice(sender, e); } while (_inputDeviceFrameReader != null) { _startButton.BackColor = Color.Red; await Task.Delay(secondsWrite * 1000); _inputDeviceFrameReader.Stop(); _outputVideoWriter.Close(); _outputVideoWriter.Dispose(); _startButton.BackColor = Color.Yellow; await Task.Delay(secondsInterval * 1000); OpenVideoWriting(); _inputDeviceFrameReader.Start(); } }
public void stopThread() { m_ThreadRunning = false; writeFrames(); m_MpegWriter.Close(); m_MpegWriter.Dispose(); clearFrames(); }
public void Dispose() { if (videoSource != null && videoSource.IsRunning) { videoSource.Stop(); } videoFileWriter?.Dispose(); }
private void StopRecording() { _writer.Close(); _writer.Dispose(); _recording = false; _logger.Info($"Stop video recording | {DateTime.Now}"); GC.Collect(); }
public void Dispose() { if (_videoSource != null && _videoSource.IsRunning) { _videoSource.SignalToStop(); } _writer?.Dispose(); }
public void Dispose() { if (VideoSource != null && VideoSource.IsRunning) { VideoSource.SignalToStop(); } writer?.Dispose(); }
// Méthode qui lit la vidéo et lance un algorithme de traitement public static void Initialisation(string path, List <Point> polygon_img) { polygon = polygon_img; _FileReader = new VideoFileReader(); Console.WriteLine("Motion Detector"); Console.WriteLine("Threshold level: " + _motionAlarmLevel); _motionDetector = new MotionDetector(new TwoFramesDifferenceDetector(), new MotionAreaHighlighting()); fileNameMovie = Path.GetFileNameWithoutExtension(path); if (File.Exists(path)) { if (!Directory.Exists("/MotionsVideo")) { Directory.CreateDirectory("/MotionsVideo"); } _FileReader.Open(path); //lecture de la vidéo image par image while (true) { using (Bitmap videoFrame = _FileReader.ReadVideoFrame()) { if (videoFrame == null) { break; } else { VideoSourcePlayer_NewFrame(videoFrame); } } } if (nbPicture >= 1) { Console.WriteLine(DateTime.Now + ": Video stopped"); _FileWriter.Close(); _FileWriter.Dispose(); nbPicture = 0; // TODO : la date réelle sur la video à mettre à la place de "00" XMLManager.CreateXMLMotion("/Movie/" + fileNameMovie + ".xml", _volgnr, DateTime.Now, DateTime.Now, "00", "00"); } _FileReader.Close(); _FileReader.Dispose(); } }
private void 录像ToolStripMenuItem_Click(object sender, EventArgs e) { if (!videoSourcePlayer1.IsRunning) { MessageBox.Show("摄像头未启动!", "视频录制", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } isShooting = !isShooting; if (isShooting) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Title = "选择视频保存路径"; saveDialog.FileName = "newVideo"; saveDialog.DefaultExt = "avi"; saveDialog.Filter = "视频文件(*.avi)|*.avi"; if (saveDialog.ShowDialog() == DialogResult.OK) { // NewVideo(saveDialog.FileName); string[] strs = saveDialog.FileName.Split('\\'); VideoFile = ""; for (int i = 0; i < strs.Length - 1; i++) { VideoFile += strs[i] + "\\"; } VideoFileName = saveDialog.FileName; videoSourcePlayer1.NewFrame += new AForge.Controls.VideoSourcePlayer.NewFrameHandler(sourcePlayer_NewFrame); 录像ToolStripMenuItem.Text = "结束录像"; } } else { videoSourcePlayer1.NewFrame -= new AForge.Controls.VideoSourcePlayer.NewFrameHandler(sourcePlayer_NewFrame); 录像ToolStripMenuItem.Text = "开始录像"; isBeginWriteVideo = false; if (videoWriter != null) { videoWriter.Close(); videoWriter.Dispose(); if (MessageBox.Show("录制成功,是否查看视频?", "", MessageBoxButtons.YesNo) == DialogResult.Yes) { System.Diagnostics.Process.Start(VideoFileName); } } } }
public void StopRecording() { lock (this) { _writer.Close(); _writer.Dispose(); this._recording = false; } }
public void StopRecording() { if (writer != null) { recording = false; writer.Close(); writer.Dispose(); } }
/// <summary> /// 结束录像 /// </summary> public void EndRecording() { if (RecordStatus == VideoRecordStatus.Recording) { StopCamera(); RecordStatus = VideoRecordStatus.End; _writer.Close(); _writer.Dispose(); } }
//关闭对象,保存到文件 public void CloseAndSaveMovieFile() { if (m_VFW != null) { m_VFW.Close(); //关闭对象 m_VFW.Dispose(); m_VFW = null; } }
private void StopVideoFileWriter() { _recording = false; _firstFrameTime.Stop(); _writer.Close(); _writer.Dispose(); MoveRecordedVideo(); }
private void BtnRecord_Click(object sender, EventArgs e) { if (BtnRecord.Text == "開始攝影") { if (textBox1.Text == "" || comboBoxAttachedCameras.Text == "" || comboBoxSupportedModes.Text == "") { MessageBox.Show("未選擇儲存路徑 or 未選擇相機 or 未選擇解析度"); } else { myLists.Clear(); Btnsetcamera.Enabled = false; BtnStart.Enabled = false; _writer = new VideoFileWriter(); _writer.Open(textBox1.Text, 350, 400, 30, VideoCodec.Raw); StopWatch.Restart(); StopWatch.Start(); _recording = true; BtnRecord.Text = "結束攝影"; label6.Text = "錄製中!"; label6.Visible = true; } } else { BtnRecord.Text = "開始攝影"; _recording = false; _writer.Close(); _writer.Dispose(); StopWatch.Stop(); using (StreamWriter outputFile = new StreamWriter(textBox1.Text.Substring(0, textBox1.Text.Length - 4) + ".txt")) { foreach (string line in myLists) { outputFile.WriteLine(line); } } label6.Text = "已儲存檔案,可安全關閉!"; textBox1.Text = ""; } }
public void stopCamera() { if (videoSource != null) { videoSource.SignalToStop(); } isRecording = false; fileWriter.Close(); fileWriter.Dispose(); fileWriter = null; }
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 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 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; }