首页 文章

iOS 11 Objective-C - 使用AVAssetWriterInputPixelBufferAdaptor从ReplayKit处理图像缓冲区

提问于
浏览
5

我'm trying to record my app'的屏幕使用ReplayKit,在录制视频时裁剪掉它的某些部分 . 不太顺利 .

ReplayKit将捕获整个屏幕,因此我决定从ReplayKit接收每个帧(通过startCaptureWithHandler作为 CMSampleBuffer ),在那里裁剪并通过AVAssetWriterInputPixelBufferAdaptor将其提供给视频编辑器 . 但是我在修剪图像缓冲区之前遇到了麻烦 .

这是我记录整个屏幕的工作代码:

// Starts recording with a completion/error handler
-(void)startRecordingWithHandler: (RPHandler)handler
{
    // Sets up AVAssetWriter that will generate a video file from the recording.
    self.writer = [AVAssetWriter assetWriterWithURL:self.outputFileURL
                                           fileType:AVFileTypeQuickTimeMovie
                                              error:nil];

    NSDictionary* outputSettings =
    @{
      AVVideoWidthKey  : @(screen.size.width),   // The whole width of the entire screen.
      AVVideoHeightKey : @(screen.size.height),  // The whole height of the entire screen.
      AVVideoCodecKey  : AVVideoCodecTypeH264,
      };

    // Sets up AVAssetWriterInput that will feed ReplayKit's frame buffers to the writer.
    self.videoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
                                                         outputSettings:outputSettings];

    // Lets it know that the input will be realtime using ReplayKit.
    [self.videoInput setExpectsMediaDataInRealTime:YES];

    NSDictionary* sourcePixelBufferAttributes =
    @{
      (NSString*) kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA),
      (NSString*) kCVPixelBufferWidthKey          : @(screen.size.width),
      (NSString*) kCVPixelBufferHeightKey         : @(screen.size.height),
      };

    // Adds the video input to the writer.
    [self.writer addInput:self.videoInput];

    // Sets up ReplayKit itself.
    self.recorder = [RPScreenRecorder sharedRecorder];

    // Arranges the pipleline from ReplayKit to the input.
    RPBufferHandler bufferHandler = ^(CMSampleBufferRef sampleBuffer, RPSampleBufferType bufferType, NSError* error) {
        [self captureSampleBuffer:sampleBuffer withBufferType:bufferType];
    };

    RPHandler errorHandler = ^(NSError* error) {
        if (error) handler(error);
    };

    // Starts ReplayKit's recording session. 
    // Sample buffers will be sent to `captureSampleBuffer` method.
    [self.recorder startCaptureWithHandler:bufferHandler completionHandler:errorHandler];
}

// Receives a sample buffer from ReplayKit every frame.
-(void)captureSampleBuffer:(CMSampleBufferRef)sampleBuffer withBufferType:(RPSampleBufferType)bufferType
{
    // Uses a queue in sync so that the writer-starting logic won't be invoked twice.
    dispatch_sync(dispatch_get_main_queue(), ^{
        // Starts the writer if not started yet. We do this here in order to get the proper source time later.
        if (self.writer.status == AVAssetWriterStatusUnknown) {
            [self.writer startWriting];
            return;
        }

        // Receives a sample buffer from ReplayKit.
        switch (bufferType) {
            case RPSampleBufferTypeVideo:{
                // Initializes the source time when a video frame buffer is received the first time.
                // This prevents the output video from starting with blank frames.
                if (!self.startedWriting) {
                    NSLog(@"self.writer startSessionAtSourceTime");
                    [self.writer startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
                    self.startedWriting = YES;
                }

                // Appends a received video frame buffer to the writer.
                [self.input append:sampleBuffer];
                break;
            }
        }
    });
}

// Stops the current recording session, and saves the output file to the user photo album.
-(void)stopRecordingWithHandler:(RPHandler)handler
{
    // Closes the input.
    [self.videoInput markAsFinished];

    // Finishes up the writer. 
    [self.writer finishWritingWithCompletionHandler:^{
        handler(self.writer.error);

        // Saves the output video to the user photo album.
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges: ^{ [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL: self.outputFileURL]; }
                                          completionHandler: ^(BOOL s, NSError* e) { }];
    }];

    // Stops ReplayKit's recording.
    [self.recorder stopCaptureWithHandler:nil];
}

其中来自ReplayKit的每个样本缓冲区将直接送入编写器(在 captureSampleBuffer 方法中),因此记录整个屏幕 .

