ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
webcam_avfoundation.m
Go to the documentation of this file.
1
6
7#ifdef __APPLE__
8
9#import <AVFoundation/AVFoundation.h>
10#import <CoreMedia/CoreMedia.h>
11#import <CoreVideo/CoreVideo.h>
12#include <dispatch/dispatch.h>
13
15#include <ascii-chat/common.h>
17#include <options/options.h>
18
19// AVFoundation timeout configuration
20#define AVFOUNDATION_FRAME_TIMEOUT_NS 500000000 // 500ms timeout (adjustable for slow cameras)
21#define AVFOUNDATION_INIT_TIMEOUT_NS (3 * NSEC_PER_SEC) // 3 second timeout for initialization
22
23@interface WebcamCaptureDelegate : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate>
24@property(nonatomic, strong) dispatch_semaphore_t frameSemaphore;
25@property(nonatomic) CVPixelBufferRef currentFrame;
26@property(nonatomic) int frameWidth;
27@property(nonatomic) int frameHeight;
28@property(nonatomic) BOOL isActive;
29@property(nonatomic) BOOL hasNewFrame;
30@property(nonatomic, strong) NSLock *frameLock;
31@end
32
33@implementation WebcamCaptureDelegate
34
35- (instancetype)init {
36 self = [super init];
37 if (self) {
38 _frameSemaphore = dispatch_semaphore_create(0);
39 _currentFrame = NULL;
40 _frameWidth = 0;
41 _frameHeight = 0;
42 _isActive = YES;
43 _hasNewFrame = NO;
44 _frameLock = [[NSLock alloc] init];
45 }
46 return self;
47}
48
49- (void)dealloc {
50 [_frameLock lock];
51 if (_currentFrame) {
52 CVPixelBufferRelease(_currentFrame);
53 _currentFrame = NULL;
54 }
55 [_frameLock unlock];
56 [_frameLock release];
57 // Release the dispatch semaphore (required under MRC for dispatch objects)
58 if (_frameSemaphore) {
59 dispatch_release(_frameSemaphore);
60 _frameSemaphore = nil;
61 }
62 [super dealloc];
63}
64
65- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
66 // Check if delegate is still active to prevent callbacks during cleanup
67 if (!self.isActive) {
68 return;
69 }
70
71 CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
72 if (!pixelBuffer)
73 return;
74
75 [self.frameLock lock];
76
77 // Replace old frame with new one
78 CVPixelBufferRef oldFrame = self.currentFrame;
79 self.currentFrame = CVPixelBufferRetain(pixelBuffer);
80
81 if (oldFrame) {
82 CVPixelBufferRelease(oldFrame);
83 }
84
85 // Update dimensions
86 self.frameWidth = (int)CVPixelBufferGetWidth(pixelBuffer);
87 self.frameHeight = (int)CVPixelBufferGetHeight(pixelBuffer);
88
89 // Always signal semaphore when we get a new frame
90 self.hasNewFrame = YES;
91
92 [self.frameLock unlock];
93
94 dispatch_semaphore_signal(self.frameSemaphore);
95}
96
97- (void)deactivate {
98 self.isActive = NO;
99}
100
101@end
102
103struct webcam_context_t {
104 AVCaptureSession *session;
105 AVCaptureDeviceInput *input;
106 AVCaptureVideoDataOutput *output;
107 WebcamCaptureDelegate *delegate;
108 dispatch_queue_t queue;
109 int width;
110 int height;
111 double fps;
112 image_t *cached_frame; // Reusable frame buffer (allocated once, reused for each read)
113 OSType actual_pixel_format; // Track actual format from camera
114};
115
116// Helper function to get supported device types without deprecated ones
117static NSArray *getSupportedDeviceTypes(void) {
118 NSMutableArray *deviceTypes = [NSMutableArray array];
119
120 // Always add built-in camera
121 [deviceTypes addObject:AVCaptureDeviceTypeBuiltInWideAngleCamera];
122
123 // Add continuity camera support for macOS 13.0+
124 if (@available(macOS 13.0, *)) {
125 [deviceTypes addObject:AVCaptureDeviceTypeContinuityCamera];
126 }
127
128 // Add external camera support for macOS 14.0+
129 if (@available(macOS 14.0, *)) {
130 [deviceTypes addObject:AVCaptureDeviceTypeExternal];
131 }
132
133 return [[deviceTypes copy] autorelease];
134}
135
136asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index) {
137 webcam_context_t *context;
138 context = SAFE_MALLOC(sizeof(webcam_context_t), webcam_context_t *);
139 if (!context) {
140 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate webcam context");
141 }
142
143 memset(context, 0, sizeof(webcam_context_t));
144
145 @autoreleasepool {
146 // Create capture session
147 context->session = [[AVCaptureSession alloc] init];
148 if (!context->session) {
149 SAFE_FREE(context);
150 return SET_ERRNO(ERROR_WEBCAM, "Failed to create AVCaptureSession");
151 }
152
153 // Set session preset for quality
154 [context->session setSessionPreset:AVCaptureSessionPreset640x480];
155
156 // Find camera device using newer discovery session API with proper device types
157 AVCaptureDevice *device = nil;
158
159 NSArray *deviceTypes = getSupportedDeviceTypes();
160 AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceTypes
161 mediaType:AVMediaTypeVideo
162 position:AVCaptureDevicePositionUnspecified];
163
164 NSArray *devices = discoverySession.devices;
165
166 for (AVCaptureDevice *device in devices) {
167 NSUInteger idx = [devices indexOfObject:device];
168 log_debug("Found device %lu: %s (type: %s)", (unsigned long)idx, [device.localizedName UTF8String], [device.deviceType UTF8String]);
169 }
170
171 if (device_index < [devices count]) {
172 device = [devices objectAtIndex:device_index];
173 } else if ([devices count] > 0) {
174 device = [devices objectAtIndex:0]; // Use first available camera
175 }
176
177 // Fallback to default device if discovery session fails
178 if (!device) {
179 device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
180 }
181
182 if (!device) {
183 log_error("No camera device found at index %d", device_index);
184 [context->session release];
185 SAFE_FREE(context);
186 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
187 }
188
189 // Create device input
190 NSError *error = nil;
191 context->input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
192 if (!context->input || error) {
193 log_error("Failed to create device input: %s", [[error localizedDescription] UTF8String]);
194 [context->session release];
195 SAFE_FREE(context);
196 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
197 }
198
199 // Add input to session
200 if ([context->session canAddInput:context->input]) {
201 [context->session addInput:context->input];
202 } else {
203 log_error("Cannot add input to capture session");
204 [context->input release];
205 [context->session release];
206 SAFE_FREE(context);
207 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
208 }
209
210 // Create video output
211 context->output = [[AVCaptureVideoDataOutput alloc] init];
212 if (!context->output) {
213 log_error("Failed to create video output");
214 [context->input release];
215 [context->session release];
216 SAFE_FREE(context);
217 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
218 }
219
220 // Configure video output for RGB format with fallback support
221 // Try RGB24 first, then fallback to other common formats (UYVY, YUV420, etc)
222 NSArray *preferredFormats = @[
223 @(kCVPixelFormatType_24RGB), // Preferred: 24-bit RGB
224 @(kCVPixelFormatType_422YpCbCr8), // UYVY - very common
225 @(kCVPixelFormatType_420YpCbCr8Planar), // I420/YUV420 (3-plane)
226 @(kCVPixelFormatType_32BGRA), // 32-bit BGRA fallback
227 ];
228
229 NSDictionary *videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey : preferredFormats};
230 [context->output setVideoSettings:videoSettings];
231 log_debug("Configured AVFoundation video output with format priorities: RGB24, UYVY, I420, BGRA");
232
233 // Create delegate and queue
234 context->delegate = [[WebcamCaptureDelegate alloc] init];
235 context->queue = dispatch_queue_create("webcam_capture_queue", DISPATCH_QUEUE_SERIAL);
236
237 [context->output setSampleBufferDelegate:context->delegate queue:context->queue];
238
239 // Add output to session
240 if ([context->session canAddOutput:context->output]) {
241 [context->session addOutput:context->output];
242 } else {
243 log_error("Cannot add output to capture session");
244 [context->delegate release];
245 [context->output release];
246 [context->input release];
247 [context->session release];
248 dispatch_release(context->queue);
249 SAFE_FREE(context);
250 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
251 }
252
253 // Configure frame rate before starting session
254 log_debug("AVFoundation: Attempting to configure frame rate...");
255 AVCaptureDeviceInput *deviceInput = (AVCaptureDeviceInput *)context->input;
256 AVCaptureDevice *captureDevice = [deviceInput device];
257
258 if (captureDevice) {
259 log_debug("AVFoundation: Found device for FPS configuration");
260 NSError *lockError = nil;
261 uint32_t target_fps = (uint32_t)GET_OPTION(fps);
262 if (target_fps > 0 && [captureDevice lockForConfiguration:&lockError]) {
263 // Find the best format that supports the target FPS
264 AVCaptureDeviceFormat *bestFormat = nil;
265 AVFrameRateRange *bestRange = nil;
266
267 for (AVCaptureDeviceFormat *format in captureDevice.formats) {
268 for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
269 if (range.minFrameRate <= target_fps && range.maxFrameRate >= target_fps && (!bestFormat || range.maxFrameRate < bestRange.maxFrameRate)) {
270 bestFormat = format;
271 bestRange = range;
272 }
273 }
274 }
275
276 if (bestFormat && bestRange) {
277 @try {
278 captureDevice.activeFormat = bestFormat;
279 captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, (int32_t)target_fps);
280 captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, (int32_t)target_fps);
281 log_info("AVFoundation: Configured for %u FPS (device supports %.0f - %.0f FPS)", target_fps, bestRange.minFrameRate, bestRange.maxFrameRate);
282 } @catch (NSException *exception) {
283 log_warn("AVFoundation: Device rejected %u FPS configuration: %s; using its default frame rate", target_fps, [[exception reason] UTF8String]);
284 }
285 } else {
286 // Device doesn't support requested FPS - find the maximum FPS available
287 AVFrameRateRange *maxRange = nil;
288 AVCaptureDeviceFormat *maxFormat = nil;
289 for (AVCaptureDeviceFormat *format in captureDevice.formats) {
290 for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
291 if (!maxRange || range.maxFrameRate > maxRange.maxFrameRate) {
292 maxRange = range;
293 maxFormat = format;
294 }
295 }
296 }
297
298 if (maxFormat && maxRange) {
299 int actual_fps = (int)maxRange.maxFrameRate;
300 @try {
301 captureDevice.activeFormat = maxFormat;
302 captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, actual_fps);
303 captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, actual_fps);
304 log_warn("Device does not support %u FPS - using maximum available %.0f FPS", target_fps, maxRange.maxFrameRate);
305 } @catch (NSException *exception) {
306 log_warn("AVFoundation: Device rejected maximum frame rate configuration: %s; using its default frame rate", [[exception reason] UTF8String]);
307 }
308 } else {
309 log_warn("Could not determine device FPS capabilities, using device default");
310 }
311 }
312 [captureDevice unlockForConfiguration];
313 } else if (target_fps > 0) {
314 log_warn("Could not lock device for FPS configuration: %s", [[lockError localizedDescription] UTF8String]);
315 }
316 }
317
318 // Start the session
319 log_debug("Starting AVFoundation capture session...");
320 [context->session startRunning];
321 CMTime duration = captureDevice.activeVideoMinFrameDuration;
322 if (CMTIME_IS_NUMERIC(duration) && duration.value > 0 && duration.timescale > 0)
323 context->fps = (double)duration.timescale / duration.value;
324
325 // Check if session is actually running
326 if (![context->session isRunning]) {
327 log_error("Failed to start capture session - session not running");
328 [context->delegate release];
329 [context->output release];
330 [context->input release];
331 [context->session release];
332 dispatch_release(context->queue);
333 SAFE_FREE(context);
334 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
335 }
336 log_debug("Capture session started successfully");
337
338 // Wait for first frame to get dimensions
339 dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, AVFOUNDATION_INIT_TIMEOUT_NS);
340 if (dispatch_semaphore_wait(context->delegate.frameSemaphore, timeout) == 0) {
341 context->width = context->delegate.frameWidth;
342 context->height = context->delegate.frameHeight;
343 log_debug("AVFoundation webcam initialized: %dx%d, delegate isActive=%d", context->width, context->height, context->delegate.isActive);
344 } else {
345 log_error("Timeout waiting for first frame");
346 [context->session stopRunning];
347 [context->delegate release];
348 [context->output release];
349 [context->input release];
350 [context->session release];
351 dispatch_release(context->queue);
352 SAFE_FREE(context);
353 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam");
354 }
355 }
356
357 *ctx = context;
358 return ASCIICHAT_OK;
359}
360
369static BOOL convert_pixel_buffer_to_rgb24(CVPixelBufferRef pixelBuffer, rgb_pixel_t *dest_pixels, int width, int height) {
370 OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer);
371
372 if (CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) {
373 log_error("Failed to lock pixel buffer for format 0x%x", pixelFormat);
374 return FALSE;
375 }
376
377 uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(pixelBuffer);
378 size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
379
380 BOOL success = FALSE;
381
382 switch (pixelFormat) {
383 case kCVPixelFormatType_24RGB:
384 // Direct copy - already RGB24
385 for (int y = 0; y < height; y++) {
386 memcpy(&dest_pixels[y * width], &baseAddress[y * bytesPerRow], width * 3);
387 }
388 success = TRUE;
389 break;
390
391 case kCVPixelFormatType_32BGRA: {
392 // Convert BGRA to RGB (skip alpha channel)
393 for (int y = 0; y < height; y++) {
394 uint8_t *src = &baseAddress[y * bytesPerRow];
395 rgb_pixel_t *dst = &dest_pixels[y * width];
396 for (int x = 0; x < width; x++) {
397 dst[x].b = src[x * 4 + 0]; // B
398 dst[x].g = src[x * 4 + 1]; // G
399 dst[x].r = src[x * 4 + 2]; // R
400 // Skip alpha at src[x*4 + 3]
401 }
402 }
403 success = TRUE;
404 break;
405 }
406
407 case kCVPixelFormatType_422YpCbCr8: {
408 // UYVY format: U Y V Y (packed)
409 for (int y = 0; y < height; y++) {
410 uint8_t *src = &baseAddress[y * bytesPerRow];
411 rgb_pixel_t *dst = &dest_pixels[y * width];
412
413 for (int x = 0; x < width; x += 2) {
414 int u = src[x * 2 + 0] - 128;
415 int y0 = src[x * 2 + 1] - 16;
416 int v = src[x * 2 + 2] - 128;
417 int y1 = src[x * 2 + 3] - 16;
418
419 // Convert YUV to RGB
420 int r0 = (298 * y0 + 409 * v + 128) >> 8;
421 int g0 = (298 * y0 - 100 * u - 208 * v + 128) >> 8;
422 int b0 = (298 * y0 + 516 * u + 128) >> 8;
423
424 dst[x].r = (uint8_t)(r0 < 0 ? 0 : (r0 > 255 ? 255 : r0));
425 dst[x].g = (uint8_t)(g0 < 0 ? 0 : (g0 > 255 ? 255 : g0));
426 dst[x].b = (uint8_t)(b0 < 0 ? 0 : (b0 > 255 ? 255 : b0));
427
428 int r1 = (298 * y1 + 409 * v + 128) >> 8;
429 int g1 = (298 * y1 - 100 * u - 208 * v + 128) >> 8;
430 int b1 = (298 * y1 + 516 * u + 128) >> 8;
431
432 dst[x + 1].r = (uint8_t)(r1 < 0 ? 0 : (r1 > 255 ? 255 : r1));
433 dst[x + 1].g = (uint8_t)(g1 < 0 ? 0 : (g1 > 255 ? 255 : g1));
434 dst[x + 1].b = (uint8_t)(b1 < 0 ? 0 : (b1 > 255 ? 255 : b1));
435 }
436 }
437 success = TRUE;
438 break;
439 }
440
441 case kCVPixelFormatType_420YpCbCr8Planar: {
442 // I420 planar format
443 size_t plane_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
444 size_t plane_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
445
446 uint8_t *y_data = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
447 uint8_t *u_data = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
448 uint8_t *v_data = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 2);
449
450 size_t y_stride = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
451 size_t u_stride = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1);
452 size_t v_stride = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 2);
453
454 for (int y = 0; y < (int)plane_height; y++) {
455 rgb_pixel_t *dst = &dest_pixels[y * width];
456
457 for (int x = 0; x < (int)plane_width; x++) {
458 int y_val = y_data[y * y_stride + x] - 16;
459 int u_val = u_data[(y / 2) * u_stride + (x / 2)] - 128;
460 int v_val = v_data[(y / 2) * v_stride + (x / 2)] - 128;
461
462 int r = (298 * y_val + 409 * v_val + 128) >> 8;
463 int g = (298 * y_val - 100 * u_val - 208 * v_val + 128) >> 8;
464 int b = (298 * y_val + 516 * u_val + 128) >> 8;
465
466 dst[x].r = (uint8_t)(r < 0 ? 0 : (r > 255 ? 255 : r));
467 dst[x].g = (uint8_t)(g < 0 ? 0 : (g > 255 ? 255 : g));
468 dst[x].b = (uint8_t)(b < 0 ? 0 : (b > 255 ? 255 : b));
469 }
470 }
471 success = TRUE;
472 break;
473 }
474
475 default:
476 log_error("Unsupported pixel format from camera: 0x%x", pixelFormat);
477 break;
478 }
479
480 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
481
482 return success;
483}
484
486 (void)ctx;
487 // No-op on macOS - AVFoundation handles frame buffering internally
488}
489
491 if (!ctx)
492 return;
493
494 @autoreleasepool {
495 // First, deactivate delegate to reject new callbacks
496 if (ctx->delegate) {
497 [ctx->delegate deactivate];
498 }
499
500 // Remove delegate to prevent any further callbacks
501 if (ctx->output) {
502 [ctx->output setSampleBufferDelegate:nil queue:nil];
503 }
504
505 // Now stop the session
506 if (ctx->session && [ctx->session isRunning]) {
507 [ctx->session stopRunning];
508
509 // Wait longer for session to fully stop
510 usleep(200000); // 200ms - give more time for cleanup
511 }
512
513 // Clean up session and associated objects
514 if (ctx->session) {
515 if (ctx->input && [ctx->session.inputs containsObject:ctx->input]) {
516 [ctx->session removeInput:ctx->input];
517 }
518 if (ctx->output && [ctx->session.outputs containsObject:ctx->output]) {
519 [ctx->session removeOutput:ctx->output];
520 }
521 [ctx->session release];
522 ctx->session = nil;
523 }
524
525 if (ctx->input) {
526 [ctx->input release];
527 ctx->input = nil;
528 }
529
530 if (ctx->output) {
531 [ctx->output release];
532 ctx->output = nil;
533 }
534
535 if (ctx->delegate) {
536 [ctx->delegate release];
537 ctx->delegate = nil;
538 }
539
540 if (ctx->queue) {
541 dispatch_release(ctx->queue);
542 ctx->queue = nil;
543 }
544 }
545
546 // Free cached frame if it was allocated
547 if (ctx->cached_frame) {
548 image_destroy(ctx->cached_frame);
549 ctx->cached_frame = NULL;
550 }
551
552 SAFE_FREE(ctx);
553 // log_info("AVFoundation webcam cleaned up");
554}
555
557 if (!ctx || !ctx->delegate || !ctx->delegate.isActive)
558 return NULL;
559
560 @autoreleasepool {
561 // Wait for a frame (configurable timeout for different camera speeds)
562 dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, AVFOUNDATION_FRAME_TIMEOUT_NS);
563 if (dispatch_semaphore_wait(ctx->delegate.frameSemaphore, timeout) != 0) {
564 log_error("No webcam frame available within timeout: %0.2f seconds", AVFOUNDATION_FRAME_TIMEOUT_NS / NSEC_PER_SEC);
565 return NULL; // No frame available within timeout
566 }
567
568 // Reset the new frame flag so we can get the next semaphore signal
569 ctx->delegate.hasNewFrame = NO;
570
571 // Lock to safely access the current frame
572 [ctx->delegate.frameLock lock];
573
574 CVPixelBufferRef pixelBuffer = ctx->delegate.currentFrame;
575 if (!pixelBuffer) {
576 [ctx->delegate.frameLock unlock];
577 return NULL;
578 }
579
580 // Retain the buffer while we're using it
581 CVPixelBufferRetain(pixelBuffer);
582
583 [ctx->delegate.frameLock unlock];
584
585 // Lock the pixel buffer
586 if (CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) {
587 log_error("Failed to lock pixel buffer");
588 CVPixelBufferRelease(pixelBuffer);
589 return NULL;
590 }
591
592 // Get buffer info
593 size_t width = CVPixelBufferGetWidth(pixelBuffer);
594 size_t height = CVPixelBufferGetHeight(pixelBuffer);
595 uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(pixelBuffer);
596
597 if (!baseAddress) {
598 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
599 CVPixelBufferRelease(pixelBuffer); // Release our retained reference
600 log_error("Failed to get pixel buffer base address");
601 return NULL;
602 }
603
604 // Allocate or reuse cached frame (allocated once, reused for each call)
605 // This matches the documented API contract: "Subsequent calls reuse the same buffer"
606 if (!ctx->cached_frame) {
607 ctx->cached_frame = image_new((int)width, (int)height);
608 if (!ctx->cached_frame) {
609 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
610 CVPixelBufferRelease(pixelBuffer); // Release our retained reference
611 log_error("Failed to allocate image buffer");
612 return NULL;
613 }
614 }
615
616 image_t *img = ctx->cached_frame;
617
618 // Get actual pixel format from camera
619 OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer);
620 if (ctx->actual_pixel_format != pixelFormat) {
621 ctx->actual_pixel_format = pixelFormat;
622 const char *format_name = "Unknown";
623 switch (pixelFormat) {
624 case kCVPixelFormatType_24RGB:
625 format_name = "RGB24";
626 break;
627 case kCVPixelFormatType_32BGRA:
628 format_name = "BGRA32";
629 break;
630 case kCVPixelFormatType_422YpCbCr8:
631 format_name = "UYVY";
632 break;
633 case kCVPixelFormatType_420YpCbCr8Planar:
634 format_name = "I420";
635 break;
636 }
637 log_debug("Camera delivering pixels in %s format (0x%x)", format_name, pixelFormat);
638 }
639
640 // Convert pixel buffer to RGB24 (handles format conversion if needed)
641 if (!convert_pixel_buffer_to_rgb24(pixelBuffer, img->pixels, (int)width, (int)height)) {
642 CVPixelBufferRelease(pixelBuffer);
643 log_error("Failed to convert pixel buffer to RGB24");
644 return NULL;
645 }
646
647 // Release our retained reference
648 CVPixelBufferRelease(pixelBuffer);
649
650 return img;
651 }
652}
653
654double webcam_get_fps(webcam_context_t *ctx) {
655 return ctx ? ctx->fps : 0.0;
656}
657
659 if (!ctx || !width || !height)
660 return ERROR_INVALID_PARAM;
661
662 *width = ctx->width;
663 *height = ctx->height;
664 return ASCIICHAT_OK;
665}
666
667asciichat_error_t webcam_list_devices(webcam_device_info_t **out_devices, unsigned int *out_count) {
668 if (!out_devices || !out_count) {
669 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
670 }
671
672 *out_devices = NULL;
673 *out_count = 0;
674
675 @autoreleasepool {
676 // Get all video capture devices using the helper that handles deprecated types
677 NSArray *deviceTypes = getSupportedDeviceTypes();
678 AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceTypes
679 mediaType:AVMediaTypeVideo
680 position:AVCaptureDevicePositionUnspecified];
681
682 NSArray<AVCaptureDevice *> *av_devices = discoverySession.devices;
683 NSUInteger device_count = [av_devices count];
684
685 if (device_count == 0) {
686 // No devices found - not an error
687 return ASCIICHAT_OK;
688 }
689
690 // Allocate device array
691 webcam_device_info_t *devices = SAFE_CALLOC((size_t)device_count, sizeof(webcam_device_info_t), webcam_device_info_t *);
692 if (!devices) {
693 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate device info array");
694 }
695
696 // Populate device info
697 for (NSUInteger i = 0; i < device_count; i++) {
698 AVCaptureDevice *device = av_devices[i];
699 devices[i].index = (unsigned int)i;
700
701 const char *name = [[device localizedName] UTF8String];
702 if (name) {
703 SAFE_STRNCPY(devices[i].name, name, WEBCAM_DEVICE_NAME_MAX);
704 } else {
705 SAFE_STRNCPY(devices[i].name, "<Unknown>", WEBCAM_DEVICE_NAME_MAX);
706 }
707 }
708
709 *out_devices = devices;
710 *out_count = (unsigned int)device_count;
711 }
712
713 return ASCIICHAT_OK;
714}
715
717 SAFE_FREE(devices);
718}
719
720#endif // __APPLE__
#define SET_ERRNO(code,...)
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_WEBCAM
Definition error_codes.h:63
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define GET_OPTION(field)
Definition options.h:1339
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index)
Initialize webcam context for advanced operations.
asciichat_error_t webcam_list_devices(webcam_device_info_t **out_devices, unsigned int *out_count)
Enumerate available webcam devices.
void webcam_free_device_list(webcam_device_info_t *devices)
Free device list returned by webcam_list_devices().
void webcam_flush_context(webcam_context_t *ctx)
Flush/interrupt pending read operations on webcam context.
struct webcam_context_t webcam_context_t
Opaque webcam context structure.
Definition webcam.h:157
asciichat_error_t webcam_get_dimensions(webcam_context_t *ctx, int *width, int *height)
Get webcam frame dimensions.
#define WEBCAM_DEVICE_NAME_MAX
Maximum length of webcam device name.
Definition webcam.h:81
image_t * webcam_read_context(webcam_context_t *ctx)
Capture a frame from webcam context.
void webcam_cleanup_context(webcam_context_t *ctx)
Clean up webcam context and release resources.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
uint8_t b
Blue color component (0-255).
uint8_t g
Green color component (0-255).
uint8_t r
Red color component (0-255).
Webcam device information structure.
Definition webcam.h:93
unsigned int index
Device index (use with webcam_init_context).
Definition webcam.h:94
🖼️ Safe overflow-checked buffer size calculations for images and video frames
double webcam_get_fps(webcam_context_t *ctx)