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
/**
 * @file ccap_file_reader_apple.mm
 * @author wysaid (this@wysaid.org)
 * @brief Video file reader implementation for macOS/iOS using AVFoundation
 * @date 2025-12
 *
 */

#if __APPLE__

#include "ccap_file_reader_apple.h"

#include "ccap_imp_apple.h"
#include "ccap_convert.h"
#include "ccap_convert_frame.h"

#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>

#include <chrono>
#include <cmath>
#include <thread>

using namespace ccap;

#if _CCAP_LOG_ENABLED_
#define CCAP_NSLOG(logLevel, ...) CCAP_CALL_LOG(logLevel, NSLog(__VA_ARGS__))
#define CCAP_NSLOG_E(...) CCAP_NSLOG(LogLevel::Error, __VA_ARGS__)
#define CCAP_NSLOG_W(...) CCAP_NSLOG(LogLevel::Warning, __VA_ARGS__)
#define CCAP_NSLOG_I(...) CCAP_NSLOG(LogLevel::Info, __VA_ARGS__)
#define CCAP_NSLOG_V(...) CCAP_NSLOG(LogLevel::Verbose, __VA_ARGS__)
#else
#define CCAP_NSLOG_E(...) ((void)0)
#define CCAP_NSLOG_W(...) ((void)0)
#define CCAP_NSLOG_I(...) ((void)0)
#define CCAP_NSLOG_V(...) ((void)0)
#endif

@interface CcapFileReaderObjc : NSObject {
    ProviderApple* _provider;
    dispatch_queue_t _readQueue;
    std::atomic<bool> _isReading;
    std::atomic<bool> _shouldStop;
    std::chrono::steady_clock::time_point _startTime;
    double _playbackSpeed;
    int64_t _currentFrameIndex;
    double _currentTime;
}

@property (nonatomic, strong) AVAsset* asset;
@property (nonatomic, strong) AVAssetReader* assetReader;
@property (nonatomic, strong) AVAssetReaderTrackOutput* trackOutput;
@property (nonatomic, strong) NSURL* fileURL;
@property (nonatomic) CMTime frameDuration;
@property (nonatomic) double videoDuration;
@property (nonatomic) double frameRate;
@property (nonatomic) int64_t totalFrameCount;
@property (nonatomic) int videoWidth;
@property (nonatomic) int videoHeight;
@property (nonatomic) BOOL opened;
@property (nonatomic) BOOL started;

- (instancetype)initWithProvider:(ProviderApple*)provider;
- (BOOL)openFile:(NSString*)filePath;
- (void)close;
- (BOOL)start;
- (void)stop;
- (double)getCurrentTime;
- (BOOL)seekToTime:(double)timeInSeconds;
- (double)getCurrentFrameIndex;
- (BOOL)seekToFrame:(int64_t)frameIndex;
- (double)getPlaybackSpeed;
- (BOOL)setPlaybackSpeed:(double)speed;

@end

@implementation CcapFileReaderObjc

- (instancetype)initWithProvider:(ProviderApple*)provider {
    self = [super init];
    if (self) {
        _provider = provider;
        _isReading = false;
        _shouldStop = false;
        _playbackSpeed = 0.0;
        _currentFrameIndex = 0;
        _currentTime = 0.0;
        _opened = NO;
        _started = NO;
    }
    return self;
}

- (void)dealloc {
    [self close];
}

