Thursday, June 14, 2012

Get all frame from movie with avfoundation

You can get all frame from movie but need memory large 
/* Get all frame from movie */
- (NSMutableArray*) getAllFrameFromMovie:(NSString*) folderName file:(NSString *) fileName {
    [mainBusy startWithTitle:@"Movie Processing ..."];
    /* Setting input movie */
    NSString* video_inputFileName = fileName;
    NSString* video_inputFilePath = [Utilities documentsPath:folderName file:video_inputFileName];
    NSURL*    video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];    
   
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:video_inputFileUrl options:options];;
   
    Float64 durationFrames = CMTimeGetSeconds([asset duration]) * 24.0;
   
    AVMutableComposition *myComp = [AVMutableComposition composition];
   
    AVMutableCompositionTrack *compositionVideoTrack = [myComp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
   
    NSError *error = nil;
    BOOL ok = NO;
   
    NSMutableArray *frameArray = [[NSMutableArray alloc] init];
   
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:myComp];
    NSError *err = nil;
   
    for (int i = 0; i < floor(durationFrames); i++) {
       
        CMTime startTime = CMTimeMake(i, 24);
        CMTime endTime = CMTimeMake(i+1, 24);
       
        CMTimeRange myRange = CMTimeRangeMake(startTime, endTime);
       
        AVAssetTrack *sourceVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
        ok = [compositionVideoTrack insertTimeRange:myRange ofTrack:sourceVideoTrack atTime:kCMTimeZero error:&error];
        if (!ok) {
            // Deal with the error.
        }
       
        CMTime time = CMTimeMake(0,1);
        UIImage *currentImg = [UIImage imageWithCGImage:[generate copyCGImageAtTime:time actualTime:nil error:&err]];
       
        /* Processing frame  */
        UIImage *img = [self drawText:@"TRAVELsec"
                             fontSize:30 inImage:currentImg atPoint:CGPointMake(10,430) rotatetext:90];
        UIImage *imgs = [self drawText:[NSString stringWithFormat:@"Frame :%d",i]
                              fontSize:30 inImage:img atPoint:CGPointMake(10,470) rotatetext:90];
        [frameArray addObject:imgs];
       
    }
   
    NSLog(@"This video is calculated at %f Frames..",durationFrames);
    NSLog(@"You made a total of %i Frames!!",[frameArray count]);
    [generate release];
   
    return frameArray;
}

No comments:

Post a Comment