ccap-rs 1.6.0

Rust bindings for ccap — high-performance, cross-platform webcam/camera capture with hardware-accelerated pixel format conversion (DirectShow/AVFoundation/V4L2), including common RGB/YUV workflows and video file input/playback support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/**
 * @file ccap_core.cpp
 * @author wysaid (this@wysaid.org)
 * @brief Header file for CameraCapture class.
 * @date 2025-04
 *
 */

#include "ccap_core.h"

#include "ccap_imp.h"

#include <algorithm>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <unordered_map>

#if defined(_WIN32) || defined(_MSC_VER)
#include <windows.h>
#endif

#ifdef _MSC_VER
#include <malloc.h>
#define ALIGNED_ALLOC(alignment, size) _aligned_malloc(size, alignment)
#define ALIGNED_FREE(ptr) _aligned_free(ptr)
#elif __MINGW32__
#define ALIGNED_ALLOC(alignment, size) __mingw_aligned_malloc(size, alignment)
#define ALIGNED_FREE(ptr) __mingw_aligned_free(ptr)
#else
#define ALIGNED_ALLOC(alignment, size) std::aligned_alloc(alignment, size)
#define ALIGNED_FREE(ptr) std::free(ptr)
#endif

namespace ccap {
ProviderImp* createProviderApple();
ProviderImp* createProviderDirectShow();
ProviderImp* createProviderMSMF();
ProviderImp* createProviderV4L2();

// Global error callback storage
namespace {
std::mutex g_errorCallbackMutex;
ErrorCallback g_globalErrorCallback;
std::mutex g_providerStateMutex;

struct ProviderCachedState {
    std::string extraInfo;
    std::function<bool(const std::shared_ptr<VideoFrame>&)> frameCallback;
    std::function<std::shared_ptr<Allocator>()> allocatorFactory;
    uint32_t maxAvailableFrameSize = DEFAULT_MAX_AVAILABLE_FRAME_SIZE;
    uint32_t maxCacheFrameSize = DEFAULT_MAX_CACHE_FRAME_SIZE;
    int requestedWidth = 640;
    int requestedHeight = 480;
    double requestedFrameRate = 0.0;
    PixelFormat requestedInternalFormat = PixelFormat::Unknown;
    PixelFormat requestedOutputFormat{
#ifdef __APPLE__
        PixelFormat::BGRA32
#else
        PixelFormat::BGR24
#endif
    };
    bool hasFrameOrientationOverride = false;
    FrameOrientation requestedFrameOrientation = FrameOrientation::Default;
};

std::unordered_map<ProviderImp*, ProviderCachedState> g_providerStates;

ProviderCachedState makeProviderCachedState(std::string_view extraInfo = {}) {
    ProviderCachedState state;
    state.extraInfo = std::string(extraInfo);
    return state;
}

ProviderCachedState copyProviderState(ProviderImp* imp) {
    if (imp == nullptr) {
        return makeProviderCachedState();
    }

    std::lock_guard<std::mutex> lock(g_providerStateMutex);
    auto iterator = g_providerStates.find(imp);
    return iterator != g_providerStates.end() ? iterator->second : makeProviderCachedState();
}

void storeProviderState(ProviderImp* imp, ProviderCachedState state) {
    if (imp == nullptr) {
        return;
    }

    std::lock_guard<std::mutex> lock(g_providerStateMutex);
    g_providerStates[imp] = std::move(state);
}

template <typename Fn>
void updateProviderState(ProviderImp* imp, Fn&& updater) {
    if (imp == nullptr) {
        return;
    }

    std::lock_guard<std::mutex> lock(g_providerStateMutex);
    auto [iterator, inserted] = g_providerStates.emplace(imp, makeProviderCachedState());
    (void)inserted;
    updater(iterator->second);
}

void eraseProviderState(ProviderImp* imp) {
    if (imp == nullptr) {
        return;
    }

    std::lock_guard<std::mutex> lock(g_providerStateMutex);
    g_providerStates.erase(imp);
}

void transferProviderState(ProviderImp* from, ProviderImp* to) {
    if (to == nullptr) {
        return;
    }

    std::lock_guard<std::mutex> lock(g_providerStateMutex);
    auto node = g_providerStates.extract(from);
    if (node.empty()) {
        g_providerStates.emplace(to, makeProviderCachedState());
        return;
    }

    node.key() = to;
    g_providerStates.insert(std::move(node));
}

#if defined(_WIN32) || defined(_MSC_VER)
enum class WindowsBackendPreference {
    Auto,
    MSMF,
    DirectShow,
};

std::string toLowerCopy(std::string_view input) {
    std::string normalized;
    normalized.reserve(input.size());
    for (char ch : input) {
        if (!std::isspace(static_cast<unsigned char>(ch))) {
            normalized.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
        }
    }
    return normalized;
}

std::optional<WindowsBackendPreference> parseWindowsBackendPreferenceValue(std::string_view value) {
    std::string normalized = toLowerCopy(value);
    if (normalized.empty()) {
        return std::nullopt;
    }

    constexpr const char* kBackendPrefix = "backend=";
    if (normalized.rfind(kBackendPrefix, 0) == 0) {
        normalized.erase(0, std::strlen(kBackendPrefix));
    }

    if (normalized == "auto") {
        return WindowsBackendPreference::Auto;
    }
    if (normalized == "msmf" || normalized == "mediafoundation") {
        return WindowsBackendPreference::MSMF;
    }
    if (normalized == "dshow" || normalized == "directshow") {
        return WindowsBackendPreference::DirectShow;
    }
    return std::nullopt;
}

std::string getEnvironmentValue(std::string_view name) {
#if defined(_WIN32) || defined(_MSC_VER)
    if (name.empty()) {
        return {};
    }

    std::string envName(name);
    DWORD required = GetEnvironmentVariableA(envName.c_str(), nullptr, 0);
    if (required == 0) {
        return {};
    }

    std::string value(required > 0 ? required - 1 : 0, '\0');
    if (GetEnvironmentVariableA(envName.c_str(), value.data(), required) == 0) {
        return {};
    }

    return value;
#else
    const char* rawValue = std::getenv(std::string(name).c_str());
    return rawValue != nullptr ? std::string(rawValue) : std::string();
#endif
}

WindowsBackendPreference resolveWindowsBackendPreference(std::string_view extraInfo) {
    if (auto parsed = parseWindowsBackendPreferenceValue(extraInfo)) {
        return *parsed;
    }

    std::string envValue = getEnvironmentValue("CCAP_WINDOWS_BACKEND");

    if (!envValue.empty()) {
        if (auto parsed = parseWindowsBackendPreferenceValue(envValue)) {
            return *parsed;
        }
    }

    return WindowsBackendPreference::Auto;
}

bool probeLibraryExport(const wchar_t* libraryName, const char* exportName) {
    HMODULE module = LoadLibraryW(libraryName);
    if (module == nullptr) {
        return false;
    }

    bool ok = GetProcAddress(module, exportName) != nullptr;
    FreeLibrary(module);
    return ok;
}

bool isMediaFoundationCameraBackendAvailable() {
    static const bool s_available = []() {
        return probeLibraryExport(L"mf.dll", "MFEnumDeviceSources") && probeLibraryExport(L"mfplat.dll", "MFStartup") &&
            probeLibraryExport(L"mfreadwrite.dll", "MFCreateSourceReaderFromMediaSource");
    }();
    return s_available;
}

ProviderImp* createWindowsProvider(std::string_view extraInfo) {
    WindowsBackendPreference preference = resolveWindowsBackendPreference(extraInfo);

    if (preference == WindowsBackendPreference::MSMF && isMediaFoundationCameraBackendAvailable()) {
        return createProviderMSMF();
    }

    return createProviderDirectShow();
}

ProviderImp* createWindowsProvider(WindowsBackendPreference preference) {
    switch (preference) {
    case WindowsBackendPreference::MSMF:
        return isMediaFoundationCameraBackendAvailable() ? createProviderMSMF() : nullptr;
    case WindowsBackendPreference::DirectShow:
    case WindowsBackendPreference::Auto:
        return createProviderDirectShow();
    }

    return createProviderDirectShow();
}

int virtualCameraRank(std::string_view name) {
    std::string normalized = toLowerCopy(name);
    constexpr std::string_view keywords[] = {
        "obs",
        "virtual",
        "fake",
    };

    for (size_t index = 0; index < std::size(keywords); ++index) {
        if (normalized.find(keywords[index]) != std::string::npos) {
            return static_cast<int>(index);
        }
    }

    return -1;
}

void sortDeviceNamesForDisplay(std::vector<std::string>& deviceNames) {
    std::stable_sort(deviceNames.begin(), deviceNames.end(), [](const std::string& lhs, const std::string& rhs) {
        return virtualCameraRank(lhs) < virtualCameraRank(rhs);
    });
}

std::vector<std::string> mergeDeviceNames(std::vector<std::string> preferred, const std::vector<std::string>& fallback) {
    for (const std::string& name : fallback) {
        if (std::find(preferred.begin(), preferred.end(), name) == preferred.end()) {
            preferred.push_back(name);
        }
    }

    sortDeviceNamesForDisplay(preferred);
    return preferred;
}

std::vector<std::string> collectDeviceNamesFromBackend(WindowsBackendPreference preference) {
    std::unique_ptr<ProviderImp> provider(createWindowsProvider(preference));
    return provider ? provider->findDeviceNames() : std::vector<std::string>();
}

bool deviceNameExistsInBackend(std::string_view deviceName, WindowsBackendPreference preference) {
    if (deviceName.empty()) {
        return false;
    }

    std::vector<std::string> deviceNames = collectDeviceNamesFromBackend(preference);
    return std::find(deviceNames.begin(), deviceNames.end(), deviceName) != deviceNames.end();
}

std::vector<WindowsBackendPreference> getAutoBackendCandidates(std::string_view deviceName) {
    std::vector<WindowsBackendPreference> candidates;

    if (deviceName.empty()) {
        candidates.push_back(WindowsBackendPreference::DirectShow);
        if (isMediaFoundationCameraBackendAvailable()) {
            candidates.push_back(WindowsBackendPreference::MSMF);
        }
        return candidates;
    }

    const bool inDirectShow = deviceNameExistsInBackend(deviceName, WindowsBackendPreference::DirectShow);
    const bool inMSMF = deviceNameExistsInBackend(deviceName, WindowsBackendPreference::MSMF);

    if (inDirectShow) {
        candidates.push_back(WindowsBackendPreference::DirectShow);
    }
    if (inMSMF) {
        candidates.push_back(WindowsBackendPreference::MSMF);
    }

    if (!candidates.empty()) {
        return candidates;
    }

    candidates.push_back(WindowsBackendPreference::DirectShow);
    if (isMediaFoundationCameraBackendAvailable()) {
        candidates.push_back(WindowsBackendPreference::MSMF);
    }
    return candidates;
}
#endif
} // namespace

CCAP_EXPORT void setErrorCallback(ErrorCallback callback) {
    std::lock_guard<std::mutex> lock(g_errorCallbackMutex);
    g_globalErrorCallback = std::move(callback);
}

CCAP_EXPORT ErrorCallback getErrorCallback() {
    std::lock_guard<std::mutex> lock(g_errorCallbackMutex);
    return g_globalErrorCallback;
}

Allocator::~Allocator() { CCAP_LOG_V("ccap: Allocator::~Allocator() called, this=%p\n", this); }

DefaultAllocator::~DefaultAllocator() {
    if (m_data) ALIGNED_FREE(m_data);
    CCAP_LOG_V("ccap: DefaultAllocator destroyed, deallocated %zu bytes of memory at %p, this=%p\n", m_size, m_data, this);
}

void DefaultAllocator::resize(size_t size) {
    assert(size != 0);
    if (size <= m_size && size >= m_size / 2 && m_data != nullptr) return;

    if (m_data) ALIGNED_FREE(m_data);

    // 32-byte alignment to meet mainstream SIMD instruction set requirements (AVX)
    size_t alignedSize = (size + 31) & ~size_t(31);
    m_data = static_cast<uint8_t*>(ALIGNED_ALLOC(32, alignedSize));
    if (!m_data) {
        reportError(ErrorCode::MemoryAllocationFailed, "Failed to allocate " + std::to_string(alignedSize) + " bytes of aligned memory");
        m_size = 0;
        return;
    }
    m_size = alignedSize;
    CCAP_LOG_V("ccap: Allocated %zu bytes of memory at %p\n", m_size, m_data);
}

VideoFrame::VideoFrame() = default;
VideoFrame::~VideoFrame() { CCAP_LOG_V("ccap: VideoFrame::VideoFrameFrame() called, this=%p\n", this); }

void VideoFrame::detach() {
    if (!allocator || data[0] != allocator->data()) {
        if (!allocator) {
            allocator = std::make_shared<DefaultAllocator>();
        }

        allocator->resize(sizeInBytes);
        // Copy data to allocator
        std::memcpy(allocator->data(), data[0], sizeInBytes);

        // Update data pointers
        data[0] = allocator->data();
        if (stride[1] > 0) {
            data[1] = data[0] + stride[0] * height;
            if (stride[2] > 0) {
                // Currently, only I420 needs to use data[2]
                data[2] = data[1] + stride[1] * height / 2;
            } else {
                data[2] = nullptr;
            }
        } else {
            data[1] = nullptr;
            data[2] = nullptr;
        }

        nativeHandle = nullptr; // Detach native handle
    }
}

ProviderImp* createProvider(std::string_view extraInfo) {
#if __APPLE__
    return createProviderApple();
#elif defined(_MSC_VER) || defined(_WIN32)
    return createWindowsProvider(extraInfo);
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    return createProviderV4L2();
#else
    if (warningLogEnabled()) {
        CCAP_LOG_W("ccap: Unsupported platform!\n");
    }
    reportError(ErrorCode::InitializationFailed, "Unsupported platform");
#endif
    return nullptr;
}

Provider::Provider() :
    m_imp(createProvider("")) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::FAILED_TO_CREATE_PROVIDER);
    } else {
        storeProviderState(m_imp, makeProviderCachedState());
        applyCachedState(m_imp);
    }
}

