Turn your iPhone into a vampire with AVFoundation and iOS 4

August 15th, 2010 § 7 comments

iOS 4 added a lot to AVFoundation, including classes and APIs that give you much more control over the iPhone camera. One of the things you can now do with the camera is read the video frame data in real time.

In this post, I’ve created a simple demo that simulates a Twilight-style vampire. In the Twilight series, vampires aren’t hurt by daylight; instead, they sparkle. Yes, sparkle.

Here are a couple of screenshots from the app:

And here’s a low-quality video of the vampire simulator in action.

The app detects the amount of light shining on the phone by doing very simple image analysis of the incoming video frames from the camera. The brighter the image seen by the camera, the more sparkles it draws on the vampire.

So how does this all work?

AVCaptureSession

The AVCaptureSession object is the centre of the new video and audio input/output universe. An AVCaptureSession can have multiple inputs and outputs. Inputs include video sources (the cameras) and audio sources (microphone). Outputs can be things like a file, or (in this example) an object that captures every frame of video data as it comes from the camera.

The following method demonstrates how to create an AVCaptureSession and add a video input from the front-facing camera (we’re using the front camera because it is more likely to be facing upward, to measure the ambient light) and an output to an object that will let us inspect every video frame that comes from the input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
- (void)start
{
    NSError *error = nil;
 
    AVCaptureDevice *captureDevice = [self frontFacingCameraIfAvailable];
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if ( ! videoInput)
    {
        NSLog(@"Could not get video input: %@", error);
        return;
    }
 
    //  the capture session is where all of the inputs and outputs tie together.
 
    captureSession = [[AVCaptureSession alloc] init];
 
    //  sessionPreset governs the quality of the capture. we don't need high-resolution images,
    //  so we'll set the session preset to low quality.
 
    captureSession.sessionPreset = AVCaptureSessionPresetLow;
 
    [captureSession addInput:videoInput];
 
    //  create the thing which captures the output
    AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
 
    //  pixel buffer format
    NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
                              [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA],
                              kCVPixelBufferPixelFormatTypeKey, nil];
    videoDataOutput.videoSettings = settings;
    [settings release];
 
    //  we don't need a high frame rate. this limits the capture to 5 frames per second.
    videoDataOutput.minFrameDuration = CMTimeMake(1, 5);
 
    //  we need a serial queue for the video capture delegate callback
    dispatch_queue_t queue = dispatch_queue_create("com.bunnyherolabs.vampire", NULL);
 
    [videoDataOutput setSampleBufferDelegate:self queue:queue];
    [captureSession addOutput:videoDataOutput];
    [videoDataOutput release];
 
    dispatch_release(queue);
 
    [captureSession startRunning];
}
 
