我目前正在尝试从RTP流解析H264数据,然后将其发送到MediaCodec以在SurfaceView for Android上呈现。
但是,我不确定如何:
我没有看到任何以简洁明了的方式实现的例子,我还没有发现MediaCodec文档对我们有所帮助。
任何人都有此领域的经验吗?
void videoCodec(ByteBuffer input, int flags) {
bufferInfo.set(0, 0, 0, flags);
int inputBufferId = codec.dequeueInputBuffer(10000);
if (inputBufferId >= 0) {
//put data
ByteBuffer inputData = inputBuffers[inputBufferId];
inputData.clear();
inputData.put(input);
//queue it up
codec.queueInputBuffer(inputBufferId, 0, input.limit(), 0, flags);
}
int outputBufferId = codec.dequeueOutputBuffer(bufferInfo, 10000);
if (outputBufferId >= 0) {
// outputBuffers[outputBufferId] is ready to be processed or rendered.
Timber.e("Rendering Data with Index of: %s", outputBufferId);
codec.releaseOutputBuffer(outputBufferId, true);
} else if (outputBufferId == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
outputBuffers = codec.getOutputBuffers();
} else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// Subsequent data will conform to new format.
//format = codec.getOutputFormat();
}
}
MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1920, 1080);
codec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
codec.configure(format, surfaceVideo.getHolder().getSurface(), null, 0);
codec.start();
inputBuffers = codec.getInputBuffers();
outputBuffers = codec.getOutputBuffers();
while (streaming) {
//receive RTP Packet
h264Parser(rtpPacket.getPayload());
}
h264Parser看起来像这样:
void h264Parser(byte[] payload) {
int packetType = (byte) payload[0] & (byte) 0x1F;
boolean startBit = (payload[1] & 0x80) != 0;
boolean endBit = (payload[1] & 0x40) != 0;
int flags = 0;
switch (packetType) {
case 7:
pps = new ByteArrayOutputStream();
pps.write(prefix);
pps.write(payload);
break;
case 8:
if (pps.size() > 0) {
pps.write(payload);
hasPps = true;
flags = MediaCodec.BUFFER_FLAG_CODEC_CONFIG;
payload = pps.toByteArray();
//Send packet to decoder
videoCodec(ByteBuffer.wrap(payload), flags);
break;
case 28:
if (hasPps) {
if (startBit) {
baos = new ByteArrayOutputStream();
baos.write(prefix);
baos.write(payload);
} else if (endBit) {
if(baos != null) {
baos.write(payload);
flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
payload = baos.toByteArray();
//Send packet to decoder
videoCodec(ByteBuffer.wrap(payload), flags);
hasPps = false;
} else {
if(baos != null ) {
baos.write(payload);
}
}
}
break;
case 1:
break;
default:
}
答案 0 :(得分:1)
据我所知,MediaCodec使用完整的访问单位,不仅是切片(有人纠正了我的错误)
所以你必须从RTP构建一个完整的访问单元并将其提供给解码器(遗憾的是我没有RTP经验,也无法帮助你构建一个)。
您将访问单元发送到解码器,如下所示:
将输入缓冲区出列
int inputBufferIndex = decoder.dequeueInputBuffer(TIMEOUT_USEC);
ByteBuffer inputBuffer = videoDecoderInputBuffers[videoInputBufIndex];
使用您的访问单元填写
inputBuffer.put(acessUnit);
inputBuffer.flip();
将缓冲区排队以进行解码
decoder.queueInputBuffer(inputBufferIndex,0,inputBuffer.limit(), 0, FLAGS);
我希望这有点帮助