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_v4l2.c
Go to the documentation of this file.
1
10
11#ifdef __linux__
12
13/* Storage capacities in elements; text buffers include the terminating NUL. */
14#define VIDEO_WEBCAM_LINUX_WEBCAM_V4L2_DEVICE_PATH_BUFFER_SIZE 32
15
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <fcntl.h>
20#include <unistd.h>
21#include <errno.h>
22#include <poll.h>
23#include <sys/mman.h>
24#include <sys/ioctl.h>
25#include <linux/videodev2.h>
26
27#include <libswscale/swscale.h>
28#include <libavutil/pixfmt.h>
29#include <libavcodec/avcodec.h>
30#include <libavformat/avformat.h>
31
34#include <ascii-chat/common.h>
35#include <options/options.h>
36#include <libplatform/filesystem.h>
37#include <libplatform/thread.h>
40#include <libplatform/lifecycle.h>
42#include <libplatform/atomic.h>
43#include <ascii-chat/log/io.h>
44
45#define WEBCAM_BUFFER_COUNT_DEFAULT 4
46#define WEBCAM_BUFFER_COUNT_MAX 8
47#define WEBCAM_DEVICE_INDEX_MAX 99
48#define WEBCAM_READ_RETRY_COUNT 3
49
50// Module-scope cached frame (freed in webcam_cleanup_context when webcam closes)
51static image_t *v4l2_cached_frame = NULL;
52
53typedef struct {
54 void *start;
55 size_t length;
56} webcam_buffer_t;
57
58struct webcam_context_t {
59 int fd;
60 int width;
61 int height;
62 double fps;
63 uint32_t pixelformat; // Actual pixel format from driver (RGB24, YUYV, NV12, I420, MJPEG, UYVY)
64 webcam_buffer_t *buffers;
65 int buffer_count;
66 image_t *cached_frame; // Reusable frame buffer (allocated once, reused for each read)
67 struct SwsContext *sws_ctx; // libswscale context for format conversion (if needed)
68 enum AVPixelFormat av_pixel_format; // FFmpeg pixel format for swscale
69 AVCodecContext *mjpeg_codec_ctx; // MJPEG JPEG decompression context (if using MJPEG format)
70 AVFrame *mjpeg_decoded_frame; // Decoded JPEG frame buffer
71
72 // Async camera reading (non-blocking)
73 lifecycle_t async_lifecycle; // Lifecycle state machine for camera thread
74 platform_thread_t camera_thread; // Background thread for continuous frame capture
75 atomic_ptr_t latest_frame; // Latest frame from camera (atomic swap)
76 image_t *async_cached_frame; // Last frame returned to caller (returned when no new frame available)
77};
78
85static void *webcam_camera_thread_func(void *arg) {
87
88 log_debug("Camera background thread started");
89
90 while (lifecycle_is_initialized(&ctx->async_lifecycle)) {
91 // Read frame (blocking on camera)
92 image_t *frame = webcam_read_context(ctx);
93
94 if (frame) {
95 // Copy the frame data (webcam_read_context returns ptr to module-level static buffer)
96 image_t *frame_copy = image_new_copy(frame);
97 if (frame_copy) {
98 // Atomic swap: replace latest_frame with new frame
99 image_t *old_frame = (image_t *)atomic_ptr_exchange(&ctx->latest_frame, frame_copy);
100 if (old_frame) {
101 image_destroy(old_frame);
102 }
103 }
104 }
105 }
106
107 log_debug("Camera background thread stopped");
108 return NULL;
109}
110
117static int webcam_v4l2_init_swscale(webcam_context_t *ctx, enum AVPixelFormat src_fmt) {
118 if (src_fmt == AV_PIX_FMT_NONE) {
119 log_error("Invalid pixel format for swscale");
120 return -1;
121 }
122
123 // Free existing context if present
124 if (ctx->sws_ctx) {
125 sws_freeContext(ctx->sws_ctx);
126 ctx->sws_ctx = NULL;
127 }
128
129 // Create new swscale context for conversion to RGB24
130 LOG_IO("swscaler", { ctx->sws_ctx = sws_getContext(ctx->width, ctx->height, src_fmt, ctx->width, ctx->height, AV_PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL); });
131
132 if (!ctx->sws_ctx) {
133 log_error("Failed to create swscale context for format conversion");
134 return -1;
135 }
136
137 ctx->av_pixel_format = src_fmt;
138 return 0;
139}
140
149static int webcam_v4l2_init_mjpeg_decoder(webcam_context_t *ctx) {
150 // Find JPEG codec
151 const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);
152 if (!codec) {
153 log_error("MJPEG codec not found in FFmpeg");
154 return -1;
155 }
156
157 // Allocate codec context
158 ctx->mjpeg_codec_ctx = avcodec_alloc_context3(codec);
159 if (!ctx->mjpeg_codec_ctx) {
160 log_error("Failed to allocate MJPEG codec context");
161 return -1;
162 }
163
164 // Set expected frame dimensions (V4L2 tells us these)
165 ctx->mjpeg_codec_ctx->width = ctx->width;
166 ctx->mjpeg_codec_ctx->height = ctx->height;
167
168 // Open codec
169 if (avcodec_open2(ctx->mjpeg_codec_ctx, codec, NULL) < 0) {
170 log_error("Failed to open MJPEG codec");
171 avcodec_free_context(&ctx->mjpeg_codec_ctx);
172 return -1;
173 }
174
175 // Allocate frame for decoded output
176 ctx->mjpeg_decoded_frame = av_frame_alloc();
177 if (!ctx->mjpeg_decoded_frame) {
178 log_error("Failed to allocate MJPEG decoded frame");
179 avcodec_free_context(&ctx->mjpeg_codec_ctx);
180 return -1;
181 }
182
183 // Initialize swscale for converting decoded MJPEG (typically YUV420P) to RGB24
184 if (webcam_v4l2_init_swscale(ctx, AV_PIX_FMT_YUV420P) != 0) {
185 log_error("Failed to initialize swscale for MJPEG decoded frames");
186 av_frame_free(&ctx->mjpeg_decoded_frame);
187 avcodec_free_context(&ctx->mjpeg_codec_ctx);
188 return -1;
189 }
190
191 return 0;
192}
193
212static int webcam_v4l2_set_format(webcam_context_t *ctx, int width, int height) {
213 struct v4l2_format fmt = {0};
214 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
215 fmt.fmt.pix.width = width;
216 fmt.fmt.pix.height = height;
217 fmt.fmt.pix.field = V4L2_FIELD_ANY;
218
219 // Try RGB24 first (ideal - no conversion needed)
220 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
221 if (ioctl(ctx->fd, VIDIOC_S_FMT, &fmt) == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24) {
222 ctx->pixelformat = V4L2_PIX_FMT_RGB24;
223 ctx->width = fmt.fmt.pix.width;
224 ctx->height = fmt.fmt.pix.height;
225 ctx->sws_ctx = NULL;
226 log_debug("V4L2 format set to RGB24 %dx%d", ctx->width, ctx->height);
227 return 0;
228 }
229
230 // Try NV12 (Raspberry Pi cameras, modern USB cameras)
231 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_NV12;
232 if (ioctl(ctx->fd, VIDIOC_S_FMT, &fmt) == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12) {
233 ctx->pixelformat = V4L2_PIX_FMT_NV12;
234 ctx->width = fmt.fmt.pix.width;
235 ctx->height = fmt.fmt.pix.height;
236 if (webcam_v4l2_init_swscale(ctx, AV_PIX_FMT_NV12) == 0) {
237 log_debug("V4L2 format set to NV12 %dx%d (will convert to RGB with swscale)", ctx->width, ctx->height);
238 return 0;
239 }
240 }
241
242 // Try I420 (planar YUV)
243 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
244 if (ioctl(ctx->fd, VIDIOC_S_FMT, &fmt) == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) {
245 ctx->pixelformat = V4L2_PIX_FMT_YUV420;
246 ctx->width = fmt.fmt.pix.width;
247 ctx->height = fmt.fmt.pix.height;
248 if (webcam_v4l2_init_swscale(ctx, AV_PIX_FMT_YUV420P) == 0) {
249 log_debug("V4L2 format set to I420 %dx%d (will convert to RGB with swscale)", ctx->width, ctx->height);
250 return 0;
251 }
252 }
253
254 // Try MJPEG (Motion-JPEG - compressed format supporting 60fps on many cameras)
255 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
256 int mjpeg_ret = ioctl(ctx->fd, VIDIOC_S_FMT, &fmt);
257 if (mjpeg_ret == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {
258 ctx->pixelformat = V4L2_PIX_FMT_MJPEG;
259 ctx->width = fmt.fmt.pix.width;
260 ctx->height = fmt.fmt.pix.height;
261 if (webcam_v4l2_init_mjpeg_decoder(ctx) == 0) {
262 log_debug("V4L2 format set to MJPEG %dx%d (60fps compressed - will decompress JPEG with FFmpeg)", ctx->width, ctx->height);
263 log_info("MJPEG format selected: pixelformat=0x%x", ctx->pixelformat);
264 return 0;
265 } else {
266 log_warn("MJPEG decoder init failed, trying next format");
267 }
268 } else {
269 log_debug("MJPEG format not supported (ioctl returned %d, got format 0x%x)", mjpeg_ret, fmt.fmt.pix.pixelformat);
270 }
271
272 // Try YUYV (YUV 4:2:2 - most webcams support this)
273 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
274 if (ioctl(ctx->fd, VIDIOC_S_FMT, &fmt) == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) {
275 ctx->pixelformat = V4L2_PIX_FMT_YUYV;
276 ctx->width = fmt.fmt.pix.width;
277 ctx->height = fmt.fmt.pix.height;
278 if (webcam_v4l2_init_swscale(ctx, AV_PIX_FMT_YUYV422) == 0) {
279 log_debug("V4L2 format set to YUYV %dx%d (will convert to RGB with swscale)", ctx->width, ctx->height);
280 return 0;
281 }
282 }
283
284 // Try UYVY (YUV 4:2:2 variant)
285 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
286 if (ioctl(ctx->fd, VIDIOC_S_FMT, &fmt) == 0 && fmt.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) {
287 ctx->pixelformat = V4L2_PIX_FMT_UYVY;
288 ctx->width = fmt.fmt.pix.width;
289 ctx->height = fmt.fmt.pix.height;
290 if (webcam_v4l2_init_swscale(ctx, AV_PIX_FMT_UYVY422) == 0) {
291 log_debug("V4L2 format set to UYVY %dx%d (will convert to RGB with swscale)", ctx->width, ctx->height);
292 return 0;
293 }
294 }
295
296 // Save errno before log_error() clears it
297 int saved_errno = errno;
298
299 // Check if format setting failed because device is busy
300 if (saved_errno == EBUSY) {
301 log_error("Failed to set V4L2 format: device is busy (another application is using it)");
302 errno = saved_errno;
303 return -1;
304 }
305
306 log_error("Failed to set V4L2 format: device supports none of (RGB24, NV12, I420, YUYV, UYVY) (errno=%d: %s)", saved_errno, SAFE_STRERROR(saved_errno));
307 errno = saved_errno;
308 return -1;
309}
310
311static int webcam_v4l2_init_buffers(webcam_context_t *ctx) {
312 struct v4l2_requestbuffers req = {0};
313 req.count = WEBCAM_BUFFER_COUNT_DEFAULT;
314 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
315 req.memory = V4L2_MEMORY_MMAP;
316
317 if (ioctl(ctx->fd, VIDIOC_REQBUFS, &req) == -1) {
318 log_error("Failed to request V4L2 buffers: %s", SAFE_STRERROR(errno));
319 return -1;
320 }
321
322 if (req.count < 2) {
323 log_error("Insufficient buffer memory");
324 return -1;
325 }
326
327 // Ensure we don't exceed our maximum buffer count
328 if (req.count > WEBCAM_BUFFER_COUNT_MAX) {
329 log_warn("Driver requested %d buffers, limiting to %d", req.count, WEBCAM_BUFFER_COUNT_MAX);
330 req.count = WEBCAM_BUFFER_COUNT_MAX;
331 }
332
333 ctx->buffer_count = req.count;
334
335 // Allocate buffer array
336 ctx->buffers = SAFE_MALLOC(sizeof(webcam_buffer_t) * ctx->buffer_count, webcam_buffer_t *);
337 if (!ctx->buffers) {
338 log_error("Failed to allocate buffer array");
339 return -1;
340 }
341
342 // Initialize buffer array
343 memset(ctx->buffers, 0, sizeof(webcam_buffer_t) * ctx->buffer_count);
344
345 for (int i = 0; i < ctx->buffer_count; i++) {
346 struct v4l2_buffer buf = {0};
347 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
348 buf.memory = V4L2_MEMORY_MMAP;
349 buf.index = i;
350
351 if (ioctl(ctx->fd, VIDIOC_QUERYBUF, &buf) == -1) {
352 log_error("Failed to query buffer %d: %s", i, SAFE_STRERROR(errno));
353 return -1;
354 }
355
356 ctx->buffers[i].length = buf.length;
357 ctx->buffers[i].start = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, ctx->fd, buf.m.offset);
358
359 if (ctx->buffers[i].start == MAP_FAILED) {
360 log_error("Failed to mmap buffer %d: %s", i, SAFE_STRERROR(errno));
361 return -1;
362 }
363 }
364
365 return 0;
366}
367
368static int webcam_v4l2_start_streaming(webcam_context_t *ctx) {
369 // Queue all buffers
370 for (int i = 0; i < ctx->buffer_count; i++) {
371 struct v4l2_buffer buf = {0};
372 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
373 buf.memory = V4L2_MEMORY_MMAP;
374 buf.index = i;
375
376 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
377 log_error("Failed to queue buffer %d: %s", i, SAFE_STRERROR(errno));
378 return -1;
379 }
380 }
381
382 enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
383 if (ioctl(ctx->fd, VIDIOC_STREAMON, &type) == -1) {
384 log_error("Failed to start V4L2 streaming: %s", SAFE_STRERROR(errno));
385 return -1;
386 }
387
388 log_dev("V4L2 streaming started");
389 return 0;
390}
391
392asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index) {
393 webcam_context_t *context;
394 context = SAFE_MALLOC(sizeof(webcam_context_t), webcam_context_t *);
395 if (!context) {
396 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate webcam context");
397 }
398
399 memset(context, 0, sizeof(webcam_context_t));
400
401 // Validate device index
402 if (device_index > WEBCAM_DEVICE_INDEX_MAX) {
403 SAFE_FREE(context);
404 return SET_ERRNO(ERROR_WEBCAM, "Invalid device index: %d (max: %d)", device_index, WEBCAM_DEVICE_INDEX_MAX);
405 }
406
407 // Open V4L2 device
408 char device_path[VIDEO_WEBCAM_LINUX_WEBCAM_V4L2_DEVICE_PATH_BUFFER_SIZE];
409 SAFE_SNPRINTF(device_path, sizeof(device_path), "/dev/video%d", device_index);
410
411 // Check if device file exists before trying to open it
412 context->fd = platform_open("webcam_device", device_path, PLATFORM_O_RDWR | O_NONBLOCK);
413 if (context->fd == -1) {
414 // Provide more helpful error messages based on errno
415 if (errno == ENOENT) {
416 SAFE_FREE(context);
417 return SET_ERRNO(ERROR_WEBCAM,
418 "V4L2 device %s does not exist.\n"
419 "No webcam found. Try:\n"
420 " 1. Check if camera is connected: ls /dev/video*\n"
421 " 2. Use test pattern instead: --test-pattern",
422 device_path);
423 } else if (errno == EACCES) {
424 SAFE_FREE(context);
426 "Permission denied accessing %s.\n"
427 "Try: sudo usermod -a -G video $USER\n"
428 "Then log out and log back in.",
429 device_path);
430 } else if (errno == EBUSY) {
431 SAFE_FREE(context);
432 return SET_ERRNO(ERROR_WEBCAM_IN_USE, "V4L2 device %s is already in use by another application.", device_path);
433 } else {
434 SAFE_FREE(context);
435 return SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to open V4L2 device %s", device_path);
436 }
437 }
438
439 // Check if it's a video capture device
440 struct v4l2_capability cap;
441 if (ioctl(context->fd, VIDIOC_QUERYCAP, &cap) == -1) {
442 close(context->fd);
443 SAFE_FREE(context);
444 return SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to query V4L2 capabilities");
445 }
446
447 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
448 close(context->fd);
449 SAFE_FREE(context);
450 return SET_ERRNO(ERROR_WEBCAM, "Device is not a video capture device");
451 }
452
453 // Set format (try 320x240 first for better performance, fallback to whatever the device supports)
454 if (webcam_v4l2_set_format(context, 320, 240) != 0) {
455 int saved_errno = errno; // Save errno before close() potentially changes it
456 close(context->fd);
457 SAFE_FREE(context);
458 // If format setting failed because device is busy, return ERROR_WEBCAM_IN_USE
459 if (saved_errno == EBUSY) {
460 return SET_ERRNO(ERROR_WEBCAM_IN_USE, "V4L2 device %s is in use - cannot set format", device_path);
461 }
462 return SET_ERRNO(ERROR_WEBCAM, "Failed to set V4L2 format for device %s", device_path);
463 }
464
465 // Initialize buffers
466 if (webcam_v4l2_init_buffers(context) != 0) {
467 close(context->fd);
468 SAFE_FREE(context);
469 return SET_ERRNO(ERROR_WEBCAM, "Failed to initialize V4L2 buffers for device %s", device_path);
470 }
471
472 // Start streaming
473 if (webcam_v4l2_start_streaming(context) != 0) {
474 // Cleanup buffers
475 for (int i = 0; i < context->buffer_count; i++) {
476 if (context->buffers[i].start != MAP_FAILED) {
477 munmap(context->buffers[i].start, context->buffers[i].length);
478 }
479 }
480 SAFE_FREE(context->buffers);
481 close(context->fd);
482 SAFE_FREE(context);
483 return SET_ERRNO(ERROR_WEBCAM, "Failed to start V4L2 streaming for device %s", device_path);
484 }
485
486 // Apply an explicit rate, then query the rate selected by the driver.
487 uint32_t target_fps = (uint32_t)GET_OPTION(fps);
488 struct v4l2_streamparm parm = {0};
489 parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
490 if (target_fps > 0) {
491 parm.parm.capture.timeperframe.numerator = 1;
492 parm.parm.capture.timeperframe.denominator = target_fps;
493 if (ioctl(context->fd, VIDIOC_S_PARM, &parm) != 0)
494 log_debug("V4L2 device does not support frame rate control");
495 }
496 if (ioctl(context->fd, VIDIOC_G_PARM, &parm) == 0 && parm.parm.capture.timeperframe.numerator) {
497 context->fps = (double)parm.parm.capture.timeperframe.denominator / parm.parm.capture.timeperframe.numerator;
498 log_info("V4L2 negotiated capture rate: %.3f FPS", context->fps);
499 }
500
501 // Initialize async lifecycle for camera thread
502 if (!lifecycle_init(&context->async_lifecycle, "webcam_camera")) {
503 // Cleanup on lifecycle init failure
504 for (int i = 0; i < context->buffer_count; i++) {
505 if (context->buffers[i].start != MAP_FAILED) {
506 munmap(context->buffers[i].start, context->buffers[i].length);
507 }
508 }
509 SAFE_FREE(context->buffers);
510 close(context->fd);
511 SAFE_FREE(context);
512 return SET_ERRNO(ERROR_INIT, "Failed to initialize camera thread lifecycle");
513 }
514
515 // Start background camera thread
516 asciichat_error_t thread_err = platform_thread_create(&context->camera_thread, "webcam_camera", webcam_camera_thread_func, context);
517 if (thread_err != ASCIICHAT_OK) {
518 lifecycle_shutdown(&context->async_lifecycle);
519 for (int i = 0; i < context->buffer_count; i++) {
520 if (context->buffers[i].start != MAP_FAILED) {
521 munmap(context->buffers[i].start, context->buffers[i].length);
522 }
523 }
524 SAFE_FREE(context->buffers);
525 close(context->fd);
526 SAFE_FREE(context);
527 return thread_err;
528 }
529
530 *ctx = context;
531 log_dev("V4L2 webcam initialized successfully on %s with async camera thread", device_path);
532
533 /* Register webcam context with named registry */
534 NAMED_REGISTER(context, device_path, "webcam", "0x%tx", NULL);
535
536 return 0;
537}
538
540 if (!ctx)
541 return;
542
543 // Stop streaming to interrupt any blocking reads
544 enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
545 if (ioctl(ctx->fd, VIDIOC_STREAMOFF, &type) == 0) {
546 log_debug("V4L2 streaming stopped for flush");
547 // Restart streaming so reads can continue if needed
548 ioctl(ctx->fd, VIDIOC_STREAMON, &type);
549 }
550}
551
553 if (!ctx)
554 return;
555
556 NAMED_UNREGISTER(ctx);
557
558 // Stop camera thread by shutting down lifecycle
559 if (lifecycle_shutdown(&ctx->async_lifecycle)) {
560 // This caller won the shutdown race, join the thread
561 thread_join(&ctx->camera_thread, NULL);
562 log_debug("Camera background thread joined");
563 }
564
565 // Clean up any remaining frames in the atomic and cached buffers
566 image_t *leftover_frame = (image_t *)atomic_ptr_exchange(&ctx->latest_frame, NULL);
567 if (leftover_frame) {
568 image_destroy(leftover_frame);
569 }
570
571 if (ctx->async_cached_frame) {
572 image_destroy(ctx->async_cached_frame);
573 ctx->async_cached_frame = NULL;
574 }
575
576 // Free swscale context if it was allocated
577 if (ctx->sws_ctx) {
578 sws_freeContext(ctx->sws_ctx);
579 ctx->sws_ctx = NULL;
580 }
581
582 // Free MJPEG codec context if it was allocated
583 if (ctx->mjpeg_codec_ctx) {
584 avcodec_free_context(&ctx->mjpeg_codec_ctx);
585 ctx->mjpeg_codec_ctx = NULL;
586 }
587
588 // Free MJPEG decoded frame if it was allocated
589 if (ctx->mjpeg_decoded_frame) {
590 av_frame_free(&ctx->mjpeg_decoded_frame);
591 ctx->mjpeg_decoded_frame = NULL;
592 }
593
594 // Free cached frame if it was allocated
595 if (v4l2_cached_frame) {
596 image_destroy(v4l2_cached_frame);
597 v4l2_cached_frame = NULL;
598 }
599
600 // Stop streaming
601 enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
602 ioctl(ctx->fd, VIDIOC_STREAMOFF, &type);
603
604 // Unmap buffers
605 if (ctx->buffers) {
606 for (int i = 0; i < ctx->buffer_count; i++) {
607 if (ctx->buffers[i].start != MAP_FAILED) {
608 munmap(ctx->buffers[i].start, ctx->buffers[i].length);
609 }
610 }
611 SAFE_FREE(ctx->buffers);
612 }
613
614 close(ctx->fd);
615 SAFE_FREE(ctx);
616 log_debug("V4L2 webcam cleaned up");
617}
618
620 if (!ctx)
621 return NULL;
622
623 struct v4l2_buffer buf = {0};
624 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
625 buf.memory = V4L2_MEMORY_MMAP;
626
627 // Use poll() to efficiently wait for frame available (500ms timeout)
628 // At 30fps, frames arrive every ~33ms; at 60fps every ~16ms
629 struct pollfd pfd = {.fd = ctx->fd, .events = POLLIN};
630
631 int poll_ret = poll(&pfd, 1, 500); // 500ms timeout for slower cameras
632
633 if (poll_ret < 0) {
634 log_error("poll() failed on V4L2 device: %s", SAFE_STRERROR(errno));
635 return NULL;
636 }
637
638 if (poll_ret == 0) {
639 // Timeout - no frame available within 100ms
640 return NULL;
641 }
642
643 // poll() returned > 0: data is available
644 if (!(pfd.revents & POLLIN)) {
645 // Some other event occurred (error/disconnect)
646 log_error("V4L2 device error: poll revents=0x%x", pfd.revents);
647 return NULL;
648 }
649
650 // Dequeue the buffer (should succeed now)
651 if (ioctl(ctx->fd, VIDIOC_DQBUF, &buf) != 0) {
652 log_error("Failed to dequeue V4L2 buffer after poll(): %s", SAFE_STRERROR(errno));
653 return NULL;
654 }
655
656 // Validate buffer index to prevent crashes
657 if (buf.index >= (unsigned int)ctx->buffer_count) {
658 log_error("V4L2 returned invalid buffer index %u (max: %d)", buf.index, ctx->buffer_count - 1);
659 return NULL;
660 }
661
662 // Validate buffer pointer
663 if (!ctx->buffers || !ctx->buffers[buf.index].start) {
664 log_error("V4L2 buffer %u not initialized (start=%p, buffers=%p)", buf.index, ctx->buffers ? ctx->buffers[buf.index].start : NULL, ctx->buffers);
665 return NULL;
666 }
667
668 // Allocate or reallocate cached frame if needed
669 if (!v4l2_cached_frame || v4l2_cached_frame->w != ctx->width || v4l2_cached_frame->h != ctx->height) {
670 if (v4l2_cached_frame) {
671 image_destroy(v4l2_cached_frame);
672 }
673 v4l2_cached_frame = image_new(ctx->width, ctx->height);
674 if (!v4l2_cached_frame) {
675 log_error("Failed to allocate image buffer");
676 // Re-queue the buffer - use safe error handling
677 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
678 log_error("Failed to re-queue buffer after image allocation failure: %s", SAFE_STRERROR(errno));
679 }
680 return NULL;
681 }
682 }
683
684 image_t *img = v4l2_cached_frame;
685
686 // Handle MJPEG decompression if using MJPEG format
687 if (ctx->pixelformat == V4L2_PIX_FMT_MJPEG) {
688 if (!ctx->mjpeg_codec_ctx) {
689 log_error("MJPEG codec context not initialized");
690 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
691 log_error("Failed to re-queue buffer after MJPEG codec error: %s", SAFE_STRERROR(errno));
692 }
693 return NULL;
694 }
695
696 // Create packet from MJPEG frame data
697 AVPacket pkt = {0};
698 av_new_packet(&pkt, buf.bytesused);
699 memcpy(pkt.data, ctx->buffers[buf.index].start, buf.bytesused);
700
701 // Send packet to decoder
702 if (avcodec_send_packet(ctx->mjpeg_codec_ctx, &pkt) < 0) {
703 log_warn_every(US_PER_SEC_INT, "Failed to send MJPEG packet (size=%u) to decoder", buf.bytesused);
704 av_packet_unref(&pkt);
705 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
706 log_error("Failed to re-queue buffer after MJPEG decode error: %s", SAFE_STRERROR(errno));
707 }
708 return NULL;
709 }
710
711 // Receive decoded frame (JPEG decompression happens here)
712 if (avcodec_receive_frame(ctx->mjpeg_codec_ctx, ctx->mjpeg_decoded_frame) < 0) {
713 log_warn_every(US_PER_SEC_INT, "Failed to decode MJPEG frame from %u bytes", buf.bytesused);
714 av_packet_unref(&pkt);
715 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
716 log_error("Failed to re-queue buffer after MJPEG receive error: %s", SAFE_STRERROR(errno));
717 }
718 return NULL;
719 }
720
721 av_packet_unref(&pkt);
722
723 // Convert decoded frame to RGB24 using swscale
724 if (!ctx->sws_ctx) {
725 log_error("Swscale context not initialized for MJPEG decoded frame");
726 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
727 log_error("Failed to re-queue buffer after swscale init error: %s", SAFE_STRERROR(errno));
728 }
729 return NULL;
730 }
731
732 uint8_t *dst_data[1] = {(uint8_t *)img->pixels};
733 int dst_linesize[1] = {ctx->width * 3};
734
735 sws_scale(ctx->sws_ctx, (const uint8_t *const *)ctx->mjpeg_decoded_frame->data, ctx->mjpeg_decoded_frame->linesize, 0, ctx->height, dst_data, dst_linesize);
736
737 // Re-queue the buffer for future use
738 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
739 log_error("Failed to re-queue V4L2 buffer %u after MJPEG decode: %s", buf.index, SAFE_STRERROR(errno));
740 }
741
742 return img;
743 }
744
745 // Copy and convert frame data based on pixel format
746 if (ctx->sws_ctx) {
747 // Use libswscale for format conversion (NV12, I420, YUYV, UYVY)
748 const uint8_t *src_data[1] = {(const uint8_t *)ctx->buffers[buf.index].start};
749 int src_linesize[1] = {0};
750
751 // Calculate source linesize based on format
752 switch (ctx->pixelformat) {
753 case V4L2_PIX_FMT_NV12:
754 case V4L2_PIX_FMT_YUV420:
755 // For planar formats, linesize equals width
756 src_linesize[0] = ctx->width;
757 break;
758 case V4L2_PIX_FMT_YUYV:
759 case V4L2_PIX_FMT_UYVY:
760 // For packed YUV 4:2:2, each pixel is 2 bytes
761 src_linesize[0] = ctx->width * 2;
762 break;
763 default:
764 src_linesize[0] = ctx->width;
765 }
766
767 uint8_t *dst_data[1] = {(uint8_t *)img->pixels};
768 int dst_linesize[1] = {ctx->width * 3};
769
770 sws_scale(ctx->sws_ctx, src_data, src_linesize, 0, ctx->height, dst_data, dst_linesize);
771 } else {
772 // RGB24 - direct copy with overflow checking
773 size_t frame_size;
774 if (image_calc_rgb_size((size_t)ctx->width, (size_t)ctx->height, &frame_size) != ASCIICHAT_OK) {
775 log_error("Failed to calculate frame size: width=%d, height=%d (would overflow)", ctx->width, ctx->height);
776 image_destroy(img);
777 return NULL;
778 }
779 memcpy(img->pixels, ctx->buffers[buf.index].start, frame_size);
780 }
781
782 // Re-queue the buffer for future use
783 if (ioctl(ctx->fd, VIDIOC_QBUF, &buf) == -1) {
784 log_error("Failed to re-queue V4L2 buffer %u: %s (fd=%d, type=%d, memory=%d)", buf.index, SAFE_STRERROR(errno), ctx->fd, buf.type, buf.memory);
785 // Still return the image - the frame data was already copied
786 }
787
788 return img;
789}
790
801 if (!ctx || !lifecycle_is_initialized(&ctx->async_lifecycle)) {
802 return NULL;
803 }
804
805 // Check if there's a new frame from the camera thread
806 image_t *new_frame = (image_t *)atomic_ptr_exchange(&ctx->latest_frame, NULL);
807
808 if (new_frame) {
809 // New frame available - update cache and return it
810 // (The background thread allocated this frame, we take ownership)
811 if (ctx->async_cached_frame) {
812 image_destroy(ctx->async_cached_frame);
813 }
814 ctx->async_cached_frame = new_frame;
815 return new_frame;
816 }
817
818 // No new frame - return the last cached frame (smooth playback without gaps)
819 return ctx->async_cached_frame;
820}
821
822double webcam_get_fps(webcam_context_t *ctx) {
823 return ctx ? ctx->fps : 0.0;
824}
825
827 if (!ctx || !width || !height)
828 return ERROR_INVALID_PARAM;
829
830 *width = ctx->width;
831 *height = ctx->height;
832 return ASCIICHAT_OK;
833}
834
835asciichat_error_t webcam_list_devices(webcam_device_info_t **out_devices, unsigned int *out_count) {
836 if (!out_devices || !out_count) {
837 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
838 }
839
840 *out_devices = NULL;
841 *out_count = 0;
842
843 // First pass: count valid video devices
844 unsigned int device_count = 0;
845 for (int i = 0; i <= WEBCAM_DEVICE_INDEX_MAX; i++) {
846 char device_path[VIDEO_WEBCAM_LINUX_WEBCAM_V4L2_DEVICE_PATH_BUFFER_SIZE];
847 safe_snprintf(device_path, sizeof(device_path), "/dev/video%d", i);
848
849 int fd = open(device_path, O_RDONLY);
850 if (fd < 0) {
851 continue;
852 }
853
854 struct v4l2_capability cap;
855 if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0 && (cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) {
856 device_count++;
857 }
858 close(fd);
859 }
860
861 if (device_count == 0) {
862 // No devices found - not an error
863 return ASCIICHAT_OK;
864 }
865
866 // Allocate device array
868 if (!devices) {
869 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate device info array");
870 }
871
872 // Second pass: populate device info
873 unsigned int idx = 0;
874 for (int i = 0; i <= WEBCAM_DEVICE_INDEX_MAX && idx < device_count; i++) {
875 char device_path[VIDEO_WEBCAM_LINUX_WEBCAM_V4L2_DEVICE_PATH_BUFFER_SIZE];
876 safe_snprintf(device_path, sizeof(device_path), "/dev/video%d", i);
877
878 int fd = open(device_path, O_RDONLY);
879 if (fd < 0) {
880 continue;
881 }
882
883 struct v4l2_capability cap;
884 if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0 && (cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) {
885 devices[idx].index = (unsigned int)i;
886 SAFE_STRNCPY(devices[idx].name, (const char *)cap.card, WEBCAM_DEVICE_NAME_MAX);
887 idx++;
888 }
889 close(fd);
890 }
891
892 *out_devices = devices;
893 *out_count = idx;
894
895 return ASCIICHAT_OK;
896}
897
899 SAFE_FREE(devices);
900}
901
902#endif // __linux__
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
void * atomic_ptr_exchange(atomic_ptr_t *a, void *new_value)
Atomically exchange a pointer and return the old value.
Named object registry for debugging — log identifiable resource names.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_STRERROR(errnum)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_WEBCAM_IN_USE
Definition error_codes.h:64
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_WEBCAM_PERMISSION
Definition error_codes.h:65
@ ERROR_INVALID_PARAM
@ ERROR_WEBCAM
Definition error_codes.h:63
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#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 US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1339
image_t * image_new_copy(const image_t *source)
Create a copy of an existing image.
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.
image_t * webcam_read_async(webcam_context_t *ctx)
Get the most recent frame from async camera thread (non-blocking).
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
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:106
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
platform_mmap_t mmap
Definition mmap.c:38
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
✅ Safe Integer Arithmetic and Overflow Detection
🔤 String Manipulation and Shell Escaping Utilities
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
Webcam device information structure.
Definition webcam.h:93
unsigned int index
Device index (use with webcam_init_context).
Definition webcam.h:94
asciichat_error_t image_calc_rgb_size(size_t width, size_t height, size_t *out_size)
Calculate total RGB buffer size from dimensions.
Definition util/image.c:64
🖼️ Safe overflow-checked buffer size calculations for images and video frames
double webcam_get_fps(webcam_context_t *ctx)