¿Cómo se convierte un CGImage a CMSampleBufferRef?
-
04-10-2019 - |
Pregunta
Me gustaría convertir un CGImage
a CMSampleBufferRef
y añadirlo a un AVAssetWriterInput
utilizando el método appendSampleBuffer:
. Me las he arreglado para obtener el CMSampleBufferRef
usando el siguiente código, pero el appendSampleBuffer:
simplemente devuelve NO
cuando abastecer el CMSampleBufferRef
resultante. ¿Qué estoy haciendo mal?
- (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 :(
}
P.S. Sé que hay pérdidas de memoria en el código, he omitido una parte del código por razones de simplicidad.
Solución
Aha, me he perdido por completo el AVAssetWriterInputPixelBufferAdaptor
de clase que hacen especialmente para tuberías de los buffers de entrada de píxeles en un escritor. Ahora el código funciona, incluso sin la materia CMSampleBuffer
desordenado.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow