iOS-逐帧读取视频文件,进行图像处理,然后另存为新视频文件

iOS-逐帧读取视频文件,进行图像处理,然后另存为新视频文件,ios,Ios,我试着一帧一帧地阅读iPhone相册中的视频。 在图像处理之后,我会将它们保存为新的视频。 我正在运行我的代码,没有任何错误,但相册中没有新的视频 这是我的密码 // Video writer init - (BOOL)setupAssetWriterForURL:(CMFormatDescriptionRef)formatDescription { float bitsPerPixel; CMVideoDimensions dimensions = CMVideoFormatD

我试着一帧一帧地阅读iPhone相册中的视频。 在图像处理之后,我会将它们保存为新的视频。 我正在运行我的代码,没有任何错误,但相册中没有新的视频

这是我的密码

// Video writer init
- (BOOL)setupAssetWriterForURL:(CMFormatDescriptionRef)formatDescription
{
    float bitsPerPixel;
    CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
    int numPixels = dimensions.width * dimensions.height;
    int bitsPerSecond;

    if ( numPixels < (640 * 480) )
        bitsPerPixel = 4.05; 
    else
        bitsPerPixel = 11.4; 

    bitsPerSecond = numPixels * bitsPerPixel;

    NSDictionary *videoCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInteger:dimensions.width], AVVideoWidthKey,
                                              [NSNumber numberWithInteger:dimensions.height], AVVideoHeightKey,
                                              [NSDictionary dictionaryWithObjectsAndKeys:
                                               [NSNumber numberWithInteger:bitsPerSecond], AVVideoAverageBitRateKey,
                                               [NSNumber numberWithInteger:30], AVVideoMaxKeyFrameIntervalKey,
                                               nil], AVVideoCompressionPropertiesKey,
                                              nil];
    if ([assetWriter canApplyOutputSettings:videoCompressionSettings forMediaType:AVMediaTypeVideo]) {
        assetWriterVideoIn = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo outputSettings:videoCompressionSettings];
        assetWriterVideoIn.expectsMediaDataInRealTime = YES;
        assetWriterVideoIn.transform = [self transformFromCurrentVideoOrientationToOrientation:self.referenceOrientation];
        if ([assetWriter canAddInput:assetWriterVideoIn])
            [assetWriter addInput:assetWriterVideoIn];
        else {
            NSLog(@"Couldn't add asset writer video input.");
            return NO;
        }
    }
    else {
        NSLog(@"Couldn't apply video output settings.");
        return NO;
    }

    return YES;
}
//视频编写器初始化
-(BOOL)setupAssetWriterForURL:(CMFormatDescriptionRef)formatDescription
{
浮动比特像素;
CMVideoDimensions dimensions=CMVideoFormatDescriptionGetDimensions(formatDescription);
int numPixels=dimensions.width*dimensions.height;
int比特秒;
如果(像素<(640*480))
bitsPerPixel=4.05;
其他的
bitsPerPixel=11.4;
bitsPerSecond=numPixels*bitsPerPixel;
NSDictionary*videoCompressionSettings=[NSDictionary Dictionary WithObjectsAndKeys:
AVVideoCodecH264,AVVideoCodeKey,
[NSNumber numberWithInteger:dimensions.width],AVVideoWidthKey,
[NSNumber NUMBER WITHINTEGER:尺寸.高度]、AVVIDEO高度键、,
[NSDictionary Dictionary WithObjects和Keys:
[NSNumber numberWithInteger:bitsPerSecond],AVVideoAverageBitRateKey,
[NSNumber numberWithInteger:30],AVVideoMaxKeyFrameIntervalKey,
无],AVVideoCompressionProperties键,
零];
if([assetWriter可以应用输出设置:视频压缩设置forMediaType:AVMEDIATYPE视频]){
assetWriterVideoIn=[[AVAssetWriterInput alloc]initWithMediaType:AvMediaType视频输出设置:视频压缩设置];
assetWriterVideoIn.expectsMediaDataInRealTime=是;
assetWriterVideoIn.transform=[self TransformfromCurrentVideoOrientation:self.referenceOrientation];
if([assetWriter CanadInput:assetWriterVideoIn])
[assetWriter附加输入:assetWriterVideoIn];
否则{
NSLog(@“无法添加资产写入程序视频输入”);
返回否;
}
}
否则{
NSLog(@“无法应用视频输出设置”);
返回否;
}
返回YES;
}
阅读视频

