4

I am attempting to crop a video I take from within my iOS app, and export it as an mp4. The original video records perfectly, but 50% of the time when I crop the video, there is a black frame in the beginning.

Here is my code.

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:@{AVURLAssetPreferPreciseDurationAndTimingKey:@YES}];

AVMutableComposition *composition = [AVMutableComposition composition];
AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

AVAssetTrack *assetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
CMTime duration = assetTrack.timeRange.duration;
[videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:assetTrack atTime:kCMTimeZero error:nil];

AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
videoComposition.frameDuration = CMTimeMake(1, 30.0);
videoComposition.renderSize = CGSizeMake(videoTrack.naturalSize.height, videoTrack.naturalSize.height);

AVMutableVideoCompositionLayerInstruction *transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
CGAffineTransform t2 = CGAffineTransformRotate(t1, M_PI_2);
[transformer setTransform:t2 atTime:kCMTimeZero];

AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.layerInstructions = @[transformer];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, duration);

videoComposition.instructions = @[instruction];

AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
exporter.videoComposition = videoComposition;
exporter.outputURL = outputURL;
exporter.outputFileType = AVFileTypeMPEG4;

[exporter exportAsynchronouslyWithCompletionHandler:^{
    //Stuff
}];
4
  • 1
    Did you ever find out what the problem was? I'm facing exactly the same issue. Thanks
    – elibud
    Dec 1, 2014 at 17:27
  • @EliBud My issue was actually caused in my recording. I was recording the first frame as audio only. To diagnose, try just recording video without audio and see if you are still having the issue. Dec 1, 2014 at 18:45
  • @JamesPaolantonio long time since this post. But how exactly did you manage to make sure there is no empty frames with audio ? Im using a AVAssetWriterInput and simple appending audio CMSampleBuffers, same with video.
    – omarojo
    Jan 16, 2019 at 22:07
  • @omarojo The issue was a race condition where I was recording audio before a video frame. I added a check to discard any audio before I received video frames. Apr 24, 2019 at 13:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.