objective c - AvAssetReader and Writer to overlay video

时光毁灭记忆、已成空白 提交于 2020-01-06 17:26:24

问题


I am trying to overlay a recorded video with AvAssetReader and AvAssetWriter with some images. Following this tutorial, I am able to copy a video (and audio) into a new file. Now my objective is to overlay some of the initial video frames with some images with this code:

while ([assetWriterVideoInput isReadyForMoreMediaData] && !completedOrFailed)
            {
                // Get the next video sample buffer, and append it to the output file.
                CMSampleBufferRef sampleBuffer = [assetReaderVideoOutput copyNextSampleBuffer];

                CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
                CVPixelBufferLockBaseAddress(pixelBuffer, 0);
                EAGLContext *eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
                CIContext *ciContext = [CIContext contextWithEAGLContext:eaglContext options:@{kCIContextWorkingColorSpace : [NSNull null]}];
                UIFont *font = [UIFont fontWithName:@"Helvetica" size:40];
                NSDictionary *attributes = @{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor lightTextColor]};
                UIImage *img = [self imageFromText:@"test" :attributes];

                CIImage *filteredImage = [[CIImage alloc] initWithCGImage:img.CGImage];

                [ciContext render:filteredImage toCVPixelBuffer:pixelBuffer bounds:[filteredImage extent] colorSpace:CGColorSpaceCreateDeviceRGB()];


                CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);

                if (sampleBuffer != NULL)
                {
                    BOOL success = [assetWriterVideoInput appendSampleBuffer:sampleBuffer];
                    CFRelease(sampleBuffer);
                    sampleBuffer = NULL;
                    completedOrFailed = !success;
                }
                else
                {
                    completedOrFailed = YES;
                }
            }

And to create image from text:

-(UIImage *)imageFromText:(NSString *)text :(NSDictionary *)attributes{
CGSize size = [text sizeWithAttributes:attributes];
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[text drawAtPoint:CGPointMake(0.0, 0.0) withAttributes:attributes];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

The video and audio are copied, but I haven't any text on my video.

Question 1: Why this code is not working?

Moreover, I want to be able to check the timecode of the current read frame. For example I would like to insert a text with the current timecode in the video.

I try this code following this tutorial:

        AVAsset *localAsset = [AVAsset assetWithURL:mURL];
    NSError *localError;
    AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:localAsset error:&localError];
    BOOL success = (assetReader != nil);

    // Create asset reader output for the first timecode track of the asset
    if (success) {
        AVAssetTrack *timecodeTrack = nil;

        // Grab first timecode track, if the asset has them
        NSArray *timecodeTracks = [localAsset tracksWithMediaType:AVMediaTypeTimecode];
        if ([timecodeTracks count] > 0)
            timecodeTrack = [timecodeTracks objectAtIndex:0];

        if (timecodeTrack) {
            AVAssetReaderTrackOutput *timecodeOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:timecodeTrack outputSettings:nil];
            [assetReader addOutput:timecodeOutput];
        } else {
            NSLog(@"%@ has no timecode tracks", localAsset);
        }
    }

But I get the log:

[...] has no timecode tracks

Question 2: Why my video hasn't any AVMediaTypeTimecode? Ad so how can I get the current frame timecode?

Thanks for your help


回答1:


I found the solutions:

To overlay video frames, you need to fix the decompression settings:

NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
NSDictionary* decompressionVideoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
// If there is a video track to read, set the decompression settings for YUV and create the asset reader output.
assetReaderVideoOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:assetVideoTrack outputSettings:decompressionVideoSettings];

To get the frame timestamp, you have to read the video informations and then use a counter to increment the current timestamp:

durationSeconds = CMTimeGetSeconds(asset.duration);
timePerFrame = 1.0 / (Float64)assetVideoTrack.nominalFrameRate;
totalFrames = durationSeconds * assetVideoTrack.nominalFrameRate;

Then in this loop

while ([assetWriterVideoInput isReadyForMoreMediaData] && !completedOrFailed)

You can found the timestamp:

CMSampleBufferRef sampleBuffer = [assetReaderVideoOutput copyNextSampleBuffer];
if (sampleBuffer != NULL){
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
if (pixelBuffer) {
Float64 secondsIn = ((float)counter/totalFrames)*durationSeconds;
CMTime imageTimeEstimate = CMTimeMakeWithSeconds(secondsIn, 600);
mergeTime = CMTimeGetSeconds(imageTimeEstimate);
                                    counter++;
}
}

I hope it could help!



来源:https://stackoverflow.com/questions/35267386/objective-c-avassetreader-and-writer-to-overlay-video

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!