如何将CGImage转换为CMSampleBufferRef? [英] How do I convert a CGImage to CMSampleBufferRef?

查看:697
本文介绍了如何将CGImage转换为CMSampleBufferRef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 CGImage 转换为 CMSampleBufferRef 并将其附加到 AVAssetWriterInput 使用 appendSampleBuffer:方法。我已设法使用以下代码获取 CMSampleBufferRef ,但 appendSampleBuffer:只返回 NO 当我提供结果 CMSampleBufferRef 时。我做错了什么?

I’d like to convert a CGImage to CMSampleBufferRef and append it to a AVAssetWriterInput using the appendSampleBuffer: method. I’ve managed to get the CMSampleBufferRef using the following code, but the appendSampleBuffer: simply returns NO when I supply the resulting CMSampleBufferRef. What am I doing wrong?

- (void) appendCGImage: (CGImageRef) frame
{
    const int width = CGImageGetWidth(frame);
    const int height = CGImageGetHeight(frame);

    // Create a dummy pixel buffer to try the encoding
    // on something simple.
    CVPixelBufferRef pixelBuffer = NULL;
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, width, height,
        kCVPixelFormatType_32BGRA, NULL, &pixelBuffer);
    NSParameterAssert(status == kCVReturnSuccess && pixelBuffer != NULL);

    // Sample timing info.
    CMTime frameTime = CMTimeMake(1, 30);
    CMTime currentTime = CMTimeAdd(lastSampleTime, frameTime);
    CMSampleTimingInfo timing = {frameTime, currentTime, kCMTimeInvalid};

    OSStatus result = 0;

    // Sample format.
    CMVideoFormatDescriptionRef videoInfo = NULL;
    result = CMVideoFormatDescriptionCreateForImageBuffer(NULL,
         pixelBuffer, &videoInfo);
    NSParameterAssert(result == 0 && videoInfo != NULL);

    // Create sample buffer.
    CMSampleBufferRef sampleBuffer = NULL;
    result = CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault,
        pixelBuffer, true, NULL, NULL, videoInfo, &timing, &sampleBuffer);
    NSParameterAssert(result == 0 && sampleBuffer != NULL);

    // Ship out the frame.
    NSParameterAssert(CMSampleBufferDataIsReady(sampleBuffer));
    NSParameterAssert([writerInput isReadyForMoreMediaData]);
    BOOL success = [writerInput appendSampleBuffer:frame];
    NSParameterAssert(success); // no go :(
}

PS我知道此代码中存在内存泄漏,为了简单起见,我省略了一些代码。

P.S. I know there are memory leaks in this code, I’ve omitted some of the code for simplicity.

推荐答案

啊哈,我完全错过了 AVAssetWriterInputPixelBufferAdaptor 专门用于将像素缓冲区管道输入到编写器输入中的类。现在代码可以工作,即使没有混乱的 CMSampleBuffer 东西。

Aha, I’ve completely missed the AVAssetWriterInputPixelBufferAdaptor class that’s made especially for piping the pixel buffers into a writer input. Now the code works, even without the messy CMSampleBuffer stuff.

这篇关于如何将CGImage转换为CMSampleBufferRef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