Provider::Provider(Provider&& other) noexcept :
    m_imp(other.m_imp) {
    other.m_imp = nullptr;
}

Provider& Provider::operator=(Provider&& other) noexcept {
    if (this == &other) {
        return *this;
    }

    eraseProviderState(m_imp);
    delete m_imp;

    m_imp = other.m_imp;
    other.m_imp = nullptr;
    return *this;
}

Provider::~Provider() {
    CCAP_LOG_V("ccap: Provider::~Provider() called, this=%p, imp=%p\n", this, m_imp);
    eraseProviderState(m_imp);
    delete m_imp;
}

Provider::Provider(std::string_view deviceName, std::string_view extraInfo) :
    m_imp(createProvider(extraInfo)) {
    if (m_imp) {
        storeProviderState(m_imp, makeProviderCachedState(extraInfo));
        applyCachedState(m_imp);
        open(deviceName);
    } else {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::FAILED_TO_CREATE_PROVIDER);
    }
}

Provider::Provider(int deviceIndex, std::string_view extraInfo) :
    m_imp(createProvider(extraInfo)) {
    if (m_imp) {
        storeProviderState(m_imp, makeProviderCachedState(extraInfo));
        applyCachedState(m_imp);
        open(deviceIndex);
    } else {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::FAILED_TO_CREATE_PROVIDER);
    }
}

