Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

objective c - AvAssetReader and Writer to overlay video

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...