当前位置:   article > 正文

Android 音视频深入 五 Android原生API完美的录视频(附源码下载)_android can't write, muxer is not started

android can't write, muxer is not started
本篇项目地址,求star

https://github.com/979451341/Audio-and-video-learning-materials/tree/master/%E5%BD%95%E8%A7%86%E9%A2%91

这一次的代码录视频在各个播放器都可以用,有时长显示,对比上一次的代码说说为何两者效果不同,但是我先补充一些之前漏掉的MediaCodec的官方说明还有MediaCodec.BufferInfo

1.MediaCodec的补充


buffer_flag_codec_config:提示标志等含有编码初始化/编解码器的具体数据,而不是媒体数据缓冲区。

buffer_flag_end_of_stream:这个信号流的结束

buffer_flag_sync_frame提:包含数据的同步帧缓冲区。

info_output_buffers_changed:输出缓冲区发生了变化,客户必须向输出缓冲区新设置的返回getoutputbuffers()这一点上。

info_output_format_changed:输出格式发生了变化,随后的数据将按照新格式。

info_try_again_later:表明呼叫超时,超时时调用dequeueoutputbuffer

dequeueInputBuffer(long timeoutUs):返回输入缓冲区的索引以填充有效数据或-如果当前没有这样的缓冲区,则返回1。

dequeueOutputBuffer(MediaCodec.BufferInfo info, long timeoutUs):将输出缓冲器,挡住了timeoutUs微妙

flush():刷新输入和输出端口的组件,所有指标以前返回调用dequeueinputbuffer(长)和dequeueoutputbuffer(mediacodec.bufferinfo,长)无效。

mediacodecinfo getcodecinfo():获取编解码器信息。

getinputbuffers():这start()返回后调用。

getoutputbuffers():在start()返回时dequeueoutputbuffer信号输出缓冲的变化通过返回info_output_buffers_changed

mediaformat getoutputformat():这叫dequeueoutputbuffer信号后返回info_output_format_changed格式变化

queueInputBuffer(int index, int offset, int size, long presentationTimeUs, int flags):在指定索引上填充一个输入缓冲区之后,将其提交给组件。


MediaCodec.BufferInfo每个缓冲区元数据包括一个偏移量和大小,指定相关联编解码器缓冲区中有效数据的范围。 我就理解为将缓存区数据写入本地的时候需要做出一些调整的 参数



2.代码对比

不废话直接来看Video编码这部分,首先对比MediaFormat

  1. mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, this.mWidth, this.mHeight);
  2. mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
  3. mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
  4. mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
  5. mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
  6. final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
  7. format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); // API >= 18
  8. format.setInteger(MediaFormat.KEY_BIT_RATE, calcBitRate());
  9. format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
  10. format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);
两者什么宽高视频格式都一样,甚至帧率、采集点大小都一样,只有一个不一样MediaFormat.KEY_COLOR_FORMAT,这个官方说明是:
由用户设置编码器,在解码器的输出格式中可读。

也就是说它能够设置编码器,能设置编码方式,也就是说这个两个工程最大的不同是编码,我们继续对比

  1. private void encodeFrame(byte[] input) {
  2. Log.w(TAG, "VideoEncoderThread.encodeFrame()");
  3. // 将原始的N21数据转为I420
  4. NV21toI420SemiPlanar(input, mFrameData, this.mWidth, this.mHeight);
  5. ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
  6. ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers();
  7. int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
  8. if (inputBufferIndex >= 0) {
  9. ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
  10. inputBuffer.clear();
  11. inputBuffer.put(mFrameData);
  12. mMediaCodec.queueInputBuffer(inputBufferIndex, 0, mFrameData.length, System.nanoTime() / 1000, 0);
  13. } else {
  14. Log.e(TAG, "input buffer not available");
  15. }
  16. —————-省略
  17. }
  18. protected void encode(final ByteBuffer buffer, final int length, final long presentationTimeUs) {
  19. if (!mIsCapturing) return;
  20. final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
  21. while (mIsCapturing) {
  22. final int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
  23. if (inputBufferIndex >= 0) {
  24. final ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
  25. inputBuffer.clear();
  26. if (buffer != null) {
  27. inputBuffer.put(buffer);
  28. }
  29. // if (DEBUG) Log.v(TAG, "encode:queueInputBuffer");
  30. if (length <= 0) {
  31. // send EOS
  32. mIsEOS = true;
  33. if (DEBUG) Log.i(TAG, "send BUFFER_FLAG_END_OF_STREAM");
  34. mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0,
  35. presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
  36. break;
  37. } else {
  38. mMediaCodec.queueInputBuffer(inputBufferIndex, 0, length,
  39. presentationTimeUs, 0);
  40. }
  41. break;
  42. } else if (inputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
  43. // wait for MediaCodec encoder is ready to encode
  44. // nothing to do here because MediaCodec#dequeueInputBuffer(TIMEOUT_USEC)
  45. // will wait for maximum TIMEOUT_USEC(10msec) on each call
  46. }
  47. }
  48. }
一样,说实话没啥不同,只有一个不同那就是第一个编码函数开头用了这个,然后在编码的时候使用了i420bytes,这个i420bytes通过xnv21bytes变换而来
  1. private static void NV21toI420SemiPlanar(byte[] nv21bytes, byte[] i420bytes, int width, int height) {
  2. System.arraycopy(nv21bytes, 0, i420bytes, 0, width * height);
  3. for (int i = width * height; i < nv21bytes.length; i += 2) {
  4. i420bytes[i] = nv21bytes[i + 1];
  5. i420bytes[i + 1] = nv21bytes[i];
  6. }
  7. }
