硬解碼播放器上如何實現截GIF功能?

如今主流的播放器都提供了錄製GIF圖的功能。GIF圖就是將一幀幀連續的圖像連續的展現出來,造成動畫。因此生成GIF圖能夠分紅兩步,首先要獲取一組連續的圖像,第二步是將這組圖像合成一個GIF文件。關於GIF文件合成,網絡上有不少開源的工具類。咱們今天主要來看下如何從播放器中獲取一組截圖。話很少說先了解下視頻播放的流程。 android

播放流程

1.一、解碼後從圖像幀池中獲取圖像幀數據

從上面流程圖中能夠看出,截圖只須要獲取解碼後的圖像幀數據便可,即從圖像幀池中拿出指定幀圖像就行了。當咱們使用FFmpeg軟解碼播放時,圖像幀池在咱們本身的代碼裏,因此咱們能夠拿到任意幀。可是但咱們使用系統MediaCodec接口硬解碼播放視頻時,視頻解碼都是系統的MediaCodec模塊來作的,若是咱們想要從MediaCodec裏拿出圖像幀數據來就得研究MediaCodec的接口了。bash

MediaCodec

MediaCodec的工做流程如上圖所示。MediaCodec類是Android底層多媒體框架的一部分,它用來訪問底層編解碼組件,一般與MediaExtractor、MediaSync、Image、Surface和AudioTrack等類一塊兒使用。網絡

簡單的說,編解碼器(Codec)的功能就是把輸入的原始數據處理成可用的輸出數據。它使用一組input buffer和一組output buffer來異步的處理數據。一個簡單的數據處理流程大體分三步:框架

  1. MediaCodec獲取一個input buffer,而後把從數據源中拆包出來的原始數據填到這個input buffer中;
  2. 把填滿原始數據的input buffer送到MediaCodec中,MediaCodec會將這些原始數據解碼成圖像幀數據,並將這些圖像幀數據放入到output buffer中;
  3. MediaCodec中獲取一個有可用圖像幀數據output buffer,而後能夠將output buffer輸出到surface或者bitmap中就能夠渲染到屏幕或者保存在圖片文件中了。
MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, mWidth, mHeight);
String mime = format.getString(MediaFormat.KEY_MIME);

// 建立視頻解碼器,配置解碼器
MediaCodec mVideoDecoder = MediaCodec.createDecoderByType(mime);
mVideoDecoder.configure(format, surface, null, 0);

// 一、獲取input buffer,將原始視頻數據包塞到input buffer中
int inputBufferIndex = mVideoDecoder.dequeueInputBuffer(50000);
ByteBuffer buffer = mVideoDecoder.getInputBuffer(inputBufferIndex);

// 二、將帶有原始視頻數據的input buffer送到MediaCodec中解碼,解碼數據會放置到output buffer中
mVideoDecoder.queueInputBuffer(mVideoBufferIndex, 0, size, presentationTime, 0);

// 三、獲取帶有視頻幀數據的output buffer,釋放output buffer時會將數據渲染到在配置解碼器時設置的surface上
int outputBufferIndex = mVideoDecoder.dequeueOutputBuffer(info, 10000);
mVideoDecoder.releaseOutputBuffer(outputBufferIndex, render);
複製代碼

上面是使用MediaCodec播放視頻的基本流程。咱們的目標是在這個播放過程當中獲取到一幀視頻圖片。從上面的過程能夠看到在獲取視頻幀數據的output buffer方法dequeueOutputBuffer返回的不是一個buffer對象,而只是一個buffer序列號,渲染時只將這個outputBufferIndex傳遞給MediaCodecMediaCodec就會將對應index的渲染到初始配置是設置的surface中。要實現截圖就得獲取到output buffer的數據,咱們如今須要的一個經過outputBufferIndex獲取到output buffer方法。看了下MediaCodec的接口還真有這樣的方法,詳細以下:異步

/**
 * Returns a read-only ByteBuffer for a dequeued output buffer
 * index. The position and limit of the returned buffer are set
 * to the valid output data.
 *
 * After calling this method, any ByteBuffer or Image object
 * previously returned for the same output index MUST no longer
 * be used.
 *
 * @param index The index of a client-owned output buffer previously
 *              returned from a call to {@link #dequeueOutputBuffer},
 *              or received via an onOutputBufferAvailable callback.
 *
 * @return the output buffer, or null if the index is not a dequeued
 * output buffer, or the codec is configured with an output surface.
 *
 * @throws IllegalStateException if not in the Executing state.
 * @throws MediaCodec.CodecException upon codec error.
 */