void Provider::applyCachedState(ProviderImp* imp) const {
    if (!imp) {
        return;
    }

    ProviderCachedState state = copyProviderState(m_imp);

    imp->setMaxAvailableFrameSize(state.maxAvailableFrameSize);
    imp->setMaxCacheFrameSize(state.maxCacheFrameSize);
    imp->setNewFrameCallback(state.frameCallback);
    imp->setFrameAllocator(state.allocatorFactory);
    imp->set(PropertyName::Width, state.requestedWidth);
    imp->set(PropertyName::Height, state.requestedHeight);
    imp->set(PropertyName::FrameRate, state.requestedFrameRate);
    imp->set(PropertyName::PixelFormatInternal, static_cast<double>(state.requestedInternalFormat));
    imp->set(PropertyName::PixelFormatOutput, static_cast<double>(state.requestedOutputFormat));
    if (state.hasFrameOrientationOverride) {
        imp->set(PropertyName::FrameOrientation, static_cast<double>(state.requestedFrameOrientation));
    }
}

bool Provider::tryOpenWithImplementation(ProviderImp* imp, std::string_view deviceName, bool autoStart) const {
    if (!imp) {
        return false;
    }

    applyCachedState(imp);
    if (!imp->open(deviceName)) {
        imp->close();
        return false;
    }

    if (autoStart && !imp->start()) {
        imp->close();
        return false;
    }

    return true;
}

