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_mediafoundation.c
Go to the documentation of this file.
1
6
7#ifdef _WIN32
8
9#define COBJMACROS
10
11/* Storage capacities in elements; text buffers include the terminating NUL. */
12#define VIDEO_WEBCAM_WINDOWS_WEBCAM_MEDIAFOUNDATION_DEVICE_NAME_BUFFER_SIZE 32
13
16#include <ascii-chat/common.h>
19#include <ascii-chat/log/io.h>
20#include <libplatform/system.h>
22#include <mfapi.h>
23#include <mfidl.h>
24#include <mfreadwrite.h>
25#include <mferror.h>
26#include <libswscale/swscale.h>
27
28/* MinGW's Windows SDK headers do not expose this Media Foundation GUID even
29 * though the runtime supports the attribute. Keep the GUID local to this
30 * translation unit instead of requiring a newer MinGW header package. */
31#if defined(__GNUC__) && !defined(_MSC_VER)
32static const GUID asciichat_mf_sample_extension_device_timestamp = {0x8f3e35e7, 0x2dcd, 0x4887, {0x86, 0x22, 0x2a, 0x58, 0xba, 0xa6, 0x52, 0xb0}};
33#define MFSampleExtension_DeviceTimestamp asciichat_mf_sample_extension_device_timestamp
34#endif
35
36// Windows Media Foundation webcam implementation
37// Note: MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING and
38// MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING are defined in mfreadwrite.h
39
40struct webcam_context_t {
41 IMFMediaSource *device;
42 IMFSourceReader *reader;
43 int width;
44 int height;
45 double fps;
46 BOOL mf_initialized;
47 BOOL com_initialized;
48 image_t *cached_frame; // Reusable frame buffer (allocated once, reused for each read)
49 webcam_frame_clock_t clock;
50 struct SwsContext *rgb_converter;
51 int stride;
52 LONGLONG last_sample_timestamp;
53 unsigned short device_index;
54 uint64_t last_frame_log_ns;
55 uint64_t last_copy_log_ns;
56 uint64_t last_backlog_log_ns;
57};
58
59static HRESULT enumerate_devices_and_print(void) {
60 IMFAttributes *attr = NULL;
61 IMFActivate **devices = NULL;
62 UINT32 count = 0;
63 HRESULT hr;
64
65 // Create attribute store for device enumeration
66 hr = MFCreateAttributes(&attr, 1);
67 if (FAILED(hr)) {
68 return SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to create MF attributes: 0x%08x", hr);
69 }
70
71 // Set the device type to video capture
72 hr = IMFAttributes_SetGUID(attr, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
73 if (FAILED(hr)) {
74 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to set MF device type: 0x%08x", hr);
75 goto cleanup;
76 }
77
78 // Enumerate video capture devices
79 hr = MFEnumDeviceSources(attr, &devices, &count);
80 if (FAILED(hr)) {
81 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to enumerate MF devices: 0x%08x", hr);
82 goto cleanup;
83 }
84
85 log_info("Found %d video capture device(s):", count);
86 for (UINT32 i = 0; i < count; i++) {
87 LPWSTR friendlyName = NULL;
88 UINT32 nameLength = 0;
89
90 hr = IMFActivate_GetAllocatedString(devices[i], &MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendlyName, &nameLength);
91 if (SUCCEEDED(hr) && friendlyName) {
92 // Convert wide string to multibyte for logging
93 int len = WideCharToMultiByte(CP_UTF8, 0, friendlyName, -1, NULL, 0, NULL, NULL);
94 if (len > 0) {
95 char *mbName = SAFE_MALLOC((size_t)len, void *);
96 if (mbName && WideCharToMultiByte(CP_UTF8, 0, friendlyName, -1, mbName, len, NULL, NULL) > 0) {
97 log_info(" Device %d: %s", i, mbName);
98 }
99 SAFE_FREE(mbName);
100 }
101 CoTaskMemFree(friendlyName);
102 } else {
103 log_info(" Device %d: <Unknown Name>", i);
104 }
105 }
106
107cleanup:
108 if (devices) {
109 for (UINT32 i = 0; i < count; i++) {
110 if (devices[i]) {
111 IMFActivate_Release(devices[i]);
112 }
113 }
114 CoTaskMemFree((void *)devices);
115 }
116 if (attr) {
117 IMFAttributes_Release(attr);
118 }
119
120 return hr;
121}
122
123asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index) {
124 log_info("Opening Windows webcam with Media Foundation, device index %d", device_index);
125
126 webcam_context_t *cam;
128
129 // Initialize all fields
130 cam->device = NULL;
131 cam->device_index = device_index;
132 cam->reader = NULL;
133 cam->width = 0;
134 cam->height = 0;
135 cam->mf_initialized = FALSE;
136 cam->com_initialized = FALSE;
137 cam->cached_frame = NULL;
138 cam->rgb_converter = NULL;
139 cam->stride = 0;
140 cam->last_sample_timestamp = -1;
141 cam->last_frame_log_ns = 0;
142 cam->last_copy_log_ns = 0;
143 cam->last_backlog_log_ns = 0;
144 cam->clock = (webcam_frame_clock_t){0};
145
146 HRESULT hr;
147 IMFAttributes *attr = NULL;
148 IMFActivate **devices = NULL;
149 UINT32 count = 0;
150 int result = -1;
151
152 // Capture Windows Media Foundation's initialization output
153 LOG_IO("mf", {
154 // Initialize COM
155 hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
156 if (SUCCEEDED(hr)) {
157 cam->com_initialized = TRUE;
158 } else if (hr != RPC_E_CHANGED_MODE) {
159 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to initialize COM: 0x%08x", hr);
160 // Note: We can't use goto from within LOG_IO block, so we'll set hr to FAILED
161 hr = E_FAIL;
162 }
163
164 // Initialize Media Foundation
165 if (SUCCEEDED(hr)) {
166 hr = MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);
167 if (FAILED(hr)) {
168 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to startup Media Foundation: 0x%08x", hr);
169 } else {
170 cam->mf_initialized = TRUE;
171 }
172 }
173 });
174
175 if (FAILED(hr)) {
176 goto error;
177 }
178
179 // Enumerate and print all devices
180 enumerate_devices_and_print();
181
182 // Create attribute store for device enumeration
183 hr = MFCreateAttributes(&attr, 1);
184 if (FAILED(hr)) {
185 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to create MF attributes: 0x%08x", hr);
186 goto error;
187 }
188
189 hr = IMFAttributes_SetGUID(attr, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
190 if (FAILED(hr)) {
191 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to set MF device type: 0x%08x", hr);
192 goto error;
193 }
194
195 // Enumerate devices
196 hr = MFEnumDeviceSources(attr, &devices, &count);
197 if (FAILED(hr)) {
198 SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to enumerate MF devices: 0x%08x", hr);
199 goto error;
200 }
201
202 if (count == 0) {
203 SET_ERRNO(ERROR_WEBCAM, "No video capture devices found");
204 hr = E_FAIL;
205 goto error;
206 }
207
208 if (device_index >= count) {
209 result = SET_ERRNO(ERROR_WEBCAM, "Device index %d out of range (0-%d)", device_index, count - 1);
210 hr = E_FAIL;
211 goto error;
212 }
213
214 // Create media source for the specified device
215 hr = IMFActivate_ActivateObject(devices[device_index], &IID_IMFMediaSource, (void **)&cam->device);
216 log_info("IMFActivate_ActivateObject returned: 0x%08x", hr);
217
218 if (FAILED(hr)) {
219 log_error("CRITICAL: Failed to activate MF device: 0x%08x", hr);
220 log_error(" 0x80070005 = E_ACCESSDENIED (device in use)");
221 log_error(" 0xc00d3704 = Device already in use");
222 log_error(" 0xc00d3e85 = MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED");
223 result = SET_ERRNO(ERROR_WEBCAM_IN_USE, "Media Foundation device %d is in use (HRESULT: 0x%08x)", device_index, hr);
224 goto error;
225 }
226
227 // The basic converter handles progressive camera YUV -> RGB without the
228 // advanced processor's frame-rate conversion and temporal buffering.
229 IMFAttributes *readerAttrs = NULL;
230 hr = MFCreateAttributes(&readerAttrs, 1);
231 if (FAILED(hr)) {
232 log_error("Failed to create reader attributes: 0x%08x", hr);
233 result = SET_ERRNO(ERROR_WEBCAM, "Failed to create reader attributes for device %d (HRESULT: 0x%08x)", device_index, hr);
234 goto error;
235 }
236
237 hr = IMFAttributes_SetUINT32(readerAttrs, &MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE);
238 if (FAILED(hr)) {
239 log_warn("Failed to set video processing attribute: 0x%08x", hr);
240 }
241
242 hr = IMFAttributes_SetUINT32(readerAttrs, &MF_LOW_LATENCY, TRUE);
243 if (FAILED(hr))
244 log_debug("Webcam source reader does not accept low-latency mode: 0x%08x", hr);
245
246 hr = MFCreateSourceReaderFromMediaSource(cam->device, readerAttrs, &cam->reader);
247 log_info("MFCreateSourceReaderFromMediaSource returned: 0x%08x, readerAttrs=%p", hr, (void *)readerAttrs);
248
249 if (readerAttrs) {
250 IMFAttributes_Release(readerAttrs);
251 }
252
253 if (FAILED(hr)) {
254 log_error("CRITICAL: Failed to create MF source reader: 0x%08x", hr);
255 result = SET_ERRNO(ERROR_WEBCAM_IN_USE, "Failed to create Media Foundation source reader for device %d (HRESULT: 0x%08x)", device_index, hr);
256 goto error;
257 }
258
259 // IMPORTANT: Select the video stream first before configuring
260 hr = IMFSourceReader_SetStreamSelection(cam->reader, (DWORD)MF_SOURCE_READER_ALL_STREAMS, FALSE);
261 log_info("SetStreamSelection (deselect all) returned: 0x%08x", hr);
262 if (FAILED(hr)) {
263 log_warn("Failed to deselect all streams: 0x%08x", hr);
264 }
265
266 hr = IMFSourceReader_SetStreamSelection(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, TRUE);
267 log_info("SetStreamSelection (select video) returned: 0x%08x", hr);
268 if (FAILED(hr)) {
269 log_error("Failed to select video stream: 0x%08x", hr);
270 result = SET_ERRNO(ERROR_WEBCAM, "Failed to select video stream for device %d (HRESULT: 0x%08x)", device_index, hr);
271 goto error;
272 }
273
274 // Prefer camera modes within the ASCII capture pixel budget, then their
275 // highest advertised rate and the size closest to 640x480.
276 IMFMediaType *bestType = NULL;
277 UINT32 bestNumerator = 0, bestDenominator = 1;
278 UINT64 bestDistance = UINT64_MAX;
279 UINT64 bestSize = ((UINT64)640 << 32) | 480;
280 for (DWORD index = 0;; index++) {
281 IMFMediaType *nativeType = NULL;
282 hr = IMFSourceReader_GetNativeMediaType(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, index, &nativeType);
283 if (hr == MF_E_NO_MORE_TYPES)
284 break;
285 if (FAILED(hr)) {
286 log_warn("Could not enumerate webcam format %lu: 0x%08x", (unsigned long)index, hr);
287 break;
288 }
289 UINT64 nativeSize = 0, nativeRate = 0;
290 if (SUCCEEDED(IMFMediaType_GetUINT64(nativeType, &MF_MT_FRAME_SIZE, &nativeSize)) && SUCCEEDED(IMFMediaType_GetUINT64(nativeType, &MF_MT_FRAME_RATE, &nativeRate))) {
291 UINT32 numerator = (UINT32)(nativeRate >> 32), denominator = (UINT32)nativeRate;
292 UINT64 width = nativeSize >> 32, height = (UINT32)nativeSize;
293 UINT64 pixels = width * height;
294 UINT64 distance = pixels > 640 * 480 ? pixels - 640 * 480 : 640 * 480 - pixels;
295 if (numerator && denominator) {
296 log_dev("Webcam supported mode: %llux%llu at %.3f FPS", (unsigned long long)width, (unsigned long long)height, (double)numerator / denominator);
297 UINT64 candidate = (UINT64)numerator * bestDenominator;
298 UINT64 best = (UINT64)bestNumerator * denominator;
299 bool within_budget = pixels <= 640 * 480;
300 bool best_within_budget = (bestSize >> 32) * (UINT32)bestSize <= 640 * 480;
301 if (!bestType || (within_budget && !best_within_budget) || (within_budget == best_within_budget && (candidate > best || (candidate == best && distance < bestDistance)))) {
302 if (bestType)
303 IMFMediaType_Release(bestType);
304 bestType = nativeType;
305 nativeType = NULL;
306 bestNumerator = numerator;
307 bestDenominator = denominator;
308 bestDistance = distance;
309 bestSize = nativeSize;
310 }
311 }
312 }
313 if (nativeType)
314 IMFMediaType_Release(nativeType);
315 }
316 if (bestType) {
317 GUID subtype = {0};
318 IMFMediaType_GetGUID(bestType, &MF_MT_SUBTYPE, &subtype);
319 log_info("Selected webcam native subtype: 0x%08lx", (unsigned long)subtype.Data1);
320 hr = IMFSourceReader_SetCurrentMediaType(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, bestType);
321 IMFMediaType_Release(bestType);
322 if (FAILED(hr)) {
323 log_warn("Could not select fastest webcam mode: 0x%08x", hr);
324 bestNumerator = 0;
325 } else {
326 log_info("Requested webcam media mode: %.3f advertised FPS", (double)bestNumerator / bestDenominator);
327 }
328 }
329
330 // Preserve native geometry so color conversion does not require a scaler.
331 IMFMediaType *rgbType = NULL;
332 hr = MFCreateMediaType(&rgbType);
333 if (SUCCEEDED(hr)) {
334 IMFMediaType_SetGUID(rgbType, &MF_MT_MAJOR_TYPE, &MFMediaType_Video);
335 IMFMediaType_SetGUID(rgbType, &MF_MT_SUBTYPE, &MFVideoFormat_RGB32);
336 if (bestNumerator) {
337 IMFMediaType_SetUINT64(rgbType, &MF_MT_FRAME_RATE, ((UINT64)bestNumerator << 32) | bestDenominator);
338 }
339
340 UINT64 frameSize = bestSize;
341 hr = IMFMediaType_SetUINT64(rgbType, &MF_MT_FRAME_SIZE, frameSize);
342 if (FAILED(hr)) {
343 log_warn("Could not set native frame size: 0x%08x", hr);
344 }
345
346 // Use partial type - let MF fill in other details
347 hr = IMFSourceReader_SetCurrentMediaType(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, rgbType);
348 IMFMediaType_Release(rgbType);
349
350 if (SUCCEEDED(hr)) {
351 log_info("Requested RGB32 output at native capture dimensions");
352 } else {
353 log_warn("Could not configure RGB32 webcam output: 0x%08x", hr);
354 result = SET_ERRNO(ERROR_WEBCAM, "Could not configure RGB32 webcam output: 0x%08x", hr);
355 goto error;
356 }
357 }
358
359 // Get actual media type and dimensions
360 IMFMediaType *currentType = NULL;
361 hr = IMFSourceReader_GetCurrentMediaType(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &currentType);
362 if (SUCCEEDED(hr)) {
363 UINT64 frameSize = 0;
364 hr = IMFMediaType_GetUINT64(currentType, &MF_MT_FRAME_SIZE, &frameSize);
365 if (SUCCEEDED(hr)) {
366 cam->width = (int)(frameSize >> 32);
367 cam->height = (int)(frameSize & 0xFFFFFFFF);
368 UINT32 stride = 0;
369 if (SUCCEEDED(IMFMediaType_GetUINT32(currentType, &MF_MT_DEFAULT_STRIDE, &stride)))
370 cam->stride = (int)stride;
371 else
372 cam->stride = cam->width * 4;
373 log_info("Media Foundation webcam opened: %dx%d stride=%d", cam->width, cam->height, cam->stride);
374 UINT64 actualRate = 0;
375 if (SUCCEEDED(IMFMediaType_GetUINT64(currentType, &MF_MT_FRAME_RATE, &actualRate)) && (UINT32)actualRate) {
376 cam->fps = (double)(actualRate >> 32) / (UINT32)actualRate;
377 log_info("Webcam OS media type accepted: %.3f advertised FPS (delivery measured during capture)", cam->fps);
378 }
379 } else {
380 // Default resolution if we can't get the actual size
381 cam->width = 640;
382 cam->height = 480;
383 log_warn("Could not get frame size, using default 640x480");
384 }
385 IMFMediaType_Release(currentType);
386 } else {
387 cam->width = 640;
388 cam->height = 480;
389 log_warn("Could not get media type, using default 640x480");
390 }
391
392 if (!cam->stride)
393 cam->stride = cam->width * 4;
394
395 DWORD streamIndex, flags;
396 LONGLONG timestamp;
397 IMFSample *sample = NULL;
398
399 hr = IMFSourceReader_ReadSample(cam->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
400 0, // Regular synchronous read
401 &streamIndex, &flags, &timestamp, &sample);
402
403 if (FAILED(hr)) {
404 log_error("CRITICAL: Failed to read test frame during initialization: 0x%08x", hr);
405 result = SET_ERRNO(ERROR_WEBCAM_IN_USE, "Failed to read test frame from device %d (HRESULT: 0x%08x)", device_index, hr);
406 goto error;
407 }
408
409 // Clean up the test sample if we got one
410 if (sample) {
411 webcam_frame_clock_age(&cam->clock, timestamp, time_get_ns());
412 IMFSample_Release(sample);
413 }
414
415 // Cleanup enumeration resources on success
416 if (devices) {
417 for (UINT32 i = 0; i < count; i++) {
418 if (devices[i]) {
419 IMFActivate_Release(devices[i]);
420 }
421 }
422 CoTaskMemFree((void *)devices);
423 devices = NULL;
424 }
425 if (attr) {
426 IMFAttributes_Release(attr);
427 attr = NULL;
428 }
429
430 *ctx = cam;
431
432 /* Register webcam context with named registry */
433 char device_name[VIDEO_WEBCAM_WINDOWS_WEBCAM_MEDIAFOUNDATION_DEVICE_NAME_BUFFER_SIZE];
434 snprintf(device_name, sizeof(device_name), "device:%u", device_index);
435 NAMED_REGISTER(cam, device_name, "webcam", "0x%tx", NULL);
436
437 return ASCIICHAT_OK;
438
439error:
440 // Only cleanup devices and attr if they haven't been cleaned up yet
441 if (devices) {
442 for (UINT32 i = 0; i < count; i++) {
443 if (devices[i]) {
444 IMFActivate_Release(devices[i]);
445 }
446 }
447 CoTaskMemFree((void *)devices);
448 }
449 if (attr) {
450 IMFAttributes_Release(attr);
451 }
452 if (cam->reader) {
453 IMFSourceReader_Release(cam->reader);
454 }
455 if (cam->device) {
456 IMFMediaSource_Release(cam->device);
457 }
458 if (cam->mf_initialized) {
459 MFShutdown();
460 }
461 if (cam->com_initialized) {
462 CoUninitialize();
463 }
464 if (cam) {
465 SAFE_FREE(cam);
466 }
467 return result;
468}
469
471 if (ctx && ctx->reader) {
472 // Flush to cancel any pending ReadSample operations
473 // This interrupts blocking synchronous reads in other threads
474 HRESULT hr = IMFSourceReader_Flush(ctx->reader, (DWORD)MF_SOURCE_READER_ALL_STREAMS);
475 if (FAILED(hr)) {
476 log_warn("IMFSourceReader_Flush failed: 0x%08lx", hr);
477 } else {
478 log_debug("Flushed webcam source reader");
479 }
480 }
481}
482
484 if (ctx) {
485 NAMED_UNREGISTER(ctx);
486
487 if (ctx->reader) {
488 // Flush before release to ensure no pending operations
490 IMFSourceReader_Release(ctx->reader);
491 ctx->reader = NULL;
492 }
493 if (ctx->device) {
494 IMFMediaSource_Release(ctx->device);
495 ctx->device = NULL;
496 }
497 if (ctx->mf_initialized) {
498 MFShutdown();
499 ctx->mf_initialized = FALSE;
500 }
501 if (ctx->com_initialized) {
502 CoUninitialize();
503 ctx->com_initialized = FALSE;
504 }
505 // Free cached frame if it was allocated
506 sws_freeContext(ctx->rgb_converter);
507 ctx->rgb_converter = NULL;
508 if (ctx->cached_frame) {
509 image_destroy(ctx->cached_frame);
510 ctx->cached_frame = NULL;
511 }
512 SAFE_FREE(ctx);
513 log_debug("Windows Media Foundation webcam closed");
514 }
515}
516
518 if (!ctx || !ctx->reader) {
519 return NULL;
520 }
521
522 HRESULT hr;
523 IMFSample *sample = NULL;
524 DWORD streamIndex, flags;
525 LONGLONG timestamp;
526 uint64_t request_ns = time_get_ns();
527 unsigned discarded = 0;
528
529 // Timing diagnostic: measure ReadSample duration
530 LARGE_INTEGER freq, start, end;
531 QueryPerformanceFrequency(&freq);
532read_latest:
533 sample = NULL;
534 QueryPerformanceCounter(&start);
535
536 // Read a sample from the source reader
537 // Use 0 for synchronous blocking read (DRAIN flag was wrong - that's for EOF)
538 hr = IMFSourceReader_ReadSample(ctx->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
539 0, // Regular synchronous read
540 &streamIndex, &flags, &timestamp, &sample);
541
542 QueryPerformanceCounter(&end);
543 double elapsed_ms = ((double)(end.QuadPart - start.QuadPart)) * 1000.0 / (double)freq.QuadPart;
544
545 log_debug_every(5 * US_PER_SEC_INT, "ReadSample took %.2f ms (hr=0x%08x, flags=0x%08x, sample=%p)", elapsed_ms, hr, flags, sample);
546
547 // Check for stream tick or other non-data flags
548 if (SUCCEEDED(hr) && (flags & MF_SOURCE_READERF_STREAMTICK)) {
549 log_info("Received stream tick, no sample yet");
550 return NULL;
551 }
552
553 if (SUCCEEDED(hr) && (flags & MF_SOURCE_READERF_ENDOFSTREAM)) {
554 log_warn("End of stream reached");
555 return NULL;
556 }
557
558 if (FAILED(hr)) {
559 log_error("CRITICAL: Failed to read MF sample on FIRST attempt: 0x%08x", hr);
560 log_error(" 0x80070005 = E_ACCESSDENIED (device in use)");
561 log_error(" 0xc00d3704 = Device already in use");
562 log_error(" 0xc00d3e85 = MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED");
563 log_error(" 0x80004005 = E_FAIL (generic failure)");
564 log_error(" 0xc00d36b2 = MF_E_INVALIDREQUEST");
565 log_error(" 0xc00d36c4 = MF_E_HW_MFT_FAILED_START_STREAMING");
566
567 // Return NULL - device is likely in use
568 return NULL;
569 }
570
571 if (!sample) {
572 static int null_count = 0;
573 null_count++;
574 if (null_count <= 10) {
575 // This is normal when using DRAIN flag - it means no sample ready yet
576 if (null_count == 1) {
577 log_info("No sample available yet (this is normal during startup)");
578 }
579 } else if (null_count > 50) {
580 // Too many consecutive NULL samples - likely exclusive access issue
581 log_error("Too many consecutive NULL samples (%d) - device likely in use", null_count);
582 }
583 return NULL;
584 }
585
586 uint64_t wall_ns = time_get_ns();
587 double backlog_ms = (double)webcam_frame_clock_age(&ctx->clock, timestamp, wall_ns) / NS_PER_MS_INT;
588 if (backlog_ms > 33.0) {
589 // ReadSample consumes queued capture samples. Low-latency mode alone does
590 // not discard samples left behind by throttling or expensive frame work.
591 // Skip their RGB conversion and keep the input thread independently live.
592 IMFSample_Release(sample);
593 sample = NULL;
594 ++discarded;
595 if (discarded < 120 && time_get_ns() - request_ns < 100 * NS_PER_MS_INT)
596 goto read_latest;
597 // A clock running slower than monotonic time cannot catch up by draining.
598 // Empty the reader before rebasing, so a new origin never hides queued frames.
599 HRESULT flushed = IMFSourceReader_Flush(ctx->reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM);
600 if (SUCCEEDED(flushed))
601 webcam_frame_clock_reset(&ctx->clock);
602 if (!ctx->last_backlog_log_ns || wall_ns - ctx->last_backlog_log_ns >= NS_PER_SEC_INT) {
603 ctx->last_backlog_log_ns = wall_ns;
604 log_debug("CAMERA_FRAME: device=%u backlog_ms=%.2f discarded=%u (drain budget exhausted, flush=0x%08lx)", ctx->device_index, backlog_ms, discarded, flushed);
605 }
606 return NULL;
607 }
608 UINT64 device_time;
609 double device_age_ms = -1;
610 if (SUCCEEDED(IMFSample_GetUINT64(sample, &MFSampleExtension_DeviceTimestamp, &device_time))) {
611 LONGLONG system_time = MFGetSystemTime();
612 if (system_time >= 0 && device_time <= (UINT64)system_time)
613 device_age_ms = (double)((UINT64)system_time - device_time) / 10000.0;
614 }
615 double device_interval_ms = ctx->last_sample_timestamp >= 0 && timestamp >= ctx->last_sample_timestamp ? (double)(timestamp - ctx->last_sample_timestamp) / 10000.0 : -1;
616 ctx->last_sample_timestamp = timestamp;
617 if (!ctx->last_frame_log_ns || wall_ns - ctx->last_frame_log_ns >= NS_PER_SEC_INT) {
618 ctx->last_frame_log_ns = wall_ns;
619 log_debug("CAMERA_FRAME: device=%u backlog_ms=%.2f read_ms=%.2f discarded=%u device_age_ms=%.2f "
620 "accepted_sample_interval_ms=%.2f",
621 ctx->device_index, backlog_ms, elapsed_ms, discarded, device_age_ms, device_interval_ms);
622 }
623
624 // Get the media buffer from the sample
625 IMFMediaBuffer *buffer = NULL;
626 hr = IMFSample_ConvertToContiguousBuffer(sample, &buffer);
627 if (FAILED(hr)) {
628 static int buffer_fail_count = 0;
629 buffer_fail_count++;
630 log_debug("Failed to get contiguous buffer: 0x%08x (failure #%d)", hr, buffer_fail_count);
631
632 if (buffer_fail_count > 20) {
633 log_error("CRITICAL: Failed to get media buffer %d times - webcam likely in use", buffer_fail_count);
634 }
635
636 IMFSample_Release(sample);
637 return NULL;
638 }
639
640 // Lock the buffer and get the data
641 BYTE *bufferData = NULL;
642 DWORD bufferLength = 0;
643 hr = IMFMediaBuffer_Lock(buffer, &bufferData, NULL, &bufferLength);
644 if (FAILED(hr)) {
645 static int lock_fail_count = 0;
646 lock_fail_count++;
647 log_debug("Failed to lock MF buffer: 0x%08x (failure #%d)", hr, lock_fail_count);
648
649 if (lock_fail_count > 20) {
650 log_error("CRITICAL: Failed to lock media buffer %d times - webcam likely in use", lock_fail_count);
651 }
652
653 IMFMediaBuffer_Release(buffer);
654 IMFSample_Release(sample);
655 return NULL;
656 }
657
658 // Use cached frame dimensions from context (no need to query media type every frame)
659 UINT32 width = (UINT32)ctx->width;
660 UINT32 height = (UINT32)ctx->height;
661
662 // Check for integer overflow before multiplication (prevents heap corruption).
663 // Check pixel count overflow
664 size_t pixel_count_check = 0;
665 if (checked_size_mul((size_t)width, (size_t)height, &pixel_count_check) != ASCIICHAT_OK) {
666 log_error("dimensions overflow: %u x %u", width, height);
667 IMFMediaBuffer_Unlock(buffer);
668 IMFMediaBuffer_Release(buffer);
669 IMFSample_Release(sample);
670 return NULL;
671 }
672
673 // Check pixel buffer size overflow
674 size_t pixel_buffer_size = 0;
675 if (checked_size_mul(pixel_count_check, sizeof(rgb_pixel_t), &pixel_buffer_size) != ASCIICHAT_OK) {
676 log_error("pixel buffer overflow: %zu pixels", pixel_count_check);
677 IMFMediaBuffer_Unlock(buffer);
678 IMFMediaBuffer_Release(buffer);
679 IMFSample_Release(sample);
680 return NULL;
681 }
682
683 // Allocate or reuse cached frame (allocated once, reused for each call)
684 // This matches the documented API contract: "Subsequent calls reuse the same buffer"
685 if (!ctx->cached_frame || ctx->cached_frame->w != (int)width || ctx->cached_frame->h != (int)height) {
686 image_t *img = image_new((int)width, (int)height);
687 if (!img) {
688 IMFMediaBuffer_Unlock(buffer);
689 IMFMediaBuffer_Release(buffer);
690 IMFSample_Release(sample);
691 return NULL;
692 }
693 image_destroy(ctx->cached_frame);
694 ctx->cached_frame = img;
695 }
696
697 image_t *img = ctx->cached_frame;
698
699 // Use FFmpeg's runtime-selected SIMD converter instead of a per-pixel C copy.
700 // Keep the context across frames, including changes in capture dimensions.
701 uint64_t converter_started_ns = time_get_ns();
702 ctx->rgb_converter = sws_getCachedContext(ctx->rgb_converter, (int)width, (int)height, AV_PIX_FMT_BGRA, (int)width, (int)height, AV_PIX_FMT_RGB24, SWS_POINT, NULL, NULL, NULL);
703 uint64_t converter_ready_ns = time_get_ns();
704 size_t stride_bytes = (size_t)(ctx->stride < 0 ? -(int64_t)ctx->stride : ctx->stride);
705 if (!ctx->rgb_converter || stride_bytes < (size_t)width * 4 || bufferLength < stride_bytes * height) {
706 IMFMediaBuffer_Unlock(buffer);
707 IMFMediaBuffer_Release(buffer);
708 IMFSample_Release(sample);
709 SET_ERRNO(ERROR_WEBCAM, "Invalid webcam RGB buffer or converter");
710 return NULL;
711 }
712 const uint8_t *first_row = bufferData + (ctx->stride < 0 ? stride_bytes * (height - 1) : 0);
713 const uint8_t *input[4] = {first_row};
714 const int input_stride[4] = {ctx->stride};
715 uint8_t *output[4] = {(uint8_t *)img->pixels};
716 const int output_stride[4] = {(int)width * 3};
717 uint64_t convert_started_ns = time_get_ns();
718 if (sws_scale(ctx->rgb_converter, input, input_stride, 0, (int)height, output, output_stride) != (int)height) {
719 IMFMediaBuffer_Unlock(buffer);
720 IMFMediaBuffer_Release(buffer);
721 IMFSample_Release(sample);
722 SET_ERRNO(ERROR_WEBCAM, "Could not convert webcam RGB buffer");
723 return NULL;
724 }
725 uint64_t convert_done_ns = time_get_ns();
726 if (convert_done_ns - convert_started_ns >= 50 * NS_PER_MS_INT)
727 log_debug("CAMERA_CONVERT: device=%u width=%u height=%u convert_ms=%.2f", ctx->device_index, width, height, (double)(convert_done_ns - convert_started_ns) / NS_PER_MS_INT);
728
729 uint64_t converted_ns = time_get_ns();
730 // Unlock and cleanup
731 IMFMediaBuffer_Unlock(buffer);
732 uint64_t unlocked_ns = time_get_ns();
733 IMFMediaBuffer_Release(buffer);
734 uint64_t buffer_released_ns = time_get_ns();
735 IMFSample_Release(sample);
736
737 uint64_t complete_ns = time_get_ns();
738 if (!ctx->last_copy_log_ns || complete_ns - ctx->last_copy_log_ns >= NS_PER_SEC_INT) {
739 ctx->last_copy_log_ns = complete_ns;
740 log_debug("CAMERA_COPY: device=%u request_ns=%llu sample_ns=%llu complete_ns=%llu read_ms=%.2f copy_ms=%.2f "
741 "device_age_ms=%.2f",
742 ctx->device_index, (unsigned long long)request_ns, (unsigned long long)wall_ns, (unsigned long long)complete_ns, (double)(wall_ns - request_ns) / NS_PER_MS_INT,
743 (double)(complete_ns - wall_ns) / NS_PER_MS_INT, device_age_ms);
744 log_debug("CAMERA_COPY_STAGES: device=%u sample_ns=%llu setup_ms=%.3f converter_ms=%.3f conversion_ms=%.3f "
745 "unlock_ms=%.3f buffer_release_ms=%.3f sample_release_ms=%.3f",
746 ctx->device_index, (unsigned long long)wall_ns, (double)(converter_started_ns - wall_ns) / NS_PER_MS_INT, (double)(converter_ready_ns - converter_started_ns) / NS_PER_MS_INT,
747 (double)(converted_ns - converter_ready_ns) / NS_PER_MS_INT, (double)(unlocked_ns - converted_ns) / NS_PER_MS_INT, (double)(buffer_released_ns - unlocked_ns) / NS_PER_MS_INT,
748 (double)(complete_ns - buffer_released_ns) / NS_PER_MS_INT);
749 }
750 return img;
751}
752
753double webcam_get_fps(webcam_context_t *ctx) {
754 return ctx ? ctx->fps : 0.0;
755}
756
758 if (!ctx || !width || !height) {
759 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
760 }
761
762 *width = ctx->width;
763 *height = ctx->height;
764 return ASCIICHAT_OK;
765}
766
767asciichat_error_t webcam_list_devices(webcam_device_info_t **out_devices, unsigned int *out_count) {
768 if (!out_devices || !out_count) {
769 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
770 }
771
772 *out_devices = NULL;
773 *out_count = 0;
774
775 IMFAttributes *attr = NULL;
776 IMFActivate **mf_devices = NULL;
777 UINT32 mf_count = 0;
778 HRESULT hr;
780 BOOL com_initialized = FALSE;
781 BOOL mf_initialized = FALSE;
782
783 // Capture Windows Media Foundation's initialization output
784 LOG_IO("mf", {
785 // Initialize COM
786 hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
787 if (SUCCEEDED(hr)) {
788 com_initialized = TRUE;
789 } else if (hr != RPC_E_CHANGED_MODE) {
790 result = SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to initialize COM: 0x%08x", hr);
791 hr = E_FAIL;
792 }
793
794 // Initialize Media Foundation
795 if (SUCCEEDED(hr)) {
796 hr = MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);
797 if (FAILED(hr)) {
798 result = SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to startup Media Foundation: 0x%08x", hr);
799 } else {
800 mf_initialized = TRUE;
801 }
802 }
803 });
804
805 if (FAILED(hr)) {
806 goto cleanup;
807 }
808
809 // Create attribute store for device enumeration
810 hr = MFCreateAttributes(&attr, 1);
811 if (FAILED(hr)) {
812 result = SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to create MF attributes: 0x%08x", hr);
813 goto cleanup;
814 }
815
816 // Set the device type to video capture
817 hr = IMFAttributes_SetGUID(attr, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
818 if (FAILED(hr)) {
819 result = SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to set MF device type: 0x%08x", hr);
820 goto cleanup;
821 }
822
823 // Enumerate video capture devices
824 hr = MFEnumDeviceSources(attr, &mf_devices, &mf_count);
825 if (FAILED(hr)) {
826 result = SET_ERRNO_SYS(ERROR_WEBCAM, "Failed to enumerate MF devices: 0x%08x", hr);
827 goto cleanup;
828 }
829
830 if (mf_count == 0) {
831 // No devices found - not an error, just return empty list
832 goto cleanup;
833 }
834
835 // Allocate output array
837 if (!devices) {
838 result = SET_ERRNO(ERROR_MEMORY, "Failed to allocate device info array");
839 goto cleanup;
840 }
841
842 // Populate device info
843 for (UINT32 i = 0; i < mf_count; i++) {
844 devices[i].index = i;
845
846 LPWSTR friendlyName = NULL;
847 UINT32 nameLength = 0;
848
849 hr = IMFActivate_GetAllocatedString(mf_devices[i], &MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendlyName, &nameLength);
850 if (SUCCEEDED(hr) && friendlyName) {
851 // Convert wide string to UTF-8
852 int len = WideCharToMultiByte(CP_UTF8, 0, friendlyName, -1, NULL, 0, NULL, NULL);
853 if (len > 0 && len < WEBCAM_DEVICE_NAME_MAX) {
854 WideCharToMultiByte(CP_UTF8, 0, friendlyName, -1, devices[i].name, WEBCAM_DEVICE_NAME_MAX, NULL, NULL);
855 } else {
856 SAFE_STRNCPY(devices[i].name, "<Unknown>", WEBCAM_DEVICE_NAME_MAX);
857 }
858 CoTaskMemFree(friendlyName);
859 } else {
860 SAFE_STRNCPY(devices[i].name, "<Unknown>", WEBCAM_DEVICE_NAME_MAX);
861 }
862 }
863
864 *out_devices = devices;
865 *out_count = mf_count;
866
867cleanup:
868 if (mf_devices) {
869 for (UINT32 i = 0; i < mf_count; i++) {
870 if (mf_devices[i]) {
871 IMFActivate_Release(mf_devices[i]);
872 }
873 }
874 CoTaskMemFree((void *)mf_devices);
875 }
876 if (attr) {
877 IMFAttributes_Release(attr);
878 }
879 if (mf_initialized) {
880 MFShutdown();
881 }
882 if (com_initialized) {
883 CoUninitialize();
884 }
885
886 return result;
887}
888
890 SAFE_FREE(devices);
891}
892
893#endif
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
Named object registry for debugging — log identifiable resource names.
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
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_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 NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
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
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:106
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
✅ Safe Integer Arithmetic and Overflow Detection
static bool size_t index
Definition queries.h:10
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
Webcam device information structure.
Definition webcam.h:93
unsigned int index
Device index (use with webcam_init_context).
Definition webcam.h:94
The useful part of webcam frame clock is in sample, previous, wall, initialized: together they descri...
Definition frame_clock.h:16
⏱️ High-precision timing utilities using sokol_time.h and uthash
double webcam_get_fps(webcam_context_t *ctx)