GPUImage - recording video with dynamic overlay post

10/05/2014 with tags : objc, gpuimage, imageprocessing

In one of my aps I had to record video with dynamic overlay - timer to be precise. First thought was to use AVFoundation to record video and then edit it adding an overlay. After some tests I have rediscovered GPUImage as an video editing/recording library.

GPUImage allows you to overlay video with any UI element (eq. UILabel). You just have to combine camera/video stream with instance of GPUImageUIElement class using GPUImageSourceOverBlendFilter.

(drop code here)
 camera -> composition_filter
 overlay -> composition_filter
 composition_filter -> preview / file

My idea was to use CGContextRef and draw overlays by myself.

I have created GPUImage filter that can be used to manually draw ovelays on video. This example draws timer showing current video playback time.

 frameDrawer.contextUpdateBlock = ^BOOL(CGContextRef context, CGSize size, CMTime time) {
        CGContextSetRGBFillColor(context, 1, 1, 1, 1);

        CGFloat secondsf = (CGFloat)time.value / (CGFloat)time.timescale;
        NSUInteger seconds = (int)roundf(secondsf);
        NSUInteger loc = (int)roundf(secondsf * 10) % (int)chars.length;

        NSString *chars = @"-\\|/";
        NSString *s = [chars substringWithRange:NSMakeRange(loc,1)];

        CGContextClearRect(context, CGRectMake(90, 90, 120, 40));
        CGContextSetRGBFillColor(context, 0, 0, 0, 0.8);
        CGContextFillRect(context, CGRectMake(90, 90, 120, 40));

        int time_m (int)(seconds / 60);
        int time_s = (int)(seconds % 60)
        s = [NSString stringWithFormat:@"%@ - %02d:%02d",s,time_m,time_s];

        CGContextSetRGBFillColor(context, 1, 1, 1, 1);
        CGContextShowTextAtPoint(context, 100, 100, [s UTF8String], s.length);

        return YES;
    };

Code

Code ia available on Github