Skip to content

Commit

Permalink
center video inside target
Browse files Browse the repository at this point in the history
  • Loading branch information
koush committed Feb 7, 2015
1 parent 988b6f1 commit 57c71f7
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions SDAVAssetExportSession.m
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ - (void)exportAsynchronouslyWithCompletionHandler:(void (^)())handler
{
duration = CMTimeGetSeconds(self.asset.duration);
}

//
// Video output
//
Expand Down Expand Up @@ -306,16 +305,41 @@ - (AVMutableVideoComposition *)buildDefaultVideoComposition
trackFrameRate = 30;
}

videoComposition.frameDuration = CMTimeMake(1, trackFrameRate);
videoComposition.renderSize = [videoTrack naturalSize];
videoComposition.frameDuration = CMTimeMake(1, trackFrameRate);
CGSize targetSize = CGSizeMake([self.videoSettings[AVVideoWidthKey] floatValue], [self.videoSettings[AVVideoHeightKey] floatValue]);
CGSize naturalSize = [videoTrack naturalSize];
CGAffineTransform transform = videoTrack.preferredTransform;
CGFloat videoAngleInDegree = atan2(transform.b, transform.a) * 180 / M_PI;
if (videoAngleInDegree == 90 || videoAngleInDegree == 270) {
CGFloat width = naturalSize.width;
naturalSize.width = naturalSize.height;
naturalSize.height = width;
}
videoComposition.renderSize = naturalSize;
// center inside
{
float ratio;
float xratio = targetSize.width / naturalSize.width;
float yratio = targetSize.height / naturalSize.height;
ratio = MIN(xratio, yratio);

float postWidth = naturalSize.width * ratio;
float postHeight = naturalSize.height * ratio;
float transx = (targetSize.width - postWidth) / 2;
float transy = (targetSize.height - postHeight) / 2;

CGAffineTransform matrix = CGAffineTransformMakeTranslation(transx / xratio, transy / yratio);
matrix = CGAffineTransformScale(matrix, ratio / xratio, ratio / yratio);
transform = CGAffineTransformConcat(transform, matrix);
}

// Make a "pass through video track" video composition.
AVMutableVideoCompositionInstruction *passThroughInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
passThroughInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, self.asset.duration);

AVMutableVideoCompositionLayerInstruction *passThroughLayer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];

[passThroughLayer setTransform:videoTrack.preferredTransform atTime:kCMTimeZero];
[passThroughLayer setTransform:transform atTime:kCMTimeZero];

passThroughInstruction.layerInstructions = @[passThroughLayer];
videoComposition.instructions = @[passThroughInstruction];
Expand Down

0 comments on commit 57c71f7

Please sign in to comment.