std::vector<std::string> Provider::findDeviceNames() {
    if (!m_imp) {
        return std::vector<std::string>();
    }

#if defined(_MSC_VER) || defined(_WIN32)
    if (m_imp->isOpened()) {
        return m_imp->findDeviceNames();
    }

    WindowsBackendPreference preference = resolveWindowsBackendPreference(copyProviderState(m_imp).extraInfo);
    if (preference == WindowsBackendPreference::DirectShow) {
        return collectDeviceNamesFromBackend(WindowsBackendPreference::DirectShow);
    }

    if (preference == WindowsBackendPreference::MSMF) {
        return collectDeviceNamesFromBackend(WindowsBackendPreference::MSMF);
    }

    std::vector<std::string> preferred = collectDeviceNamesFromBackend(WindowsBackendPreference::DirectShow);
    std::vector<std::string> fallback = collectDeviceNamesFromBackend(WindowsBackendPreference::MSMF);
    return mergeDeviceNames(std::move(preferred), fallback);
#else
    return m_imp->findDeviceNames();
#endif
}

bool Provider::open(std::string_view deviceName, bool autoStart) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return false;
    }

#if defined(_MSC_VER) || defined(_WIN32)
    if (m_imp->isOpened()) {
        return m_imp->open(deviceName) && (!autoStart || m_imp->start());
    }

    auto tryBackend = [&](WindowsBackendPreference preference) {
        std::unique_ptr<ProviderImp> candidate(createWindowsProvider(preference));
        if (!candidate || !tryOpenWithImplementation(candidate.get(), deviceName, autoStart)) {
            return false;
        }

        transferProviderState(m_imp, candidate.get());
        delete m_imp;
        m_imp = candidate.release();
        return true;
    };

    if (looksLikeFilePath(deviceName)) {
        return tryBackend(WindowsBackendPreference::DirectShow);
    }

    WindowsBackendPreference preference = resolveWindowsBackendPreference(copyProviderState(m_imp).extraInfo);
    if (preference == WindowsBackendPreference::DirectShow) {
        return tryBackend(WindowsBackendPreference::DirectShow);
    }

    if (preference == WindowsBackendPreference::MSMF) {
        if (!isMediaFoundationCameraBackendAvailable()) {
            reportError(ErrorCode::InitializationFailed, "Media Foundation camera backend is unavailable on this system");
            return false;
        }
        return tryBackend(WindowsBackendPreference::MSMF);
    }

    for (WindowsBackendPreference candidate : getAutoBackendCandidates(deviceName)) {
        if (candidate == WindowsBackendPreference::MSMF && !isMediaFoundationCameraBackendAvailable()) {
            continue;
        }
        if (tryBackend(candidate)) {
            return true;
        }
    }

    return false;
