首页  编辑  

安卓摄像头视频压缩和推流

Tags: /Android/   Date Created:
安卓下如何对摄像头进行实时视频压缩和推流到RTP服务器?

onPreviewFrame中处理即可:
private NV21Convertor mConvertor;
private MediaCodec mMediaCodec;
private byte[] mPpsSps = new byte[0]; private Camera.CameraInfo cameraInfo;
public void onPreviewFrame(byte[] data, Camera camera) {
                ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers();
byte[] dst = new byte[data.length];
Camera.Size previewSize = m_camera.getParameters().getPreviewSize();
if (cameraInfo.facing == 0) {
dst = Util.rotateNV21Degree90(data, previewSize.width, previewSize.height);
} else {
dst = data;
}
try {
int bufferIndex = mMediaCodec.dequeueInputBuffer(5000000);
if (bufferIndex >= 0) {
inputBuffers[bufferIndex].clear();
mConvertor.convert(dst, inputBuffers[bufferIndex]);
mMediaCodec.queueInputBuffer(bufferIndex, 0,
inputBuffers[bufferIndex].position(),
System.nanoTime() / 1000, 0);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
while (outputBufferIndex >= 0) {
ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
byte[] outData = new byte[bufferInfo.size];
outputBuffer.get(outData);
//记录pps和sps
if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 103) {
mPpsSps = outData;
} else if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 101) {
//在关键帧前面加上pps和sps数据
byte[] iframeData = new byte[mPpsSps.length + outData.length];
System.arraycopy(mPpsSps, 0, iframeData, 0, mPpsSps.length);
System.arraycopy(outData, 0, iframeData, mPpsSps.length, outData.length);
outData = iframeData;
}
//发送实时流
mRtpSenderWrapper.sendAvcPacket(outData, 0, outData.length, 0);
// Util.save(outData, 0, outData.length, path, true);
mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);
outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
}
} else {
Log.e("easypusher", "No buffer available !");
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String stack = sw.toString();
Log.e("save_log", stack);
e.printStackTrace();
} finally {
}