将NV21字节数据转换为H264格式并获取H264编解码器格式的字节

时间:2019-01-22 09:23:08

标签: android video-streaming h.264 mediacodec

我可以从下面获取NV21字节数据,我想通过UDP端口将字节数据发送到服务器,但是NV21字节数据的大小很大,因此我正在尝试将NV21字节数据转换为H264编解码器格式

   private CameraProxy.CameraDataCallBack callBack = new CameraProxy.CameraDataCallBack() {

        @Override
        public void onDataBack(byte[] data, long length) {


            encode(datam); // it zips to data to H264 codec format

}
};

我正在将H264 frmat保存到数据以使用 encode(datam),但是我无法获得字节格式以通过UDP发送服务器。我该怎么办?

//Video format to H264
private synchronized void encode(byte[] data) {

    ByteBuffer[]  inputBuffers = mMediaCodec.getInputBuffers();
    ByteBuffer[]  outputBuffers = mMediaCodec.getOutputBuffers();

    int inputBufferIndex = mMediaCodec.dequeueInputBuffer(-1);
    if (inputBufferIndex >= 0) {
        ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
        inputBuffer.capacity();
        inputBuffer.clear();
        inputBuffer.put(data);
        mMediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, 1000000, 0);

    } else {
        return;
    }

    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
    Log.i(TAG, "outputBufferIndex-->" + outputBufferIndex);
    do {
        if (outputBufferIndex >= 0) {
            ByteBuffer outBuffer = outputBuffers[outputBufferIndex];
            System.out.println("buffer info-->" + bufferInfo.offset + "--"
                    + bufferInfo.size + "--" + bufferInfo.flags + "--"
                    + bufferInfo.presentationTimeUs);
            byte[] outData = new byte[bufferInfo.size];
            outBuffer.get(outData);
            try {
                if (bufferInfo.offset != 0) {

                    fos.write(outData, bufferInfo.offset, outData.length
                            - bufferInfo.offset);
                } else {
                    fos.write(outData, 0, outData.length);

                }
                fos.flush();
                Log.i(TAG, "out data -- > " + outData.length);
                mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);
                outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo,
                        0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            outputBuffers = mMediaCodec.getOutputBuffers();
        } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            MediaFormat format = mMediaCodec.getOutputFormat();
        }
    } while (outputBufferIndex >= 0);
}

0 个答案:

没有答案