【问题标题】:iOS Memory leaks creating a video from images with AVAssetWriteriOS 内存泄漏使用 AVAssetWriter 从图像创建视频
【发布时间】:2012-02-09 03:43:15
【问题描述】:


我是 iOS 开发和 stackoverflow 的新手,所以如果我的代码看起来不够好,请多多包涵。

我已经设置了一个测试应用程序使用 ARC 和 AVAssetWriter 创建一个视频,其中包含我的应用程序包中的图像。一切都按预期工作,并且视频可以正确创建,但是当我使用 Instruments 分析我的应用程序时,我得到了内存泄漏,我真的不知道如何修复,因为我在 Detail 视图中看不到与我的代码相关的任何内容(所有泄漏的对象都是 Malloc,负责的库是 VideoToolbox)。

这是我在视图控制器类中开始编写视频时调用的方法:

- (void)writeVideo
{
    // Set the frameDuration ivar (50/600 = 1 sec / 12 number of frames)
    frameDuration = CMTimeMake(50, 600);
    nextPresentationTimeStamp = kCMTimeZero;

    [self deleteTempVideo];

    NSError *error = nil;
    AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:self.videoPath] fileType:AVFileTypeQuickTimeMovie error:&error];
    if (!error) {
        // Define video settings to be passed to the AVAssetWriterInput instance
        NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                       AVVideoCodecH264, AVVideoCodecKey, 
                                       [NSNumber numberWithInt:640],AVVideoWidthKey, 
                                       [NSNumber numberWithInt:480], AVVideoHeightKey, nil];
        // Instanciate the AVAssetWriterInput
        AVAssetWriterInput *writerInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
        // Instanciate the AVAssetWriterInputPixelBufferAdaptor to be connected to the writer input
        AVAssetWriterInputPixelBufferAdaptor *pixelBufferAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput sourcePixelBufferAttributes:nil];
        // Add the writer input to the writer and begin writing
        [writer addInput:writerInput];
        [writer startWriting];
        [writer startSessionAtSourceTime:nextPresentationTimeStamp];
        //
        dispatch_queue_t mediaDataRequestQueue = dispatch_queue_create("Media data request queue", NULL);
        [writerInput requestMediaDataWhenReadyOnQueue:mediaDataRequestQueue usingBlock:^{
            while (writerInput.isReadyForMoreMediaData) {
                CVPixelBufferRef nextBuffer = [self fetchNextPixelBuffer];
                if (nextBuffer) {
                    [pixelBufferAdaptor appendPixelBuffer:nextBuffer withPresentationTime:nextPresentationTimeStamp];
                    nextPresentationTimeStamp = CMTimeAdd(nextPresentationTimeStamp, frameDuration);
                    CVPixelBufferRelease(nextBuffer);                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSUInteger totalFrames = [self.imagesNames count]; 
                        float progress = 1.0 * (totalFrames - [self.imageNamesCopy count]) / totalFrames;
                        [self.progressBar setProgress:progress animated:YES];
                    });
                } else {
                    [writerInput markAsFinished];
                    [writer finishWriting];
                    [self loadVideo];
                    dispatch_release(mediaDataRequestQueue);
                    break;
                }
            }
        }];
    }
}


这是我用于获取像素缓冲区以附​​加到在前一个方法中实例化的像素缓冲区适配器的方法:

// Consume the imageNamesCopy mutable array and return a CVPixelBufferRef relative to the last object of the array
- (CVPixelBufferRef)fetchNextPixelBuffer
{
    NSString *imageName = [self.imageNamesCopy lastObject];
    if (imageName) [self.imageNamesCopy removeLastObject];
    // Create an UIImage instance
    UIImage *image = [UIImage imageNamed:imageName];
    CGImageRef imageRef = image.CGImage;    

    CVPixelBufferRef buffer = NULL;
    size_t width = CGImageGetWidth(imageRef);
    size_t height = CGImageGetHeight(imageRef);
    // Pixel buffer options
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey, 
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];
    // Create the pixel buffer
    CVReturn result = CVPixelBufferCreate(NULL, width, height, kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options, &buffer);
    if (result == kCVReturnSuccess && buffer) {
        CVPixelBufferLockBaseAddress(buffer, 0);
        void *bufferPointer = CVPixelBufferGetBaseAddress(buffer);
        // Define the color space
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        // Create the bitmap context to draw the image
        CGContextRef context = CGBitmapContextCreate(bufferPointer, width, height, 8, 4 * width, colorSpace, kCGImageAlphaNoneSkipFirst);
        CGColorSpaceRelease(colorSpace);
        if (context) {
            CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
            CGContextRelease(context);
        }
        CVPixelBufferUnlockBaseAddress(buffer, 0);
    }
    return buffer;
}

【问题讨论】:

  • AVAssetWriter *writer 从未发布。
  • @Allyn:也许我遗漏了什么,但由于我使用的是 ARC,我应该如何发布 AVAssetWriter *writer?
  • 抱歉,我错过了您使用 ARC。在这种情况下,您可能永远不会发布 CVReturn 结果 - 我认为这不会由 ARC 处理。
  • 抱歉,Allyn,但据我所知(而且我知道的不多)CVReturn 是一个 int,所以它不应该被释放。

标签: ios4 instruments automatic-ref-counting avassetwriter


【解决方案1】:

我发现内存泄漏与视频编写代码无关。泄漏的代码似乎是我从 - (void)writeVideo 中调用的 [self deleteTempVideo] 方法

我仍然需要弄清楚它有什么问题,但我想我的问题此时超出了范围。
这是- (void)deleteTempVideo的代码:

- (void)deleteTempVideo
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager isReadableFileAtPath:self.videoPath]) [fileManager removeItemAtPath:self.videoPath error:nil];
}

这是我用于访问 self.videoPath @property 的 getter:

- (NSString *)videoPath
{
    if (!_videoPath) {
        NSString *fileName = @"test.mov";
        NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        _videoPath = [directoryPath stringByAppendingPathComponent:fileName];
    }
    return _videoPath;
}

【讨论】:

    【解决方案2】:

    就我的经验而言,当你同时使用圆弧和方块时, 您不应该直接使用成员变量。 相反,您可以使用弱属性。

    假设您有一个名为 ClassA 的类和一个名为 _memberA 的成员变量。 通常我会定义memberA的一个属性,然后我可以像下面这样写代码。

    __weak ClassA *weakSelf = self;
    SomeVariable.function = ^() {
        weakSelf.memberA ..... (not use _memberA Here)
    }
    

    PS。 如果块来自某个静态函数,例如 [UIView 动画:持续时间:完成:],则使用成员变量时似乎没问题。

    我通过这种方式解决了很多内存泄漏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 2010-10-27
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多