iphone - iPhone 读取视频帧时出现内存问题

标签 iphone ios video frame avurlasset

我在从 iPhone 库中选择的现有视频中读取视频帧时遇到内存问题。首先,我将 UIImage-frames 本身添加到一个数组中,但一段时间后我认为该数组对于内存来说太大了,所以我将 UIImages 保存在文档文件夹中并将图像路径添加到数组中。但是,即使使用 Instruments 检查分配情况,我仍然收到相同的内存警告。分配的总内存永远不会超过 2.5mb。也没有发现泄漏...有人能想到什么吗?

-(void)addFrame:(UIImage *)image
{
    NSString *imgPath = [NSString stringWithFormat:@"%@/Analysis%d-%d.png", docFolder, currentIndex, framesArray.count];       
    [UIImagePNGRepresentation(image) writeToFile:imgPath atomically:YES];
    [framesArray addObject:imgPath];    
    frameCount++;      
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissModalViewControllerAnimated:YES];
    [framesArray removeAllObjects];    
    frameCount = 0;          

    // incoming video
    NSURL *videoURL = [info valueForKey:UIImagePickerControllerMediaURL];
    //NSLog(@"Video : %@", videoURL);

    // AVURLAsset to read input movie (i.e. mov recorded to local storage)
    NSDictionary *inputOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *inputAsset = [[AVURLAsset alloc] initWithURL:videoURL options:inputOptions];     

    // Load the input asset tracks information
    [inputAsset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler: ^{        

        NSError *error = nil;
        nrFrames = CMTimeGetSeconds([inputAsset duration]) * 30;
        NSLog(@"Total frames = %d", nrFrames);

        // Check status of "tracks", make sure they were loaded    
        AVKeyValueStatus tracksStatus = [inputAsset statusOfValueForKey:@"tracks" error:&error];
        if (!tracksStatus == AVKeyValueStatusLoaded)
            // failed to load
            return;        

        /* Read video samples from input asset video track */
        AVAssetReader *reader = [AVAssetReader assetReaderWithAsset:inputAsset error:&error];

        NSMutableDictionary *outputSettings = [NSMutableDictionary dictionary];
        [outputSettings setObject: [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]  forKey: (NSString*)kCVPixelBufferPixelFormatTypeKey];
        AVAssetReaderTrackOutput *readerVideoTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:[[inputAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] outputSettings:outputSettings];


        // Assign the tracks to the reader and start to read
        [reader addOutput:readerVideoTrackOutput];
        if ([reader startReading] == NO) {
            // Handle error
            NSLog(@"Error reading");
        }

        NSAutoreleasePool *pool = [NSAutoreleasePool new];
        while (reader.status == AVAssetReaderStatusReading)
        {            
            if(!memoryProblem)
            {
                CMSampleBufferRef sampleBufferRef = [readerVideoTrackOutput copyNextSampleBuffer];
                if (sampleBufferRef) 
                {
                    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBufferRef);
                    /*Lock the image buffer*/
                    CVPixelBufferLockBaseAddress(imageBuffer,0); 
                    /*Get information about the image*/
                    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); 
                    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
                    size_t width = CVPixelBufferGetWidth(imageBuffer); 
                    size_t height = CVPixelBufferGetHeight(imageBuffer); 

                    /*We unlock the  image buffer*/
                    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

                    /*Create a CGImageRef from the CVImageBufferRef*/
                    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
                    CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); 
                    CGImageRef newImage = CGBitmapContextCreateImage(newContext); 

                    /*We release some components*/
                    CGContextRelease(newContext); 
                    CGColorSpaceRelease(colorSpace);

                    UIImage *image= [UIImage imageWithCGImage:newImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationRight];          
                    //[self addFrame:image];
                    [self performSelectorOnMainThread:@selector(addFrame:) withObject:image waitUntilDone:YES];

                    /*We release the CGImageRef*/
                    CGImageRelease(newImage);                    

                    CMSampleBufferInvalidate(sampleBufferRef);
                    CFRelease(sampleBufferRef);
                    sampleBufferRef = NULL;
                }
            }
            else 
            {                
                break;
            }            
        }
        [pool release];

        NSLog(@"Finished");        
    }];   
}

最佳答案

你做一件事并尝试。

NSAutoreleasePool 移至 while 循环内,并在循环内将其排出。

所以它会像下面这样:

while (reader.status == AVAssetReaderStatusReading)
{            
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    .....

    [pool drain];
} 

关于iphone - iPhone 读取视频帧时出现内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887527/

相关文章:

ios - 从 UITableviewCell 中的按钮打开的下拉菜单 UIView 在单元格边界外不可单击

iphone - addSubview 和 removeFromSuperview 时的堆增长

ios - iPad 启动屏幕的不同背景图像,用于启动屏幕中的横向和纵向模式。storyboard

ios - 如何为 iOS 存折创建 "generic type pass"?

javascript - 在滚动条上擦洗视频(apple.com esque)——严重口吃

audio - 将 soundcloud 中的音频与视频文件合并并存储在我们的服务器上?违反api?

ios - UIScrollview 滚动但不会停留在用户抬起手指的位置 swift Storyboard

ios 如何在自定义 View 中放置自定义 Controller 重定向 obj-c 代码

objective-c - 使用变量填充 UITableView

video - Google API用于从youtube视频中提取标签