-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebcamComponent.cs
1797 lines (1576 loc) · 73.9 KB
/
WebcamComponent.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Types;
using Grasshopper.GUI.Canvas;
using Rhino.Geometry;
using System.IO;
using System.Linq;
using System.Text;
namespace crft
{
// Custom double-buffered PictureBox with improved rendering and error handling
public class BufferedPictureBox : PictureBox
{
private bool _disposing = false;
public BufferedPictureBox()
{
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint, true);
// Force refresh whenever the Image property changes
this.ImageChanged += OnImageChanged;
}
private void OnImageChanged(object sender, EventArgs e)
{
// Don't invalidate if we're in the process of disposing
if (!_disposing && !this.IsDisposed && this.IsHandleCreated)
{
// Ensure control is refreshed when the image changes
try
{
this.Invalidate();
}
catch (Exception ex)
{
// Just log and continue if invalidate fails
Debug.WriteLine($"Error invalidating PictureBox: {ex.Message}");
}
}
}
// We need to add this event to detect image changes
private EventHandler _imageChanged;
public event EventHandler ImageChanged
{
add
{
// Safe event attachment
if (_imageChanged == null)
_imageChanged = value;
else
_imageChanged += value;
}
remove
{
// Safe event detachment
_imageChanged -= value;
}
}
// Override the Image property to raise the ImageChanged event
public new Image Image
{
get
{
// Safe getter
try
{
if (this.IsDisposed || _disposing)
return null;
return base.Image;
}
catch
{
return null; // Return null if any exception occurs
}
}
set
{
// Skip if disposing or disposed
if (_disposing || this.IsDisposed)
return;
try
{
// Store old image for proper disposal
Image oldImage = base.Image;
// Only update if different
if (oldImage != value)
{
// Set the new image first
base.Image = value;
// Notify event subscribers (if any)
if (!_disposing && !this.IsDisposed)
_imageChanged?.Invoke(this, EventArgs.Empty);
// Dispose old image if applicable
if (oldImage != null && oldImage != value)
{
try
{
oldImage.Dispose();
}
catch
{
// Ignore errors in disposal
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error setting PictureBox.Image: {ex.Message}");
}
}
}
// Override OnPaint to ensure the image is always repainted
protected override void OnPaint(PaintEventArgs pe)
{
if (this.IsDisposed || _disposing || pe == null || pe.Graphics == null)
return;
try
{
base.OnPaint(pe);
// Only attempt to draw if we have a valid image
if (this.Image != null)
{
// Force refresh of the entire control area
pe.Graphics.Clear(this.BackColor);
// Draw the image with high quality
pe.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pe.Graphics.DrawImage(this.Image, this.ClientRectangle);
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error in BufferedPictureBox.OnPaint: {ex.Message}");
}
}
// Override Dispose to ensure proper cleanup
protected override void Dispose(bool disposing)
{
// Set flag to avoid event raising during disposal
_disposing = true;
// Dispose the image first to avoid null reference issues
if (disposing)
{
try
{
if (base.Image != null)
{
Image oldImage = base.Image;
base.Image = null; // Clear the reference first
oldImage.Dispose(); // Then dispose the image
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error disposing PictureBox image: {ex.Message}");
}
}
// Call base implementation
base.Dispose(disposing);
}
}
public class WebcamComponent : GH_Component
{
internal Bitmap _currentFrame;
private bool _isRunning = false;
private bool _hasCapturedFrame = false;
internal int _deviceIndex = 0;
private CancellationTokenSource _cancellationSource;
private Task _captureTask;
private Process _avfProcess;
private string _tempImagePath;
private int _refreshInterval = 33; // ~30 fps
internal readonly object _lockObject = new object();
// Recording
private bool _isRecording = false;
private string _recordingPath = null;
private string _videoOutputPath = null;
private Process _ffmpegRecordProcess = null;
// Available cameras
internal List<string> _detectedCameras = new List<string>();
// Form
private WebcamViewer _webcamForm = null;
private bool _previousEnableState = false;
// For UI update throttling - using a shorter interval for better responsiveness
private DateTime _lastUIUpdate = DateTime.MinValue;
private const int UI_UPDATE_INTERVAL_MS = 16; // ~60fps for UI updates
private string _videoName = "webcam";
public WebcamComponent()
: base("Webcam", "Webcam",
"Captures and displays webcam video feed with recording capability",
"Display", "Preview")
{
// Use unique ID for temporary frame path
_tempImagePath = Path.Combine(Path.GetTempPath(),
"gh_webcam_" + Guid.NewGuid().ToString() + ".jpg");
// Use the same directory structure as SAM for output
// Format: /tmp/frames_{name}
_videoName = "webcam_" + DateTime.Now.ToString("yyyyMMdd_HHmmss");
// Use the same directory structure as SAM
_recordingPath = Path.Combine("/tmp", $"frames_{_videoName}");
// Generate a video file output path with .mp4 extension in the same location
_videoOutputPath = Path.Combine(_recordingPath, $"{_videoName}.mp4");
if (!Directory.Exists(_recordingPath))
{
Directory.CreateDirectory(_recordingPath);
}
}
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddBooleanParameter("Enable", "E", "Enable/disable webcam", GH_ParamAccess.item, false);
pManager.AddIntegerParameter("Device", "D", "Webcam device index", GH_ParamAccess.item, 1);
pManager.AddTextParameter("Name", "N", "Video name prefix (used for SAM compatibility)", GH_ParamAccess.item, "webcam");
// Optional parameter
pManager[2].Optional = true;
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddGenericParameter("Image", "I", "Current webcam frame", GH_ParamAccess.item);
pManager.AddTextParameter("VideoPath", "V", "Path to recorded video file (.mp4)", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
DiagnoseWebcamState();
bool enable = false;
int deviceIndex = 0;
string videoName = "";
if (!DA.GetData(0, ref enable)) return;
if (!DA.GetData(1, ref deviceIndex)) return;
// Get optional video name parameter for SAM compatibility
if (DA.GetData(2, ref videoName) && !string.IsNullOrEmpty(videoName))
{
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string previousName = _videoName;
// Clean up the name to be file-system friendly
string safeName = string.Join("_", videoName.Split(Path.GetInvalidFileNameChars()));
_videoName = safeName;
// Only update paths if name has changed
if (_videoName != previousName.Split('_')[0])
{
// Update recording and video paths using the new name
_recordingPath = Path.Combine("/tmp", $"frames_{_videoName}");
_videoOutputPath = Path.Combine(_recordingPath, $"{_videoName}_{timestamp}.mp4");
// Create directory if it doesn't exist
if (!Directory.Exists(_recordingPath))
{
try
{
Directory.CreateDirectory(_recordingPath);
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
$"Could not create recording directory: {ex.Message}");
}
}
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
$"Set video name to: {_videoName}");
}
}
// Only update state if the enable value actually changed
bool stateChanged = (enable != _previousEnableState);
_previousEnableState = enable;
// Scan for cameras when needed
if (_detectedCameras.Count == 0)
{
ScanForCameras();
}
// Store the device index immediately to ensure it's used correctly
_deviceIndex = deviceIndex;
// Report camera info even when not enabled
ReportCameraInfo(deviceIndex);
// Always respond to enable state
if (enable && !_isRunning)
{
// Delete previous recording if it exists
if (_videoOutputPath != null && File.Exists(_videoOutputPath))
{
try
{
File.Delete(_videoOutputPath);
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Deleted previous recording");
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
$"Could not delete previous recording: {ex.Message}");
}
}
StartCamera();
ShowWebcamWindow();
}
else if (!enable && _isRunning)
{
// If we're recording when disabled, stop the recording first
if (_isRecording)
{
try
{
// Call ToggleRecording to stop recording cleanly
ToggleRecording();
}
catch (Exception ex)
{
Debug.WriteLine($"Error stopping recording on disable: {ex.Message}");
}
}
// Stop the camera and close the window
StopCamera();
CloseWebcamWindow();
// Display the state change message
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
"Camera disabled. Video path is preserved for output.");
}
// Handle outputs based on component state
if (enable && _currentFrame != null)
{
try
{
Bitmap frameCopy;
lock (_lockObject)
{
frameCopy = (Bitmap)_currentFrame.Clone();
}
DA.SetData(0, frameCopy);
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Error: {ex.Message}");
}
}
else
{
// Send placeholder when disabled but only if the user is expecting output data
if (enable)
{
Bitmap placeholder = new Bitmap(320, 240);
using (Graphics g = Graphics.FromImage(placeholder))
{
g.Clear(Color.Black);
using (Font font = new Font("Arial", 10))
{
g.DrawString("Camera initializing...", font, Brushes.White, new PointF(80, 110));
}
}
DA.SetData(0, placeholder);
}
}
// Always output the video path if we have a valid recorded file, regardless of current enable state
if (_videoOutputPath != null && File.Exists(_videoOutputPath))
{
DA.SetData(1, _videoOutputPath);
}
}
private void ReportCameraInfo(int deviceIndex)
{
if (_detectedCameras.Count > 0)
{
if (deviceIndex >= 0 && deviceIndex < _detectedCameras.Count)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
$"Selected camera (index {deviceIndex}): {_detectedCameras[deviceIndex]}");
}
else
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
$"Device index {deviceIndex} is out of range. {_detectedCameras.Count} cameras detected.");
}
}
else
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No cameras detected.");
}
}
private void ScanForCameras()
{
_detectedCameras.Clear();
try
{
Process listDevices = new Process();
listDevices.StartInfo.FileName = "imagesnap";
listDevices.StartInfo.Arguments = "-l";
listDevices.StartInfo.UseShellExecute = false;
listDevices.StartInfo.RedirectStandardOutput = true;
listDevices.StartInfo.CreateNoWindow = true;
listDevices.Start();
string deviceList = listDevices.StandardOutput.ReadToEnd();
listDevices.WaitForExit();
// Log all available cameras for debugging
Debug.WriteLine("Available cameras from imagesnap -l:");
Debug.WriteLine(deviceList);
// Extract camera names from output
string[] lines = deviceList.Split('\n');
int cameraIndex = 0;
foreach (string line in lines)
{
if (line.StartsWith("=>"))
{
string cameraName = line.Substring(3).Trim();
_detectedCameras.Add(cameraName);
// Log each camera with its index
Debug.WriteLine($"Camera {cameraIndex}: {cameraName}");
cameraIndex++;
}
}
// Log the number of cameras detected
Debug.WriteLine($"Total cameras detected: {_detectedCameras.Count}");
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Error scanning for cameras: {ex.Message}");
}
}
private void ShowWebcamWindow()
{
try
{
if (Grasshopper.Instances.ActiveCanvas != null)
{
Grasshopper.Instances.ActiveCanvas.BeginInvoke((Action)(() =>
{
if (_webcamForm == null || _webcamForm.IsDisposed)
{
_webcamForm = new WebcamViewer(this);
_webcamForm.Show();
}
}));
}
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Error creating webcam window: {ex.Message}");
}
}
private void CloseWebcamWindow()
{
try
{
if (_webcamForm != null && !_webcamForm.IsDisposed)
{
if (Grasshopper.Instances.ActiveCanvas != null)
{
Grasshopper.Instances.ActiveCanvas.BeginInvoke((Action)(() =>
{
try
{
// Close the form and mark it as null
_webcamForm.Close();
_webcamForm.Dispose(); // Ensure full disposal
_webcamForm = null;
// Force a UI update to ensure Grasshopper updates
if (OnPingDocument() != null)
{
OnPingDocument().NewSolution(false);
}
Debug.WriteLine("Webcam window closed successfully");
}
catch (Exception ex)
{
Debug.WriteLine($"Error in UI thread closing webcam form: {ex.Message}");
}
}));
}
else
{
// If no canvas is available, try to close directly
_webcamForm.Close();
_webcamForm.Dispose();
_webcamForm = null;
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error closing webcam form: {ex.Message}");
}
}
// Creates the directory structure expected by the SAM component
private void CreateSAMCompatibleDirectories()
{
try
{
// Create main frames directory
if (!Directory.Exists(_recordingPath))
{
Directory.CreateDirectory(_recordingPath);
}
// Create segmentation_output/masks directory
string segmentationDir = Path.Combine(_recordingPath, "segmentation_output");
string masksDir = Path.Combine(segmentationDir, "masks");
if (!Directory.Exists(masksDir))
{
Directory.CreateDirectory(masksDir);
}
// Create masking_output directory
string maskingDir = Path.Combine(_recordingPath, "masking_output");
if (!Directory.Exists(maskingDir))
{
Directory.CreateDirectory(maskingDir);
}
// Create reconstruction directory
string reconstructionDir = Path.Combine(_recordingPath, "reconstruction");
if (!Directory.Exists(reconstructionDir))
{
Directory.CreateDirectory(reconstructionDir);
}
Debug.WriteLine($"Created SAM-compatible directory structure in {_recordingPath}");
}
catch (Exception ex)
{
Debug.WriteLine($"Error creating SAM-compatible directories: {ex.Message}");
}
}
private void DiagnoseWebcamState()
{
StringBuilder diagnostic = new StringBuilder();
diagnostic.AppendLine("=== Webcam Component Diagnostic ===");
diagnostic.AppendLine($"Is Running: {_isRunning}");
diagnostic.AppendLine($"Has Captured Frame: {_hasCapturedFrame}");
diagnostic.AppendLine($"Device Index: {_deviceIndex}");
diagnostic.AppendLine($"Current Frame Null: {_currentFrame == null}");
diagnostic.AppendLine($"Video Name: {_videoName}");
diagnostic.AppendLine($"Recording Path: {_recordingPath}");
diagnostic.AppendLine($"Video Output Path: {_videoOutputPath}");
if (_currentFrame != null)
{
diagnostic.AppendLine($"Frame Dimensions: {_currentFrame.Width}x{_currentFrame.Height}");
}
diagnostic.AppendLine($"Temp Image Path: {_tempImagePath}");
diagnostic.AppendLine($"Temp Image Exists: {File.Exists(_tempImagePath)}");
if (File.Exists(_tempImagePath))
{
FileInfo info = new FileInfo(_tempImagePath);
diagnostic.AppendLine($"Temp Image Size: {info.Length} bytes");
diagnostic.AppendLine($"Temp Image Last Write: {info.LastWriteTime}");
}
diagnostic.AppendLine($"Detected Cameras: {_detectedCameras.Count}");
for (int i = 0; i < _detectedCameras.Count; i++)
{
diagnostic.AppendLine($" {i}: {_detectedCameras[i]}");
}
Debug.WriteLine(diagnostic.ToString());
// Add summary to runtime messages
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
$"Diagnostics: Running={_isRunning}, HasFrame={_hasCapturedFrame}, " +
$"FrameExists={_currentFrame != null}, VideoPath={_videoOutputPath}");
}
private void StartCamera()
{
try
{
// Add debug message
Debug.WriteLine("Starting camera capture...");
// Generate a fresh temp path for this capture session
_tempImagePath = Path.Combine(Path.GetTempPath(),
"gh_webcam_" + Guid.NewGuid().ToString() + ".jpg");
Debug.WriteLine($"Using temp image path: {_tempImagePath}");
_cancellationSource = new CancellationTokenSource();
_captureTask = Task.Run(() => CaptureLoop(_cancellationSource.Token));
_isRunning = true;
Debug.WriteLine("Camera capture started successfully");
}
catch (Exception ex)
{
Debug.WriteLine($"Error in StartCamera: {ex.Message}");
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Error starting camera: {ex.Message}");
}
}
private void CaptureLoop(CancellationToken token)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
MacOSCaptureLoop(token);
}
else
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
"This component currently only supports macOS");
}
}
private bool CheckRequiredTools()
{
try
{
// Check for ffmpeg
Process ffmpegCheck = new Process();
ffmpegCheck.StartInfo.FileName = "which";
ffmpegCheck.StartInfo.Arguments = "ffmpeg";
ffmpegCheck.StartInfo.UseShellExecute = false;
ffmpegCheck.StartInfo.RedirectStandardOutput = true;
ffmpegCheck.StartInfo.CreateNoWindow = true;
ffmpegCheck.Start();
string ffmpegPath = ffmpegCheck.StandardOutput.ReadToEnd().Trim();
ffmpegCheck.WaitForExit();
// Check for imagesnap
Process imagesnapCheck = new Process();
imagesnapCheck.StartInfo.FileName = "which";
imagesnapCheck.StartInfo.Arguments = "imagesnap";
imagesnapCheck.StartInfo.UseShellExecute = false;
imagesnapCheck.StartInfo.RedirectStandardOutput = true;
imagesnapCheck.StartInfo.CreateNoWindow = true;
imagesnapCheck.Start();
string imagesnapPath = imagesnapCheck.StandardOutput.ReadToEnd().Trim();
imagesnapCheck.WaitForExit();
if (string.IsNullOrEmpty(ffmpegPath) || string.IsNullOrEmpty(imagesnapPath))
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
$"Required tools not found. ffmpeg: {!string.IsNullOrEmpty(ffmpegPath)}, imagesnap: {!string.IsNullOrEmpty(imagesnapPath)}");
return false;
}
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Required tools found.");
return true;
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Error checking tools: {ex.Message}");
return false;
}
}
private void MacOSCaptureLoop(CancellationToken token)
{
try
{
// Check required tools first
if (!CheckRequiredTools())
{
return;
}
if (_detectedCameras.Count == 0)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No webcams found");
return;
}
// Valid device index check
if (_deviceIndex < 0 || _deviceIndex >= _detectedCameras.Count)
{
// Try to find FaceTime camera
int builtInIndex = _detectedCameras
.FindIndex(n => n.ToLower().Contains("facetime"));
if (builtInIndex >= 0)
{
_deviceIndex = builtInIndex;
}
else
{
_deviceIndex = 0; // Default to first camera
}
}
string selectedCamera = _detectedCameras[_deviceIndex];
AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
$"Using camera {_deviceIndex}: {selectedCamera}");
// Set up faster refresh rate for better video smoothness
_refreshInterval = 16; // 60fps target
// Use ffmpeg in continuous streaming mode for better performance
Process streamProcess = null;
try
{
// Start a continuous stream with ffmpeg
streamProcess = new Process();
streamProcess.StartInfo.FileName = "ffmpeg";
// Target a specific resolution to avoid size issues
streamProcess.StartInfo.Arguments = $"-f avfoundation -framerate 30 " +
$"-video_size 640x480 " + // Set specific size constraint
$"-i \"{_deviceIndex}\" " +
$"-f image2 -update 1 -y \"{_tempImagePath}\"";
streamProcess.StartInfo.UseShellExecute = false;
streamProcess.StartInfo.CreateNoWindow = true;
streamProcess.StartInfo.RedirectStandardError = true;
Debug.WriteLine($"Starting FFMPEG with: {streamProcess.StartInfo.Arguments}");
// Start the streaming process
streamProcess.Start();
_avfProcess = streamProcess; // Store for cleanup later
// Short wait for process to start
Thread.Sleep(500);
// Verify initial success - this is important for live view
if (!File.Exists(_tempImagePath))
{
// If ffmpeg fails, try imagesnap as fallback
Process initialCapture = new Process();
initialCapture.StartInfo.FileName = "imagesnap";
initialCapture.StartInfo.Arguments = $"-d \"{selectedCamera}\" -w 640 -h 480 \"{_tempImagePath}\"";
initialCapture.StartInfo.UseShellExecute = false;
initialCapture.StartInfo.CreateNoWindow = true;
initialCapture.Start();
initialCapture.WaitForExit();
}
// Main capture loop - poll the continuously updated file
while (!token.IsCancellationRequested)
{
try
{
// Check if ffmpeg is still running
if (streamProcess.HasExited)
{
Debug.WriteLine("FFMPEG process exited unexpectedly, restarting...");
break;
}
// Process the current image if it exists
if (File.Exists(_tempImagePath))
{
var fileInfo = new FileInfo(_tempImagePath);
if (fileInfo.Length > 0)
{
// Use a short file access timeout to avoid blocking
try
{
using (FileStream stream = new FileStream(
_tempImagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Bitmap newFrame = new Bitmap(stream);
// Store current frame for component output
lock (_lockObject)
{
if (_currentFrame != null)
{
_currentFrame.Dispose();
}
_currentFrame = (Bitmap)newFrame.Clone();
_hasCapturedFrame = true;
}
// CRITICAL: Update UI directly with frame for live view
UpdateWebcamUI(newFrame);
// Update component at reduced rate
TimeSpan timeSinceLastUpdate = DateTime.Now - _lastUIUpdate;
if (timeSinceLastUpdate.TotalMilliseconds >= UI_UPDATE_INTERVAL_MS * 2) // Reduce component updates
{
_lastUIUpdate = DateTime.Now;
ExpireSolution(true);
}
}
}
catch (IOException)
{
// File might be being written to, just skip and try next time
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Frame processing error: {ex.Message}");
}
// Short sleep for high-frequency polling
Thread.Sleep(_refreshInterval);
}
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
$"Streaming error: {ex.Message}. Falling back to individual capture mode.");
// Fall back to individual captures
SnapshotCaptureLoop(token, selectedCamera);
}
finally
{
// Clean up the streaming process
if (streamProcess != null && !streamProcess.HasExited)
{
try { streamProcess.Kill(); } catch { /* ignore */ }
}
}
}
catch (Exception ex)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Capture loop error: {ex.Message}");
}
}
// Fallback method using imagesnap for individual frames
private void SnapshotCaptureLoop(CancellationToken token, string selectedCamera)
{
// Set more aggressive timing for snapshots to improve live view experience
int snapshotInterval = 50; // 20fps target for fallback mode
while (!token.IsCancellationRequested)
{
try
{
// Determine device argument
string deviceArg = $"-d \"{selectedCamera}\"";
// Add size constraint to prevent window sizing issues
string sizeArg = "-w 480 -h 360"; // Force smaller size for better performance
// Choose save path
string currentFramePath = _tempImagePath;
// Capture frame with size constraints
Process captureProcess = new Process();
captureProcess.StartInfo.FileName = "imagesnap";
captureProcess.StartInfo.Arguments = $"{deviceArg} {sizeArg} \"{currentFramePath}\"";
captureProcess.StartInfo.UseShellExecute = false;
captureProcess.StartInfo.CreateNoWindow = true;
// Start capture with timeout
captureProcess.Start();
bool completed = captureProcess.WaitForExit(500); // 500ms timeout
if (!completed)
{
// If it takes too long, kill the process and retry
try { captureProcess.Kill(); } catch { /* ignore */ }
Thread.Sleep(snapshotInterval);
continue;
}
// Process capture
if (File.Exists(currentFramePath))
{
var fileInfo = new FileInfo(currentFramePath);
if (fileInfo.Length > 0)
{
using (FileStream stream = new FileStream(
currentFramePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Bitmap newFrame = new Bitmap(stream);
// Store frame for component
lock (_lockObject)
{
if (_currentFrame != null)
{
_currentFrame.Dispose();
}
_currentFrame = (Bitmap)newFrame.Clone();
_hasCapturedFrame = true;
}
// CRITICAL: Always update the webcam preview window immediately
UpdateWebcamUI(newFrame);
// Only update Grasshopper component at controlled rate
TimeSpan timeSinceLastUpdate = DateTime.Now - _lastUIUpdate;
if (timeSinceLastUpdate.TotalMilliseconds >= UI_UPDATE_INTERVAL_MS * 2)
{
_lastUIUpdate = DateTime.Now;
ExpireSolution(true);
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Frame capture error: {ex.Message}");
}
// Use shorter sleep time for more responsive preview
Thread.Sleep(snapshotInterval);
}
}
private void UpdateWebcamUI(Bitmap frame)
{
try
{
// Make a defensive check to avoid null reference issues
if (frame == null)
{
Debug.WriteLine("UpdateWebcamUI: Skipping update due to null frame");
return;
}
if (_webcamForm == null)
{
Debug.WriteLine("UpdateWebcamUI: Skipping update due to null webcam form");
return;
}
if (_webcamForm.IsDisposed)
{
Debug.WriteLine("UpdateWebcamUI: Skipping update due to disposed webcam form");
return;
}
if (!_isRunning)
{
Debug.WriteLine("UpdateWebcamUI: Skipping update because camera is not running");
return;
}
// CRITICAL: Pass the frame directly to the UI without an intermediate clone
// The UpdateImage method will handle cloning and resizing
_webcamForm.UpdateImage(frame);
}
catch (Exception ex)