我们再看每一次编码一个帧放入混合器分别是咋搞的,下面这个代码意思是监听编码一帧前后编码器的状态的变化并将编码后的数据放入MP4文件里,然后释放内存

  1. drain();
  2. // request stop recording
  3. signalEndOfInputStream();
  4. // process output data again for EOS signale
  5. drain();
  6. // release all related objects
  7. release();
我们在看看drain()里面说啥,
开头就mMediaCodec.getOutputBuffers输出数据,然后得到编码器的状态,如果超时了就退出当前循环,如果输出缓冲区发生了变化,那就在执行一次mMediaCodec.getOutputBuffers,如果输出格式变化了重新给编码器配置MediaFormat,然后编码器再次加入混合器,状态的值小于0就是不可预料的状态了,既然是不可预料那就没办法了,剩下来的就是正常的状态,配合着BufferInfo将数据写入混合器
  1. protected void drain() {
  2. if (mMediaCodec == null) return;
  3. ByteBuffer[] encoderOutputBuffers = mMediaCodec.getOutputBuffers();
  4. int encoderStatus, count = 0;
  5. final MediaMuxerWrapper muxer = mWeakMuxer.get();
  6. if (muxer == null) {
  7. // throw new NullPointerException("muxer is unexpectedly null");
  8. Log.w(TAG, "muxer is unexpectedly null");
  9. return;
  10. }
  11. LOOP: while (mIsCapturing) {
  12. // get encoded data with maximum timeout duration of TIMEOUT_USEC(=10[msec])
  13. encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
  14. if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
  15. // wait 5 counts(=TIMEOUT_USEC x 5 = 50msec) until data/EOS come
  16. if (!mIsEOS) {
  17. if (++count > 5)
  18. break LOOP; // out of while
  19. }
  20. } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
  21. if (DEBUG) Log.v(TAG, "INFO_OUTPUT_BUFFERS_CHANGED");
  22. // this shoud not come when encoding
  23. encoderOutputBuffers = mMediaCodec.getOutputBuffers();
  24. } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
  25. if (DEBUG) Log.v(TAG, "INFO_OUTPUT_FORMAT_CHANGED");
  26. // this status indicate the output format of codec is changed
  27. // this should come only once before actual encoded data
  28. // but this status never come on Android4.3 or less
  29. // and in that case, you should treat when MediaCodec.BUFFER_FLAG_CODEC_CONFIG come.
  30. if (mMuxerStarted) { // second time request is error
  31. throw new RuntimeException("format changed twice");
  32. }
  33. // get output format from codec and pass them to muxer
  34. // getOutputFormat should be called after INFO_OUTPUT_FORMAT_CHANGED otherwise crash.
  35. final MediaFormat format = mMediaCodec.getOutputFormat(); // API >= 16
  36. mTrackIndex = muxer.addTrack(format);
  37. mMuxerStarted = true;
  38. if (!muxer.start()) {
  39. // we should wait until muxer is ready
  40. synchronized (muxer) {
  41. while (!muxer.isStarted())
  42. try {
  43. muxer.wait(100);
  44. } catch (final InterruptedException e) {
  45. break LOOP;
  46. }
  47. }
  48. }
  49. } else if (encoderStatus < 0) {
  50. // unexpected status
  51. if (DEBUG) Log.w(TAG, "drain:unexpected result from encoder#dequeueOutputBuffer: " + encoderStatus);
  52. } else {
  53. final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
  54. if (encodedData == null) {
  55. // this never should come...may be a MediaCodec internal error
  56. throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
  57. }
  58. if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
  59. // You shoud set output format to muxer here when you target Android4.3 or less
  60. // but MediaCodec#getOutputFormat can not call here(because INFO_OUTPUT_FORMAT_CHANGED don't come yet)
  61. // therefor we should expand and prepare output format from buffer data.
  62. // This sample is for API>=18(>=Android 4.3), just ignore this flag here
  63. if (DEBUG) Log.d(TAG, "drain:BUFFER_FLAG_CODEC_CONFIG");
  64. mBufferInfo.size = 0;
  65. }
  66. if (mBufferInfo.size != 0) {
  67. // encoded data is ready, clear waiting counter
  68. count = 0;
  69. if (!mMuxerStarted) {
  70. // muxer is not ready...this will prrograming failure.
  71. throw new RuntimeException("drain:muxer hasn't started");
  72. }
  73. // write encoded data to muxer(need to adjust presentationTimeUs.
  74. mBufferInfo.presentationTimeUs = getPTSUs();
  75. muxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);
  76. prevOutputPTSUs = mBufferInfo.presentationTimeUs;
  77. }
  78. // return buffer to encoder
  79. mMediaCodec.releaseOutputBuffer(encoderStatus, false);
  80. if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
  81. // when EOS come.
  82. mIsCapturing = false;
  83. break; // out of while
  84. }
  85. }
  86. }
  87. }
打完收工,代码很多,多多抽象理解,重在理解过程,细节。。。。。,自我总结

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/683474
推荐阅读
相关标签
  

闽ICP备14008679号