0

I am trying to understand one of sample Virtual Camera based on CoreMediaIO given at https://github.com/seanchas116/SimpleDALPlugin

Currenty this camera display animated moving sqaure. relevant code for this is

private func createPixelBuffer() -> CVPixelBuffer? {
    let pixelBuffer = CVPixelBuffer.create(size: CGSize(width: width, height: height))
    pixelBuffer?.modifyWithContext { [width, height] context in
        let time = Double(mach_absolute_time()) / Double(1000_000_000)
        let pos = CGFloat(time - floor(time))

        context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
        context.fill(CGRect(x: 0, y: 0, width: width, height: height))

        context.setFillColor(CGColor(red: 0, green: 1, blue: 0, alpha: 1))

        context.fill(CGRect(x: pos * CGFloat(width), y: 310, width: 100, height: 100))
    }
    return pixelBuffer
}

create and modifyWithContext are defined here

import Foundation

extension CVPixelBuffer {
    static func create(size: CGSize) -> CVPixelBuffer? {
        var pixelBuffer: CVPixelBuffer?
        let options = [
            kCVPixelBufferCGImageCompatibilityKey as String: true,
            kCVPixelBufferCGBitmapContextCompatibilityKey as String: true,
        ] as [String: Any]

        let error = CVPixelBufferCreate(
            kCFAllocatorSystemDefault,
            Int(size.width),
            Int(size.height),
            kCVPixelFormatType_32ARGB,
            options as CFDictionary,
            &pixelBuffer)

        guard error == noErr else {
            log("CVPixelBufferCreate error: \(error)")
            return nil
        }
        return pixelBuffer
    }

    var width: Int {
        return CVPixelBufferGetWidth(self)
    }
    var height: Int {
        return CVPixelBufferGetHeight(self)
    }

    func modifyWithContext(callback: (CGContext) -> Void) {
        CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
        let data = CVPixelBufferGetBaseAddress(self)

        let colorSpace = CGColorSpaceCreateDeviceRGB();
        let bytesPerRow = CVPixelBufferGetBytesPerRow(self)

        let context = CGContext(
            data: data,
            width: width, height: height, bitsPerComponent: 8,
            bytesPerRow: bytesPerRow,
            space: colorSpace,
            bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)

        if let context = context {
            callback(context)
        }

        CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
    }
}

How can I update this code to output window capturing of any specific window like chrome or terminal etc?

4

0 回答 0