- (BOOL)openFile:(NSString*)filePath {
    if (_opened) {
        [self close];
    }
    
    _fileURL = [NSURL fileURLWithPath:filePath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        reportError(ErrorCode::FileOpenFailed, "File does not exist: " + std::string([filePath UTF8String]));
        return NO;
    }
    
    _asset = [AVAsset assetWithURL:_fileURL];
    if (!_asset) {
        reportError(ErrorCode::FileOpenFailed, "Failed to create AVAsset");
        return NO;
    }
    
    // Get video track
    NSArray<AVAssetTrack*>* videoTracks = [_asset tracksWithMediaType:AVMediaTypeVideo];
    if (videoTracks.count == 0) {
        reportError(ErrorCode::UnsupportedVideoFormat, "No video track found");
        return NO;
    }
    
    AVAssetTrack* videoTrack = videoTracks.firstObject;
    
    // Get video properties
    CGSize naturalSize = videoTrack.naturalSize;
    _videoWidth = (int)naturalSize.width;
    _videoHeight = (int)naturalSize.height;
    
    // Apply transform if needed (for rotated videos)
    CGAffineTransform transform = videoTrack.preferredTransform;
    if (transform.b == 1.0 && transform.c == -1.0) {
        // 90 degrees rotation
        std::swap(_videoWidth, _videoHeight);
    } else if (transform.b == -1.0 && transform.c == 1.0) {
        // -90 degrees rotation
        std::swap(_videoWidth, _videoHeight);
    }
    
    _frameRate = videoTrack.nominalFrameRate;
    if (_frameRate <= 0) {
        _frameRate = 30.0; // Default to 30 fps
    }
    
    _frameDuration = CMTimeMake(1, (int32_t)_frameRate);
    _videoDuration = CMTimeGetSeconds(_asset.duration);
    _totalFrameCount = (int64_t)(_videoDuration * _frameRate);
    
    // Update provider frame properties
    if (_provider) {
        auto& prop = _provider->getFrameProperty();
        prop.width = _videoWidth;
        prop.height = _videoHeight;
        prop.fps = _frameRate;
    }
    
    CCAP_NSLOG_I(@"ccap: Opened video file: %@ (%dx%d, %.2f fps, %.2f seconds, %lld frames)",
                 filePath, _videoWidth, _videoHeight, _frameRate, _videoDuration, _totalFrameCount);
    
    _opened = YES;
    _currentFrameIndex = 0;
    _currentTime = 0.0;
    
    return YES;
}