#else
    return m_imp->open(deviceName) && (!autoStart || m_imp->start());
#endif
}

bool Provider::open(int deviceIndex, bool autoStart) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return false;
    }

    std::string deviceName;
    if (deviceIndex >= 0) {
        auto deviceNames = findDeviceNames();
        if (!deviceNames.empty()) {
            deviceIndex = std::min(deviceIndex, static_cast<int>(deviceNames.size()) - 1);
            deviceName = deviceNames[deviceIndex];

            CCAP_LOG_V("ccap: input device index %d, selected device name: %s\n", deviceIndex, deviceName.c_str());
        }
    }

    return open(deviceName, autoStart);
}

bool Provider::isOpened() const { return m_imp && m_imp->isOpened(); }

bool Provider::isFileMode() const { return m_imp && m_imp->isFileMode(); }

std::optional<DeviceInfo> Provider::getDeviceInfo() const { return m_imp ? m_imp->getDeviceInfo() : std::nullopt; }

void Provider::close() {
    if (m_imp) {
        m_imp->close();
    }
}

bool Provider::start() {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return false;
    }
    return m_imp->start();
}

void Provider::stop() {
    if (m_imp) m_imp->stop();
}

bool Provider::isStarted() const { return m_imp && m_imp->isStarted(); }

bool Provider::set(PropertyName prop, double value) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return false;
    }

    bool result = m_imp->set(prop, value);
    if (!result) {
        return false;
    }

    updateProviderState(m_imp, [&](ProviderCachedState& state) {
        switch (prop) {
        case PropertyName::Width:
            state.requestedWidth = static_cast<int>(value);
            break;
        case PropertyName::Height:
            state.requestedHeight = static_cast<int>(value);
            break;
        case PropertyName::FrameRate:
            state.requestedFrameRate = value;
            break;
        case PropertyName::PixelFormatInternal: {
            auto intValue = static_cast<int>(value);
#if defined(_MSC_VER) || defined(_WIN32)
            intValue &= ~kPixelFormatFullRangeBit;
#endif
            state.requestedInternalFormat = static_cast<PixelFormat>(intValue);
            break;
        }
        case PropertyName::PixelFormatOutput: {
            uint32_t formatValue = static_cast<uint32_t>(value);
#if defined(_MSC_VER) || defined(_WIN32)
            formatValue &= ~static_cast<uint32_t>(kPixelFormatFullRangeBit);
#endif
            state.requestedOutputFormat = static_cast<PixelFormat>(formatValue);
            break;
        }
        case PropertyName::FrameOrientation:
            state.requestedFrameOrientation = static_cast<FrameOrientation>(static_cast<int>(value));
            state.hasFrameOrientationOverride = true;
            break;
        default:
            break;
        }
    });

    return true;
}