- (AVCaptureDevice *)frontFacingCameraIfAvailable
{
    //  look at all the video devices and get the first one that's on the front
    NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *captureDevice = nil;
    for (AVCaptureDevice *device in videoDevices)
    {
        if (device.position == AVCaptureDevicePositionFront)
        {
            captureDevice = device;
            break;
        }
    }
 
    //  couldn't find one on the front, so just get the default video device.
    if ( ! captureDevice)
    {
        captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
 
    return captureDevice;
}

The code is (I hope) pretty straightforward. A few things to note:

  • (line 49) The frontFacingCameraIfAvailable method gets the AVCaptureDevice that represents the front-facing camera, if it exists. AVCaptureDevice makes it easy to enumerate all of the capture sources on the device for any given media type (e.g. video, audio). We simply query each device in the list to see if it’s on the front or the back of the phone.
  • Since all we’re doing is measuring the average brightness of the picture, there’s no need to waste resources by grabbing full HD video at 30 frames per second. The sessionPreset property of AVCaptureSession (line 20) governs the resolution of the capture, and the minFrameDuration property of AVCaptureVideoDataOutput (line 35) limits the frame rate.
  • (line 28) We tell the AVCaptureVideoDataOutput object what format we want the frames in. Available options are Y’CbCr and RGB. RGB data is simple to understand, so we ask for that with the kCVPixelFormatType_32BGRA constant.
  • (lines 38-44) AVCaptureVideoDataOutput sends the captured video frames to its delegate. The “queue” argument in setSampleBufferDelgate:queue: is a Grand Central Dispatch queue. I’m not going to go into detail about GCD queues here. Luckily, creating a suitable queue can be done with a single line of code. It can be released immediately after setting the delegate because the AVCaptureVideoDataOutput retains the queue.

Once the capture session starts (with startRunning), every frame of video seen by the camera is sent to the delegate object by callings its captureOutput:didOutputSampleBuffer:fromConnection: method. My implementation of this delegate callback is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    if (CVPixelBufferLockBaseAddress(imageBuffer, 0) == kCVReturnSuccess)
    {
        UInt8 *base = (UInt8 *)CVPixelBufferGetBaseAddress(imageBuffer);
 
        //  calculate average brightness based on a naive calculation
 
        size_t bytesPerRow      = CVPixelBufferGetBytesPerRow(imageBuffer); 
        size_t width            = CVPixelBufferGetWidth(imageBuffer); 
        size_t height           = CVPixelBufferGetHeight(imageBuffer); 
        size_t pixelCount       = width * height;
        UInt32 totalBrightness  = 0;
 
        for (UInt8 *rowStart = base; height; rowStart += bytesPerRow, height --)
        {
            size_t columnCount = width;
            for (UInt8 *p = rowStart; columnCount; p += 4, columnCount --)
            {
                UInt32 value = (p[0] + p[1] + p[2]);
                totalBrightness += value;
            }
        }
        CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
        Game *theGame = self.game;
        dispatch_async(dispatch_get_main_queue(), ^{
            [theGame updateSparklesWithBrightness:(float)totalBrightness/(255 * 3 * pixelCount)];
        });
    }
}

Note that I have not tried to optimize this code at all. This code loops through every pixel in the frame and sums the red, green and blue components. When it’s done, it calculates the average by dividing by the number of pixels and components. It also converts the 8-bit pixel value (0-255) it to a floating-point value in the range of 0 to 1.0. It uses GCD to call the main app on the main thread with the brightness value. The method updateSparklesWithBrightness: in my app adds or removes sparkle graphics based on how bright the camera image is.

Next week I’ll present the rest of the app, which uses the Sparrow framework to display and animate the sparkles.

Tagged ,

§ 7 Responses to Turn your iPhone into a vampire with AVFoundation and iOS 4"

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

What's this?

You are currently reading Turn your iPhone into a vampire with AVFoundation and iOS 4 at bunnyhero dev.

meta

