Skip to content

Instantly share code, notes, and snippets.

@luca-bernardi
Created February 23, 2013 18:12
Show Gist options
  • Save luca-bernardi/5020724 to your computer and use it in GitHub Desktop.
Save luca-bernardi/5020724 to your computer and use it in GitHub Desktop.
Find the video orientation of an AVAsset. (Useful if you need to send the video to a remote server)
//
// AVAsset+VideoOrientation.h
//
// Created by Luca Bernardi on 19/09/12.
// Copyright (c) 2012 Luca Bernardi. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
typedef enum {
LBVideoOrientationUp, //Device starts recording in Portrait
LBVideoOrientationDown, //Device starts recording in Portrait upside down
LBVideoOrientationLeft, //Device Landscape Left (home button on the left side)
LBVideoOrientationRight, //Device Landscape Right (home button on the Right side)
LBVideoOrientationNotFound = 99 //An Error occurred or AVAsset doesn't contains video track
} LBVideoOrientation;
@interface AVAsset (VideoOrientation)
/**
Returns a LBVideoOrientation that is the orientation
of the iPhone / iPad whent starst recording
@return A LBVideoOrientation that is the orientation of the video
*/
@property (nonatomic, readonly) LBVideoOrientation videoOrientation;
@end
//
// AVAsset+VideoOrientation.m
//
// Created by Luca Bernardi on 19/09/12.
// Copyright (c) 2012 Luca Bernardi. All rights reserved.
//
#import "AVAsset+VideoOrientation.h"
static inline CGFloat RadiansToDegrees(CGFloat radians) {
return radians * 180 / M_PI;
};
@implementation AVAsset (VideoOrientation)
@dynamic videoOrientation;
- (LBVideoOrientation)videoOrientation
{
NSArray *videoTracks = [self tracksWithMediaType:AVMediaTypeVideo];
if ([videoTracks count] == 0) {
return LBVideoOrientationNotFound;
}
AVAssetTrack* videoTrack = [videoTracks objectAtIndex:0];
CGAffineTransform txf = [videoTrack preferredTransform];
CGFloat videoAngleInDegree = RadiansToDegrees(atan2(txf.b, txf.a));
LBVideoOrientation orientation = 0;
switch ((int)videoAngleInDegree) {
case 0:
orientation = LBVideoOrientationRight;
break;
case 90:
orientation = LBVideoOrientationUp;
break;
case 180:
orientation = LBVideoOrientationLeft;
break;
case -90:
orientation = LBVideoOrientationDown;
break;
default:
orientation = LBVideoOrientationNotFound;
break;
}
return orientation;
}
@end
@danoli3
Copy link

danoli3 commented Mar 28, 2014

I love you!

@andrei4002
Copy link

awesome, thank you!!!

@ivanlesko
Copy link

works like a charm

@stayHF
Copy link

stayHF commented Apr 28, 2017

very good!

@Sumit-2singh
Copy link

this is not working with Time-Lapse

@wvdk
Copy link

wvdk commented Jan 7, 2019

@svanichkin
Copy link

not working for Time-Lapse and some vertical video

@heistings
Copy link

There must be some bugs if the video is from screen recording.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment