使用MediaCodec和MediaMuxer对视频进行编码和复用

时间:2014-06-01 20:32:02

标签: android video mediacodec mediamuxer

我正在开发一款应用,用于解码视频并替换某些帧并使用MediaMuxerMediaCodec重新编码。该应用程序可以工作,如果我不替换任何帧(1080p视频除外,我在下面解释),但当我这样做时,替换后的帧是像素化的,视频是不连贯的。

此外,当我尝试使用1920x1080视频的应用时,我得到一个奇怪的输出,视频没有显示任何内容,直到我滚动到视频的开头,然后视频开始显示(但同样的问题)在编辑之后提到像素化之前。

以下是我配置编码器的方法:

Video_format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, interval);
Video_format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
Video_format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
Video_format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0);
int color_format=MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar;
Video_format.setInteger(MediaFormat.KEY_COLOR_FORMAT, color_format);

encoder.configure(Video_format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

总而言之,我有两个问题:

1-修改帧后的像素化帧和乱码视频。

2-损坏的1920x1080视频,除非我滚动到开头。

修改

以下是未经编辑的1080p video示例,当我在VLC上播放并在手机上播放不正确时会显示绿屏,除非我滚动开始,现在奇怪地在YouTube上正常工作,除了绿色框架启动

这是一个样本720p video,在开始时编辑了一个绿框,并在编辑后清除了像素化和延迟

以下是我用来解码重新编码的代码:

do{
  Bitmap b1;

  if(edited_frames.containsKey(extractor.getSampleTime()))
    b1=BitmapFactory.decodeFile(edited_frames.get(extractor.getSampleTime()));
  else
    b1=decode(extractor.getSampleTime(),Preview_width,Preview_Height);

  if(b1==null) continue;

  Bitmap b_scal=Bitmap.createScaledBitmap(b1, Preview_width, Preview_Height, false);
  if(b_scal==null) continue;
  encode(b_scal, encoder, muxer, videoTrackIndex);
  lastTime=extractor.getSampleTime();
}while(extractor.advance());

解码方法:

private Bitmap decode(final long time,final int width,final int height){
  MediaFormat newFormat = codec.getOutputFormat();
  Bitmap b = null;
  final int TIMEOUT_USEC = 10000;
  ByteBuffer[] decoderInputBuffers = codec.getInputBuffers();
  MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();

  boolean outputDone = false;
  boolean inputDone = false;
  while (!outputDone) {
    if (!inputDone) {
      int inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_USEC);
      if (inputBufIndex >= 0) {
        ByteBuffer inputBuf = decoderInputBuffers[inputBufIndex];

        int chunkSize = extractor.readSampleData(inputBuf, 0);
        if (chunkSize < 0) {
          codec.queueInputBuffer(inputBufIndex, 0, 0, 0L, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
          inputDone = true;
        } else {
          long presentationTimeUs = extractor.getSampleTime();
          codec.queueInputBuffer(inputBufIndex, 0, chunkSize, presentationTimeUs, 0 );
        }
        inputBuf.clear();
        decoderInputBuffers[inputBufIndex].clear();
      } else {
      }
    }
    ByteBuffer[] outputBuffers;
    if (!outputDone) {
      int decoderStatus = codec.dequeueOutputBuffer(info, TIMEOUT_USEC);
      if (decoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
      } else if (decoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
        outputBuffers = codec.getOutputBuffers();
      } else if (decoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
        newFormat = codec.getOutputFormat();
      } else if (decoderStatus < 0) {
      } else { 
        if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
          outputDone = true;
        }

        boolean doRender = (info.size != 0);

        codec.releaseOutputBuffer(decoderStatus, false);
        if (doRender) {
          outputBuffers = codec.getOutputBuffers();
          ByteBuffer buffer = outputBuffers[decoderStatus];
          buffer = outputBuffers[decoderStatus];

          outputDone = true;

          byte[] outData = new byte[info.size];
          buffer.get(outData);
          buffer.clear();
          outputBuffers[decoderStatus].clear();
          try {
            int colr_format=-1;
            if(newFormat!=null && newFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT)==21){
              colr_format=ImageFormat.NV21;
            }else if(newFormat!=null && newFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT)!=21){            
              Toast.makeText(getApplicationContext(), "Unknown color format "+format.getInteger(MediaFormat.KEY_COLOR_FORMAT), Toast.LENGTH_LONG).show();
              finish();
              return null;
            }

            int[] arrrr=new int[format.getInteger(MediaFormat.KEY_WIDTH)* format.getInteger(MediaFormat.KEY_HEIGHT)];
            YUV_NV21_TO_RGB(arrrr, outData, format.getInteger(MediaFormat.KEY_WIDTH), format.getInteger(MediaFormat.KEY_HEIGHT));

            lastPresentationTimeUs = info.presentationTimeUs;

            b = Bitmap.createBitmap(arrrr, format.getInteger(MediaFormat.KEY_WIDTH), format.getInteger(MediaFormat.KEY_HEIGHT), Bitmap.Config.ARGB_8888);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  return b;
}

这是编码方法:

private void encode(Bitmap b, MediaCodec encoder, MediaMuxer muxer, int track_indx){
  MediaCodec.BufferInfo enc_info = new MediaCodec.BufferInfo();
  boolean enc_outputDone = false;
  boolean enc_inputDone = false;

  final int TIMEOUT_USEC = 10000;

  ByteBuffer[] encoderInputBuffers = encoder.getInputBuffers();
  ByteBuffer[] enc_outputBuffers = encoder.getOutputBuffers();

  while (!enc_outputDone) {
    if (!enc_inputDone) {
      int inputBufIndex = encoder.dequeueInputBuffer(TIMEOUT_USEC);
      if (inputBufIndex >= 0) {
        ByteBuffer inputBuf = encoderInputBuffers[inputBufIndex];
        int chunkSize = 0;

        if(b==null){
        }else{
          int mWidth = b.getWidth();
          int mHeight = b.getHeight();

          byte [] yuv = new byte[mWidth*mHeight*3/2];
          int [] argb = new int[mWidth * mHeight];

          b.getPixels(argb, 0, mWidth, 0, 0, mWidth, mHeight);
          encodeYUV420SP(yuv, argb, mWidth, mHeight);

          b.recycle();
          b=null;
          inputBuf.put(yuv);
          chunkSize = yuv.length;
        }

        if (chunkSize < 0) {
          encoder.queueInputBuffer(inputBufIndex, 0, 0, 0L,
                            MediaCodec.BUFFER_FLAG_END_OF_STREAM);
        } else {
          long presentationTimeUs = extractor.getSampleTime();
          Log.i("Encode","Encode Time: "+presentationTimeUs);
          encoder.queueInputBuffer(inputBufIndex, 0, chunkSize, presentationTimeUs, 0);
          inputBuf.clear();

          encoderInputBuffers[inputBufIndex].clear();
          enc_inputDone=true;
        }
      }
    }
    if (!enc_outputDone) {
      int enc_decoderStatus = encoder.dequeueOutputBuffer(enc_info, TIMEOUT_USEC);
      if (enc_decoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
      } else if (enc_decoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
        enc_outputBuffers = encoder.getOutputBuffers();
      } else if (enc_decoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
        MediaFormat newFormat = encoder.getOutputFormat();
      } else if (enc_decoderStatus < 0) {
      } else { 
        if ((enc_info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
          enc_outputDone = true;
      }

      boolean enc_doRender = (enc_info.size != 0);
      encoder.releaseOutputBuffer(enc_decoderStatus, false);
      if (enc_doRender) {
        enc_outputDone = true;
        ByteBuffer enc_buffer = enc_outputBuffers[enc_decoderStatus];

        try {
          muxer.writeSampleData(track_indx, enc_buffer, enc_info);
        } catch (Exception e) {
          e.printStackTrace();
        }
        enc_buffer.clear();
        enc_outputBuffers[enc_decoderStatus].clear();
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

像素化很可能是由于错误的帧时间戳造成的,因此请确保帧的时间戳单调增加,并且在将它们传递给MediaCodec和MediaMuxer时是相同的。在这种特定情况下,您只需要替换要替换的帧的数据,并保留原始流中的时间戳。

确保将位图转换为YUV颜色空间,并使用正确的像素格式。 Android在RGBA中存储每个像素4个字节的位图,你需要将其转换为YUV,每个像素的Y值和2x2的块的U和V值,然后将它们放在进入的字节数组的不同平面中。编解码器。

此外,前段时间我制作了一个使用MediaCodec调整视频大小的示例应用,它也可以为您提供帮助:https://github.com/grishka/android-video-transcoder