generic viagra india
cialis versus levitra
where to puchase cialis online
viagra urethral
cialis for sale
viagra cialis levitra buy viagra
natural viagra
half price viagra
levitra canada
cialis 10 mg
viagra dosing
cialis side effect
generic cialis soft from india
shelf life of viagra
cialis en ligne de pharmacie
levitra alcohol
formula for viagra
100 dollars cialis
levitra lawyers
viagra
apcalis levitra vs
order discount viagra
levitra young people
viagra vs levitra
viagra oral sex
cialis response
viagra side effect
ladies viagra
levitra users
best generic viagra prices
cheap cialis find
bought viagra fuerteventura
viagra candy
viagra side affects
cialis headache
avandia
effects of viagra on women
viagra next day shipment
viagra extacy ashanti
what is cialis soft
viagra logo
viagra works
over the counter viagra
diabetes and viagra
viagra ocular side effects
viagra wholesale
cialis no perscription
buying viagra in new zealand
cialis allergic lesions
pharmacy online viagra
viagra for sale online
viagra gel
cialis generic
viagra joke
viagra what to expect
directions for taking viagra
lowest cost for cialis 20mm tablets
purchasing viagra
cialis next day delivery
cialis prices
geniune cialis no prescription
viagra pay by e-check
side effects from viagra
levitra consumer information
cialises
viagra sideffects
viagra from usa
viagra uterine thickness
viagra blood pressure
cheapest viagra
cialis achalasia
cialis and levitra
generico viagra
cialis generic india
achat viagra
substitute for viagra
viagra pills cod
levitra sale
viagra availability at boots
cialis pill
viagra and women
buy viagra online in uk
what is the best herbal viagra
levitra medication
purchase cialis
health net viagra non-formulary cost
death by viagra
discount viagra online
roomid 71 cialis
viagra pic
on line prescriptions for cialis
cialis soft tab
viagra soft
viagra purchase
viagra discussion
viagra sheet off leg
what is better viagra or levitra
viagra s
viagra rx
viagra reviews
viagra women forum
viagra levitra cialis
cialis generic rx
viagra time
cialis lawyer ohio
order pfizer viagra with mastercard
drug impotence levitra
buy cialis online viagra
purchase generic viagra
viagra sildenafil citrate
cheap viagra new zealand
generic viagra overnight delivery
cialis australia
cialis overnight
gay men viagra vs cialis
prices cialis
money order viagra
lowest viagra prices
does viagra work for woman
viagra sildenafil
cialis and violent sex
is viagra for women
buy sublingual viagra online
buy viagra
on line viagra
cialis bph
levitra headache
where to buy viagra on line
20mg cialis
generic viagra
cialis super viagra
tadalafil generic cialis
viagra use of
viagra otc
purchase viagra
viagra dosage for women
viagra shelf life
canadian pharmacy viagra
viagra and cocaine
cialis murah klang
info on viagra
cialis dosage
pic viagra woman
discounted viagra
cheapest viagra prices
cheapest generic viagra
cialis user forum
wikipedia viagra
viagra sales uk
cialis viagra sampler
info on cialis
ship free viagra sample
buy cialis online uk
viagra or cealis
cialis women libido
searchstring cialis type all
buying cialis
cost levitra
cialis levitra viagra
viagra 6 free samples
ending viagra use
cialis no prescription
rosacea viagra
viagra adverse events
cialis drug information
viagra for under $2
buy cialis online now
advantages of viagra
c-ring viagra
male enhancement cialis
viagra rss feed
what is better levitra viagra cialis
viagra sample
cheapest price for viagra
headaches levitra
viagra for sale in the uk
viagra cialis levitra buy viagra
recreational viagra
viagra viagra
prescription for viagra
chineese viagra
cialis order form in uk
natural herbal viagra
cost of cialis
double dose of cialis
viagra versus cialis
canada cialis levitra
cialis softabs
can viagra be used by women
india generic cialis
buy viagra alternative
cialis erection problems
generic cialis from india
buying viagra buying viagra
bad side effects of viagra
levitra tabs
viagra inventor
buy cialis online
cheap viagra discount
buy viagra meds online
no prescription cialis
what is better viagra or levitra
que sabes del viagra
cialis canada
buying generic cialis
best buy viagra
online viagra store
natural viagra products
levitra vs cialis
women using viagra
generic viagra buy
buy cialis generic
women viagra
cialis without a prescription
videos viagra
viagra use and abuse
ingredients viagra
cialis cheap
us viagra
cialis vs levitra
what is levitra
side effects viagra
viagra women
what happens when you take viagra
cialis sample
overnight cialis
approval cialis fda
viagra no prescription
bayer and levitra
india cialis
new drug cialis
levitra website
side effects cialis
viagra and jokes
cialis vs levitra
lowest priced viagra in britain
generic viagra online
viagra generico
cialis or viagra
viagra for men
viagra vs cialis
viagra cialis levitra
viagra lawyer ohio
buy online viagra
uk pharmacies cheap viagra
german viagra substitutes
viagra boots
songs about viagra
levitra doses
levitra dose
natural substitute for viagra
cheapest generic levitra
generic levitra 32
women who take levitra
best price for generic viagra
cialis opposite effec
purchase cialis online
viagra online pharmacy
bayer levitra samples
heather viagra grow
cialis multiple attempts
buy viagra in amsterdam
viagra by mail
cialis levia and viagra
viagra uk 32
buy viagra on the internet
cheap cialis sale online
viagra pay pal
viagra discount store
genric viagra
cat 1 keyword viagra
order cialis uk
viagra cialis levitra
cialis overnight shipping
viagra usage
viagra free trials
viagra herbal substitute
negative effects of viagra
woman taking viagra
viagra ad
order cheap viagra
cialis new viagra
buy soma online
buy viagra online 35008
viagra alternative research
u 19835 cialis
cheapest price viagra
viagra free samples
viagra dosage
brand viagra without prescription
ebm diabetes viagra
liquid cialis
discount viagra canada
generic viagra from india
levitra for women
cialis alcohol
buy viagra in canada
women and viagra
cheapest place to buy viagra
40 grams of cialis
viagra info
cialis alternative
cialis naion
viagra experiences
no prescription order viagra online
make your own viagra
levitra vs viagra
pharmacy viagra
women who take viagra
lowest price generic viagra
cheapest place to buy viagra online
buy cialis by check
cialis new viagra
viagra soft tabs
levitra women
levitra pills
viagra and altace
viagra use
levitra vardenafil
buy viagra in mexico
generic viagra lowest prices
buy viagra in bangkok
viagra best way to use
best natural viagra
viagra retarded ejaculation
cialis mexico
generic low price viagra
buy viagra online without prescription
does levitra work
viagra cialis store
dosage of viagra
discount levitra online
viagra ads funny
cialis britain
viagra generique
cialis soft tab india
viagra faq
viagra from canada
levitra eye problems
cialis testimonial
viagra pennis enlargement
suppliers of viagra in uk
what is cialis
cialis trial pack $38
cialis pictures descriptions
cialis canada online pharmacy viagra
lowest prices for cialis
lowest prices viagra
cialis information
viagra australia
viagra india
uk cialis supplier
viagra natural
exercising after taking cialis
cheap viagra
cialis duration of effectiveness
cvs viagra
viagra on-line
cialis versus levitra
sample cialis
u id password cialis
generic for viagra
viagra not working
levitra medicine
natural cialis
cialis wholesale online
cialis samples
cialis viagra levitra
herbal viagra replacements
women use viagra
buy viagra online
viagra online no prescription
multiple acts viagra
viagra forum
viagra online asap
viagra in the water
generic viagra mexico
viagra cialis store
cialis interactions
generic brands of viagra online
soma
cialis pictures results
viagra without a prescription
viagra patent
viagra tiajuana
alchohol and cialis
cialis purchase
cialis and viagra together
overnight viagra
gernic viagra
cialis user reviews
levitra and marijana
viagra buy
viagra directions
rapid tabs viagra
viagra suppositories ivf
wild horses viva viagra
viagra beneficial side effects
canada cialis levitra
viagra cialis
cheap cialis
10 mg cialis
viagra for sale
viagra and jet lag
buy discount paxil
cialis oral
viagra side effects
get viagra over the counter
herbal viagra 32
viagra london
viagra and blood pressure
levitra men video
viagra online
womens viagra
sample of viagra
womens viagra
viagra professional
generic viagra cheap
efficacy levitra
viagra erection time
viagra stories
us pharmacy cialis
viagra cream
mexican viagra
discount generic viagra
viagra low cost
levitra side effects
hair growth with viagra
levitra cialis viagra
buy viagra usa
ed cialis
adverse side effects of viagra
side effects of cialis
viagra uk sales
uprima cialis viagra
apcalis vs viagra
viagra england
buy cheap viagra online uk
buy viagra in uk
guaranteed cheapest viagra
low cost viagra
levitra prescribing
cost of viagra
cialis drug prescription
cialis soft tab description
viagra supplier
viagra pictures
cialis viagra levitra
viagra prices
20mg levitra