- (BOOL)setupAssetReader {
    if (_assetReader) {
        [_assetReader cancelReading];
        _assetReader = nil;
        _trackOutput = nil;
    }
    
    NSError* error = nil;
    _assetReader = [[AVAssetReader alloc] initWithAsset:_asset error:&error];
    if (error) {
        reportError(ErrorCode::FileOpenFailed, "Failed to create AVAssetReader: " + std::string([error.localizedDescription UTF8String]));
        return NO;
    }
    
    NSArray<AVAssetTrack*>* videoTracks = [_asset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack* videoTrack = videoTracks.firstObject;
    
    // Configure output settings - prefer NV12/BGRA based on provider settings
    OSType pixelFormat = kCVPixelFormatType_32BGRA;
    if (_provider) {
        auto& prop = _provider->getFrameProperty();
        if (prop.outputPixelFormat & kPixelFormatYUVColorBit) {
            pixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
        }
    }
    
    NSDictionary* outputSettings = @{
        (id)kCVPixelBufferPixelFormatTypeKey: @(pixelFormat)
    };
    
    _trackOutput = [[AVAssetReaderTrackOutput alloc] initWithTrack:videoTrack outputSettings:outputSettings];
    _trackOutput.alwaysCopiesSampleData = NO;
    
    if ([_assetReader canAddOutput:_trackOutput]) {
        [_assetReader addOutput:_trackOutput];
    } else {
        reportError(ErrorCode::UnsupportedVideoFormat, "Cannot add track output to asset reader");
        return NO;
    }
    
    // Set time range starting from current position
    CMTime startTime = CMTimeMakeWithSeconds(_currentTime, 600);
    CMTime duration = CMTimeSubtract(_asset.duration, startTime);
    _assetReader.timeRange = CMTimeRangeMake(startTime, duration);
    
    if (![_assetReader startReading]) {
        reportError(ErrorCode::FileOpenFailed, "Failed to start reading");
        return NO;
    }
    
    return YES;
}

- (void)close {
    [self stop];
    
    if (_assetReader) {
        [_assetReader cancelReading];
        _assetReader = nil;
    }
    _trackOutput = nil;
    _asset = nil;
    _fileURL = nil;
    _opened = NO;
    _currentFrameIndex = 0;
    _currentTime = 0.0;
    
    // Clean up queue only when fully closing (ARC will handle release)
    _readQueue = nil;
}

- (BOOL)start {
    if (!_opened || _started) {
        return _started;
    }
    
    if (![self setupAssetReader]) {
        return NO;
    }
    
    _shouldStop = false;
    _started = YES;
    _startTime = std::chrono::steady_clock::now();
    
    // Reuse existing queue or create new one
    if (!_readQueue) {
        _readQueue = dispatch_queue_create("ccap.file_reader", DISPATCH_QUEUE_SERIAL);
    }
    
    dispatch_async(_readQueue, ^{
        [self readLoop];
    });
    
    return YES;
}

- (void)stop {
    _shouldStop = true;
    _started = NO;
    
    // Wait for reading to finish
    int waitCount = 0;
    while (_isReading && waitCount++ < 100) {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    
    if (_assetReader) {
        [_assetReader cancelReading];
    }
    
    // Queue will be reused on next start(), cleaned up only in close()
}

- (void)readLoop {
    _isReading = true;
    
    auto lastFrameTime = std::chrono::steady_clock::now();
    double targetFrameInterval = (_playbackSpeed > 0.0) ? (1.0 / (_frameRate * _playbackSpeed)) : 0.0;
    
    while (!_shouldStop && _assetReader.status == AVAssetReaderStatusReading) {
        @autoreleasepool {
            // Backpressure: if queue is full, wait for consumer to catch up
            // This prevents dropping frames in file mode
            if (!_provider->shouldReadMoreFrames()) {
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                continue;
            }

            CMSampleBufferRef sampleBuffer = [_trackOutput copyNextSampleBuffer];
            
            if (!sampleBuffer) {
                if (_assetReader.status == AVAssetReaderStatusCompleted) {
                    CCAP_NSLOG_I(@"ccap: Video playback completed");
                }
                break;
            }
            
            // Frame rate control (only when playback speed > 0)
            if (targetFrameInterval > 0.0) {
                auto now = std::chrono::steady_clock::now();
                double elapsedSeconds = std::chrono::duration<double>(now - lastFrameTime).count();
                double sleepTime = targetFrameInterval - elapsedSeconds;
                
                if (sleepTime > 0.001) {
                    std::this_thread::sleep_for(std::chrono::duration<double>(sleepTime));
                }
                
                lastFrameTime = std::chrono::steady_clock::now();
            }
            
            // Process the frame
            [self processFrame:sampleBuffer];
            
            CFRelease(sampleBuffer);
            
            _currentFrameIndex++;
            _currentTime = (double)_currentFrameIndex / _frameRate;
            
            // Update target interval in case playback speed changed
            targetFrameInterval = (_playbackSpeed > 0.0) ? (1.0 / (_frameRate * _playbackSpeed)) : 0.0;
        }
    }
    
    _isReading = false;
    _started = NO;
    
    // Notify waiting grab() calls that playback has finished
    if (_provider) {
        _provider->notifyGrabWaiters();
    }
}

- (void)processFrame:(CMSampleBufferRef)sampleBuffer {
    if (!_provider) return;
    
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    if (!imageBuffer) return;
    
    CVPixelBufferLockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
    
    auto newFrame = _provider->getFreeFrame();
    
    CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
    newFrame->timestamp = (uint64_t)(CMTimeGetSeconds(pts) * 1e9);
    newFrame->width = (uint32_t)CVPixelBufferGetWidth(imageBuffer);
    newFrame->height = (uint32_t)CVPixelBufferGetHeight(imageBuffer);
    newFrame->nativeHandle = imageBuffer;
    newFrame->sizeInBytes = (uint32_t)CVPixelBufferGetDataSize(imageBuffer);
    
    OSType pixelFormatType = CVPixelBufferGetPixelFormatType(imageBuffer);
    
    bool isYUV = (pixelFormatType == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ||
                  pixelFormatType == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange);
    
    if (isYUV) {
        newFrame->pixelFormat = (pixelFormatType == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) 
                                ? PixelFormat::NV12f : PixelFormat::NV12;
        newFrame->data[0] = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);
        newFrame->data[1] = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 1);
        newFrame->data[2] = nullptr;
        newFrame->stride[0] = (uint32_t)CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0);
        newFrame->stride[1] = (uint32_t)CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 1);
        newFrame->stride[2] = 0;
    } else {
        newFrame->pixelFormat = PixelFormat::BGRA32;
        newFrame->data[0] = (uint8_t*)CVPixelBufferGetBaseAddress(imageBuffer);
        newFrame->data[1] = nullptr;
        newFrame->data[2] = nullptr;
        newFrame->stride[0] = (uint32_t)CVPixelBufferGetBytesPerRow(imageBuffer);
        newFrame->stride[1] = 0;
        newFrame->stride[2] = 0;
    }
    
    // Note: AVFoundation (AVAssetReader) returns video frames in TopToBottom order
    // for all formats (NV12, BGRA32), similar to Media Foundation on Windows.
    constexpr FrameOrientation inputOrientation = FrameOrientation::TopToBottom;
    
    // Check if conversion or flip is needed
    auto& prop = _provider->getFrameProperty();
    bool isOutputYUV = (newFrame->pixelFormat & kPixelFormatYUVColorBit) != 0;
    FrameOrientation targetOrientation = isOutputYUV ? FrameOrientation::TopToBottom : _provider->frameOrientation();
    bool shouldFlip = !isOutputYUV && (inputOrientation != targetOrientation);
    bool shouldConvert = newFrame->pixelFormat != prop.outputPixelFormat;
    
    newFrame->orientation = targetOrientation;
    
    bool zeroCopy = !shouldConvert && !shouldFlip;
    
    if (!zeroCopy) {
        if (!newFrame->allocator) {
            auto&& f = _provider->getAllocatorFactory();
            newFrame->allocator = f ? f() : std::make_shared<DefaultAllocator>();
        }
        
        zeroCopy = !inplaceConvertFrame(newFrame.get(), prop.outputPixelFormat, shouldFlip);
        CVPixelBufferUnlockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
    }
    
    if (zeroCopy) {
        CFRetain(imageBuffer);
        auto manager = std::make_shared<FakeFrame>([imageBuffer, newFrame]() mutable {
            CVPixelBufferUnlockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
            CFRelease(imageBuffer);
            newFrame->nativeHandle = nullptr;
            newFrame = nullptr;
        });
        
        auto fakeFrame = std::shared_ptr<VideoFrame>(manager, newFrame.get());
        newFrame = fakeFrame;
    }
    
    newFrame->frameIndex = _currentFrameIndex;
    
    _provider->newFrameAvailable(std::move(newFrame));
}

