How can I ensure correct playback orientation of recorded video?

Jeff Axelrod picture Jeff Axelrod · Sep 9, 2012 · Viewed 7.1k times · Source

I'm using the MediaStore.ACTION_VIDEO_CAPTURE intent to capture video and later play it back using a VideoView. I would like to know the orientation of the video that was captured.

I don't want to use the orientation at the time of the intent call because the user may rotate the device prior to hitting the shutter button. I also don't want to implement my own custom video capture.

Is the orientation of the video stored in the saved file and/or returned in the intent result?

Answer

Joe picture Joe · Sep 14, 2012

Is the orientation of the video stored in the saved file and/or returned in the intent result?

The AOSP VideoCamera activity does supply the rotation value of the camera device to the MediaRecorder.setOrientationHint() method. Here's an excerpt of the code in the VideoCamera.initializeRecorder() code related to this:

    // See android.hardware.Camera.Parameters.setRotation for
    // documentation.
    // Note that mOrientation here is the device orientation, which is 
    // the opposite of what getWindowManager().getDefaultDisplay().getRotation() 
    // would return, which is the orientation the graphics need to rotate 
    // in order to render correctly.
    int rotation = 0;
    if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
        CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            rotation = (info.orientation - mOrientation + 360) % 360;
        } else {  // back-facing camera
            rotation = (info.orientation + mOrientation) % 360;
        }
    }
    mMediaRecorder.setOrientationHint(rotation);

Here's the documentation for setOrientationHint() explaining the storage of the information:

Sets the orientation hint for output video playback. This method should be called before prepare(). This method will not trigger the source video frame to rotate during video recording, but to add a composition matrix containing the rotation angle in the output video if the output format is OutputFormat.THREE_GPP or OutputFormat.MPEG_4 so that a video player can choose the proper orientation for playback. Note that some video players may choose to ignore the compostion matrix in a video during playback.

Since you are using the framework's VideoView widget to playback the video, it should already handle the information in the composition matrix correctly and you should only need to compare the width and height of the video to decide whether to set a landscape or portrait orientation for your playback activity. One simple way to do this would be to just call ThumbnailUtils.createVideoThumbnail() (which internally uses MediaMetaDataRetriever) and check the resolution of the returned bitmap.