5

我正在尝试使用ReplayKit录制我的应用程序的屏幕,在录制视频时裁剪掉其中的某些部分。不太顺利。

ReplayKit 将捕获整个屏幕,因此我决定从 ReplayKit 接收每一帧(如CMSampleBuffervia ),将其裁剪并通过AVAssetWriterInputPixelBufferAdaptorstartCaptureWithHandler将其提供给视频编写器。但是我在裁剪之前硬拷贝图像缓冲区时遇到了麻烦。

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

// 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);
}

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

破碎的

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

  • 每行字节的硬编码4 * width->“错误访问”。
  • 使用intanddouble而不是char-> 一些奇怪的调试器终止异常。
  • 使用其他图像格式 -> “不支持”或访问错误。

此外,releaseCallback它永远不会被调用——ram 将在 10 秒的录制时间内用完。

从这个输出看,潜在的原因是什么?

4

2 回答 2

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)
于 2018-07-23T23:06:02.630 回答
0

You could first save the video as it is. Then by using AVMutableComposition class, you can crop the video by adding instructions and layer instructions to it.

于 2018-07-20T10:35:40.120 回答