double Provider::get(PropertyName prop) { return m_imp ? m_imp->get(prop) : NAN; }

std::shared_ptr<VideoFrame> Provider::grab(uint32_t timeoutInMs) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return nullptr;
    }
    return m_imp->grab(timeoutInMs);
}

void Provider::setNewFrameCallback(std::function<bool(const std::shared_ptr<VideoFrame>&)> callback) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return;
    }
    updateProviderState(m_imp, [&](ProviderCachedState& state) {
        state.frameCallback = callback;
    });
    m_imp->setNewFrameCallback(std::move(callback));
}

void Provider::setFrameAllocator(std::function<std::shared_ptr<Allocator>()> allocatorFactory) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return;
    }
    updateProviderState(m_imp, [&](ProviderCachedState& state) {
        state.allocatorFactory = allocatorFactory;
    });
    m_imp->setFrameAllocator(std::move(allocatorFactory));
}

void Provider::setMaxAvailableFrameSize(uint32_t size) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return;
    }
    updateProviderState(m_imp, [&](ProviderCachedState& state) {
        state.maxAvailableFrameSize = size;
    });
    m_imp->setMaxAvailableFrameSize(size);
}

void Provider::setMaxCacheFrameSize(uint32_t size) {
    if (!m_imp) {
        reportError(ErrorCode::InitializationFailed, ErrorMessages::PROVIDER_IMPLEMENTATION_NULL);
        return;
    }
    updateProviderState(m_imp, [&](ProviderCachedState& state) {
        state.maxCacheFrameSize = size;
    });
    m_imp->setMaxCacheFrameSize(size);
}

} // namespace ccap