By referring Aegonis\'s work 1 and work 2, I also got the H.264 stream , but the color is not correct. I am using HTC Butterfly for development. Here is part of my code:
After reading this discussion it turns out that more generalised way for encoding frames
of various resolutions is to align chroma plane by 2048 bytes before sending frame to the MediaCodec
. This is actual for QualComm
(OMX.qcom.video.encoder.avc
) encoder which I believe HTC Butterfly has, but still does not works well for all resolutions. 720x480
and 176x144
are still have chroma plane misaligned according to the output video. Also, avoid resolutions which sizes can't be divided by 16.
The transformation is pretty simple:
int padding = 0;
if (mediaCodecInfo.getName().contains("OMX.qcom")) {
padding = (width * height) % 2048;
}
byte[] inputFrameBuffer = new byte[frame.length];
byte[] inputFrameBufferWithPadding = new byte[padding + frame.length];
ColorHelper.NV21toNV12(frame, inputFrameBuffer, width, height);
# copy Y plane
System.arraycopy(inputFrameBuffer, 0, inputFrameBufferWithPadding, 0, inputFrameBuffer.length);
int offset = width * height;
# copy U and V planes aligned by boundary
System.arraycopy(inputFrameBuffer, offset, inputFrameBufferWithPadding, offset + padding, inputFrameBuffer.length - offset);