- (double)getCurrentTime {
    return _currentTime;
}

- (BOOL)seekToTime:(double)timeInSeconds {
    if (!_opened) return NO;
    
    timeInSeconds = std::clamp(timeInSeconds, 0.0, _videoDuration);
    _currentTime = timeInSeconds;
    _currentFrameIndex = (int64_t)(timeInSeconds * _frameRate);
    
    // If playing, restart from new position
    if (_started) {
        [self stop];
        return [self start];
    }
    
    return YES;
}

- (double)getCurrentFrameIndex {
    return (double)_currentFrameIndex;
}

- (BOOL)seekToFrame:(int64_t)frameIndex {
    if (!_opened) return NO;
    
    frameIndex = std::clamp(frameIndex, (int64_t)0, _totalFrameCount);
    _currentFrameIndex = frameIndex;
    _currentTime = (double)frameIndex / _frameRate;
    
    // If playing, restart from new position
    if (_started) {
        [self stop];
        return [self start];
    }
    
    return YES;
}

- (double)getPlaybackSpeed {
    return _playbackSpeed;
}

- (BOOL)setPlaybackSpeed:(double)speed {
    if (speed < 0) return NO;
    _playbackSpeed = speed;
    return YES;
}

@end

namespace ccap {

FileReaderApple::FileReaderApple(ProviderApple* provider) :
    m_provider(provider) {
    m_objc = [[CcapFileReaderObjc alloc] initWithProvider:provider];
}

FileReaderApple::~FileReaderApple() {
    close();
    m_objc = nil;
}

bool FileReaderApple::open(std::string_view filePath) {
    // Convert string_view to NSString safely (string_view may not be null-terminated)
    NSString* path = [[NSString alloc] initWithBytes:filePath.data()
                                              length:filePath.size()
                                            encoding:NSUTF8StringEncoding];
    return [m_objc openFile:path];
}

void FileReaderApple::close() {
    [m_objc close];
}

bool FileReaderApple::isOpened() const {
    return m_objc.opened;
}

bool FileReaderApple::start() {
    return [m_objc start];
}

void FileReaderApple::stop() {
    [m_objc stop];
}

bool FileReaderApple::isStarted() const {
    return m_objc.started;
}

double FileReaderApple::getDuration() const {
    return m_objc.videoDuration;
}

double FileReaderApple::getFrameCount() const {
    return (double)m_objc.totalFrameCount;
}

double FileReaderApple::getCurrentTime() const {
    return [m_objc getCurrentTime];
}

bool FileReaderApple::seekToTime(double timeInSeconds) {
    return [m_objc seekToTime:timeInSeconds];
}

double FileReaderApple::getCurrentFrameIndex() const {
    return [m_objc getCurrentFrameIndex];
}

bool FileReaderApple::seekToFrame(int64_t frameIndex) {
    return [m_objc seekToFrame:frameIndex];
}

double FileReaderApple::getPlaybackSpeed() const {
    return [m_objc getPlaybackSpeed];
}

bool FileReaderApple::setPlaybackSpeed(double speed) {
    return [m_objc setPlaybackSpeed:speed];
}

double FileReaderApple::getFrameRate() const {
    return m_objc.frameRate;
}

int FileReaderApple::getWidth() const {
    return m_objc.videoWidth;
}

int FileReaderApple::getHeight() const {
    return m_objc.videoHeight;
}

} // namespace ccap

#endif // __APPLE__