然后,我使用AVAssetWriterInputPixelBufferAdaptor用相同的逻辑替换了该部件,该工作正常:

...
case RPSampleBufferTypeVideo:{
    ... // Initializes source time.

    // Gets the timestamp of the sample buffer.
    CMTime time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);

    // Extracts the pixel image buffer from the sample buffer.
    CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    // Appends a received sample buffer as an image buffer to the writer via the adaptor.
    [self.videoAdaptor appendPixelBuffer:imageBuffer withPresentationTime:time];
    break;
}
...

适配器设置为:

NSDictionary* sourcePixelBufferAttributes =
@{
  (NSString*) kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA),
  (NSString*) kCVPixelBufferWidthKey          : @(screen.size.width),
  (NSString*) kCVPixelBufferHeightKey         : @(screen.size.height),
  };

self.videoAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:self.videoInput
                                                                                     sourcePixelBufferAttributes:sourcePixelBufferAttributes];

所以管道工作正常 .

然后,我在主存储器中创建了图像缓冲区的硬拷贝并将其提供给适配器:

...
case RPSampleBufferTypeVideo:{
    ... // Initializes source time.

    // Gets the timestamp of the sample buffer.
    CMTime time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);

    // Extracts the pixel image buffer from the sample buffer.
    CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    // Hard-copies the image buffer.
    CVPixelBufferRef copiedImageBuffer = [self copy:imageBuffer];

    // Appends a received video frame buffer to the writer via the adaptor.
    [self.adaptor appendPixelBuffer:copiedImageBuffer withPresentationTime:time];
    break;
}
...

// Hard-copies the pixel buffer.
-(CVPixelBufferRef)copy:(CVPixelBufferRef)inputBuffer
{
    // Locks the base address of the buffer
    // so that GPU won't change the data until unlocked later.
    CVPixelBufferLockBaseAddress(inputBuffer, 0); //-------------------------------

    char* baseAddress = (char*)CVPixelBufferGetBaseAddress(inputBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(inputBuffer);
    size_t width = CVPixelBufferGetWidth(inputBuffer);
    size_t height = CVPixelBufferGetHeight(inputBuffer);
    size_t length = bytesPerRow * height;

    // Mallocs the same length as the input buffer for copying.
    char* outputAddress = (char*)malloc(length);

    // Copies the input buffer's data to the malloced space.
    for (int i = 0; i < length; i++) {
        outputAddress[i] = baseAddress[i];
    }

    // Create a new image buffer using the copied data.
    CVPixelBufferRef outputBuffer;
    CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
                                 width,
                                 height,
                                 kCVPixelFormatType_32BGRA,
                                 outputAddress,
                                 bytesPerRow,
                                 &releaseCallback, // Releases the malloced space.
                                 NULL,
                                 NULL,
                                 &outputBuffer);

    // Unlocks the base address of the input buffer
    // So that GPU can restart using the data.
    CVPixelBufferUnlockBaseAddress(inputBuffer, 0); //-------------------------------

    return outputBuffer;
}

// Releases the malloced space.
void releaseCallback(void *releaseRefCon, const void *baseAddress)
{
    free((void *)baseAddress);
}

这不起作用 - 保存的视频看起来像右侧的屏幕截图:

broken

似乎每行的字节数和颜色格式都是错误的 . 我已经研究并试验了以下内容,但无济于事:

  • 硬编码 4 * width ,每行字节数 - > "bad access" .

  • 使用 intdouble 而不是 char - >一些奇怪的调试器终止异常 .

  • 使用其他图像格式 - > "not supported"或访问错误 .

此外,永远不会调用 releaseCallback - ram将在10秒内完成录制 .

从这个输出看起来有什么潜在的原因?

2 回答

  • 0

    您可以先保存视频 . 然后,通过使用 AVMutableComposition 类,您可以通过向其添加指令和图层指令来裁剪视频 .

  • 0

    就我而言,Replaykit使用420YpCbCr8BiPlanarFullRange格式调用sampleBuffer . 不是RBGA格式 . 你需要工作2架飞机 . 您的屏幕截图显示底部顶部UV平面上的Y平面 . UV平面是Y平面的一半大小 . 获取2架飞机的基地址 .

    CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
    CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 1)
    

    您还需要通过这些API获取每个平面的宽度,高度,每行字节数 .

    CVPixelBufferGetWithOfPlane(imageBuffer, 0 or 1)
    CVPixelBufferGetHeightOfPlane(imageBuffer, 0 or 1)
    CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0 or 1)
    

相关问题