@Nullable
public ByteBuffer getOutputBuffer(int index) {
    ByteBuffer newBuffer = getBuffer(false /* input */, index);
    synchronized(mBufferLock) {
        invalidateByteBuffer(mCachedOutputBuffers, index);
        mDequeuedOutputBuffers.put(index, newBuffer);
    }
    return newBuffer;
}
複製代碼

注意接口文檔對返回值的描述 return the output buffer, or null if the index is not a dequeued output buffer, or the codec is configured with an output surface. 也就是說若是咱們在初始化MediaCodec時設置了surface,那麼咱們經過這個接口獲取到的output buffer都是null。緣由是當咱們給MediaCodec時設置了surface做爲數據輸出對象時,output buffer直接使用的是native buffer沒有將數據映射或者拷貝到ByteBuffer中,這樣會使圖像渲染更加高效。播放器主要的最主要的功能仍是要播放,因此設置surface是必須的,那麼在拿不到放置解碼後視頻幀數據的ByteBuffer的狀況下,咱們改怎麼實現截圖功能呢?ide

1.二、渲染後從View中獲取圖像幀數據

這時咱們轉換思路,既然硬解碼後的圖像幀數據不方便獲取(方案1),那麼咱們能不能等到圖像幀數據渲染到View上後再從View中去獲取數據呢(方案2)? 工具

截圖方案
咱們視頻播放器使用的 SurfaceVIew + MediaCodec的方式來實現的。那咱們來調研下從 SurfaceVIew 中獲取圖像的技術實現。而後咱們就有了這篇文章 《爲啥從SurfaceView中獲取不到圖片?》。結束就是從 SurfaceView沒法獲取到渲染出來的圖像。爲了獲取視頻截圖咱們換用 TextureView + MediaCodec的方式來實現播放。從 TextureView中獲取當前顯示幀圖像方法以下。

/**
 * <p>Returns a {@link android.graphics.Bitmap} representation of the content
 * of the associated surface texture. If the surface texture is not available,
 * this method returns null.</p>
 *
 * <p>The bitmap returned by this method uses the {@link Bitmap.Config#ARGB_8888}
 * pixel format.</p>
 *
 * <p><strong>Do not</strong> invoke this method from a drawing method
 * ({@link #onDraw(android.graphics.Canvas)} for instance).</p>
 *
 * <p>If an error occurs during the copy, an empty bitmap will be returned.</p>
 *
 * @param width The width of the bitmap to create
 * @param height The height of the bitmap to create
 *
 * @return A valid {@link Bitmap.Config#ARGB_8888} bitmap, or null if the surface
 *         texture is not available or width is &lt;= 0 or height is &lt;= 0
 *
 * @see #isAvailable()
 * @see #getBitmap(android.graphics.Bitmap)
 * @see #getBitmap()
 */
public Bitmap getBitmap(int width, int height) {
    if (isAvailable() && width > 0 && height > 0) {
        return getBitmap(Bitmap.createBitmap(getResources().getDisplayMetrics(),
                width, height, Bitmap.Config.ARGB_8888));
    }
    return null;
}
複製代碼

到目前爲止完成了一小步,實現了從播放器中獲取一張圖像的功能。接下來咱們看下如何獲取一組圖像。動畫

1.3 獲取一組連續的圖像

單張圖像都獲取成功了,獲取多張圖像還難嗎?因爲咱們獲取圖片的方式是等到圖像在View中渲染出來後再從View中獲取的。那麼問題來了,如要生成一張播放時長爲5s的GIF,收集這組圖像是否是真的得持續5s,讓5s內全部數據都在View上渲染了一次才能收集到呢?這種體驗確定是不容許的,爲此咱們使用相似倍速播放的功能,讓5s內的圖像數據快速的在View上渲染一遍,以此來快速的獲取5s類的圖像數據。ui

if (isScreenShot) {
    // GIF圖不須要全部幀數據,定義每秒5張,那麼每200ms渲染一幀數據便可
    render = (info.presentationTimeUs - lastFrameTimeMs) > 200;
}else{
    // 同步音頻的時間
    render = mediaPlayer.get_sync_info(info.presentationTimeUs) != 0;
}

if (render) {
    lastFrameTimeMs = info.presentationTimeUs;
}

mVideoDecoder.releaseOutputBuffer(mVideoBufferIndex, render);
複製代碼

如上述代碼所示,在截圖模式下圖像渲染不在與音頻同步,這樣就實現了圖像快速渲染。另外就是GIF圖每秒只有幾張圖而已,這裏定義是5張,那麼只須要從視頻源的每秒30幀數據中選出5張圖渲染出來便可。這樣咱們就快速的獲取到了5s的圖像數據。this

獲取到所需的圖像數據之後,剩下的就是合成GIF文件了。那這樣就實現了在使用MediaCodec硬解碼播放視頻的狀況下生成GIF圖的需求。

相關文章
相關標籤/搜索