如何将CGImage转换为CMSampleBufferRef?

我想将一个CGImage转换为CMSampleBufferRef并使用appendSampleBuffer:方法将其附加到AVAssetWriterInput 。 我设法使用下面的代码来获取CMSampleBufferRef ,但appendSampleBuffer:当我提供产生的CMSampleBufferRef时,只是返回NO 。 我究竟做错了什么?

 - (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我知道这个代码中有内存泄漏,为了简单起见,我省略了一些代码。

啊哈,我已经完全错过了AVAssetWriterInputPixelBufferAdaptor类,这是专门为pipe道像素缓冲区写入器input。 现在的代码工作,即使没有凌乱的CMSampleBuffer东西。