Search code examples
androidrotationandroid-mediacodec

Android Rotate Surface created using MediaCodec


I am using Camera2 APIs to capture video from the Camera. I understand that we need to rotate the preview as Camera2 does not have an equivalent of setDisplayOrientation(). Able to rotate preview using a Matrix.

I am also using the MediaCodec APIs to encode the video. The encoded video however is inverted when I rotate the phone 180 degrees. I am out of ideas on how to rotate the encoded video.

I tried KEY_ROTATION in MediaFormat while configuring. But I guess this is only while decoding (Output surface).

Thank you!!


Solution

  • Camera2 doesn't directly matter here - you can use MediaRecorder if you want with camera2, via MediaRecorder.getSurface() and the MediaRecoder.setOrientationHint() method to set the desired orientation.

    If you're using MediaCodec instead of MediaRecorder, then there's no orientation flag there; the corresponding method is MediaMuxer.setOrientationHint, since all MediaRecoder does is write the requested orientation into the video file metadata; the actual frames are not generally rotated by the encoder.

    If you're not wrapping the encoded buffers into a video file, but instead consuming them in some other way (network transmission for video chat, etc), you need to pass the orientation along with the encoded frames and apply the transform in the receiving end yourself.