Usama Usama - 1 month ago 7
iOS Question

How to get correct Orientation for videos from PhotoLibrary iOS

I am trying to implement Instagram video cropping feature. For that i need to get correct orientation of the video with which i will layout my

MPMoviePlayerController
view in correct aspect ratio and user will then be able to pan the video and shown square video will be cropped on action.

I am having problem with getting correct orientation of the video. I am using following code

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileUrl options:nil];
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *track = [tracks objectAtIndex:0];
UIInterfaceOrientation orientation =[self orientationForTrack:track];

// method to get orientation
- (UIInterfaceOrientation)orientationForTrack:(AVAssetTrack *)videoTrack
{
CGSize size = [videoTrack naturalSize];
CGAffineTransform txf = [videoTrack preferredTransform];

if (size.width == txf.tx && size.height == txf.ty)
return UIInterfaceOrientationLandscapeRight;
else if (txf.tx == 0 && txf.ty == 0)
return UIInterfaceOrientationLandscapeLeft;
else if (txf.tx == 0 && txf.ty == size.width)
return UIInterfaceOrientationPortraitUpsideDown;
else
return UIInterfaceOrientationUnknown;
}


Problem which i am having is that some times the videos which are actually in portrait, above piece of code is classifying it as landscape and vice versa. I only need to know two states of video's orientation (Landscape or Portrait). I want exact same orientation value which
MPMoviePlayerController
is interpreting. My application only supports Portrait orientation. Any help would be highly appreciated.

PS: Above code is working fine for videos which are captured from iphone camera, videos which are downloaded or shared through the whatsapp are causing the problem.

Answer

Only way which solved this issue for me is to capture thumbnail image from the video using method:

- (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes timeOption:(MPMovieTimeOption)option

and then adding check on the thumbnail image like :

if (singleFrameImage.size.height > singleFrameImage.size.width) {
    // potrait video
} else {
    // landscape
}

This solution is tested on videos captured from iPhone camera and also on a set (8-10) of videos randomly downloaded from internet.