- (void)readMovie:(NSURL *)url
{
    AVURLAsset * asset = [AVURLAsset URLAssetWithURL:url options:nil];
    [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:
     ^{
         dispatch_async(dispatch_get_main_queue(),
                        ^{
                            AVAssetTrack * videoTrack = nil;
                            NSArray * tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
                            if ([tracks count] == 1)
                            {
                                videoTrack = [tracks objectAtIndex:0];

                                NSError * error = nil;

                                // _movieReader is a member variable
                                AVAssetReader *movieReader = [[AVAssetReader alloc] initWithAsset:asset error:&error];
                                if (error)
                                    NSLog(@"_movieReader fail!\n");

                                NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
                                NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
                                NSDictionary* videoSettings = 
                                [NSDictionary dictionaryWithObject:value forKey:key]; 

                                [movieReader addOutput:[AVAssetReaderTrackOutput 
                                                         assetReaderTrackOutputWithTrack:videoTrack 
                                                         outputSettings:videoSettings]];
                                [movieReader startReading];

                                while ([movieReader status] == AVAssetReaderStatusReading)
                                {
                                    AVAssetReaderTrackOutput * output = [movieReader.outputs objectAtIndex:0];
                                    CMSampleBufferRef sampleBuffer = [output copyNextSampleBuffer];
                                    if (sampleBuffer)
                                    {
                                        if ( !assetWriter ) {
                                            outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%llu.mov", NSTemporaryDirectory(), mach_absolute_time()]];

                                            NSError *error = nil;
                                            assetWriter = [[AVAssetWriter alloc] initWithURL:outputURL fileType:(NSString *)kUTTypeQuickTimeMovie error:&error];
                                            if (error)
                                                [self showError:error];


                                            if (assetWriter) {
                                                CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
                                                [self setupAssetWriterForURL:formatDescription];
                                            }
                                        }
                                        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);


                                        CVPixelBufferLockBaseAddress(imageBuffer,0);

                                        int bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
                                        int bufferWidth = CVPixelBufferGetWidth(imageBuffer);
                                        int bufferHeight = CVPixelBufferGetHeight(imageBuffer);
                                        unsigned char *pixel = (unsigned char *)CVPixelBufferGetBaseAddress(imageBuffer);


                                        for( int row = 0; row < bufferHeight; row++ ) {
                                            for( int column = 0; column < bufferWidth; column++ ) {

                                                pixel[0] = (pixel[0]+pixel[1]+pixel[2])/3;
                                                pixel[1] = (pixel[0]+pixel[1]+pixel[2])/3;
                                                pixel[2] = (pixel[0]+pixel[1]+pixel[2])/3;

                                                pixel += 4;
                                            }
                                        }


                                        CVPixelBufferUnlockBaseAddress(imageBuffer,0);

                                        if ( assetWriter ) {
                                            [self writeSampleBuffer:sampleBuffer ofType:AVMediaTypeVideo];
                                        }


                                        CFRelease(sampleBuffer);
                                    }

                                }
                                if (assetWriter) {
                                    [assetWriterVideoIn markAsFinished];
                                    assetWriter = nil;
                                    [assetWriter finishWriting];
                                    assetWriterVideoIn = nil;
                                    assetWriter = nil;

                                    [self saveMovieToCameraRoll];
                                }
                                else {
                                    [self showError:[assetWriter error]];
                                }

                            }
                        });
     }];

}
- (void) writeSampleBuffer:(CMSampleBufferRef)sampleBuffer ofType:(NSString *)mediaType
{
    if ( assetWriter.status == AVAssetWriterStatusUnknown ) {

        if ([assetWriter startWriting]) {
            [assetWriter startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
        }
        else {
            [self showError:[assetWriter error]];
        }
    }

    if ( assetWriter.status == AVAssetWriterStatusWriting ) {

        if (mediaType == AVMediaTypeVideo) {
            if (assetWriterVideoIn.readyForMoreMediaData) {
                if (![assetWriterVideoIn appendSampleBuffer:sampleBuffer]) {
                    [self showError:[assetWriter error]];
                }
            }
        }

    }
}
- (void)saveMovieToCameraRoll
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:outputURL
                                completionBlock:^(NSURL *assetURL, NSError *error) {
                                    if (error){
                                        [self showError:error];
                                    NSLog(@"save fail");
                                }
                                    else
                                    {
                                        [self removeFile:outputURL];
                                        NSLog(@"!!!");
                                    }
                                    });
                                }];
}
- (void)removeFile:(NSURL *)fileURL
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [fileURL path];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSError *error;
        BOOL success = [fileManager removeItemAtPath:filePath error:&error];
        if (!success)
            [self showError:error];
    }
}
-(void)readMovie:(NSURL*)url
{
AVURLAsset*asset=[AVURLAsset UrlAssetTwithUrl:url选项:无];
[asset LoadValuesAsSynchronousLyforkeys:[NSArray arrayWithObject:@“tracks”]completionHandler:
^{
dispatch\u async(dispatch\u get\u main\u queue(),
^{
AVAssetTrack*videoTrack=nil;
NSArray*轨迹=[asset tracksWithMediaType:AVMediaTypeVideo];
如果([轨道计数]==1)
{
videoTrack=[跟踪对象索引:0];
n错误*错误=nil;
//_movieReader是一个成员变量
Avassetrader*movieReader=[[Avassetrader alloc]initWithAsset:asset error:&error];
如果(错误)
NSLog(@“movieReader失败!\n”);
NSString*键=(NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber*值=[NSNumber NUMBERWITHUNSIGNESDINT:kCVPixelFormatType_32BGRA];
NSDictionary*视频设置=
[NSDictionary dictionaryWithObject:value-forKey:key];
[movieReader addOutput:[AvassetraderTrackOutput
AssetTrackerTrackOutputWithTrack:videoTrack
输出设置:视频设置]];
[movieReader Startreding];
while([movieReader status]==AvassetraderStatusReading)
{
AvasseTraderTrackOutput*输出=[movieReader.outputs对象索引:0];
CMSampleBufferRef sampleBuffer=[output copyNextSampleBuffer];
if(采样缓冲区)
{
如果(!assetWriter){
outputURL=[NSURL fileURLWithPath:[NSString stringWithFormat:@“%@/%llu.mov”,NSTemporaryDirectory(),mach_absolute_time()];
n错误*错误=nil;
assetWriter=[[AVAssetWriter alloc]initWithURL:outputURL文件类型:(NSString*)kUTTypeQuickTimeMovie错误:&错误];
如果(错误)
[自动淋浴错误:错误];
if(assetWriter){
CMFormatDescriptionRef formatDescription=CMSampleBufferGetFormatDescription(sampleBuffer);
[self-setupAssetWriterForURL:formatDescription];
}
}
CVImageBufferRef imageBuffer=CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
int bytesPerRow=CVPixelBufferGetBytesPerRow(图像缓冲区);
int bufferWidth=CVPixelBufferGetWidth(imageBuffer);
int bufferHeight=CVPixelBufferGetHeight(imageBuffer);
无符号字符*像素=(u
                            //assetWriter = nil; commented line  
                               [assetWriter finishWriting];
                                assetWriterVideoIn = nil;
                                assetWriter = nil;

                                [self saveMovieToCameraRoll];
                            }`