1. 程式人生 > >Android FFmpeg視訊轉碼並儲存到本地

Android FFmpeg視訊轉碼並儲存到本地

本文講述在Android中, 如何將FFmpeg視訊轉碼為YUV格式並儲存到本地。

配置好之後,我們先來明確下概念,FFmpeg解碼的流程是固定的

  1. av_register_all: 註冊所有元件
  2. avformat_open_input : 開啟輸入視訊檔案
  3. avformat_find_stream_info: 獲取視訊檔案資訊
  4. avcodec_find_decoder: 根據編解碼上下文中的編碼id查詢對應的解碼
  5. avcodec_open2: 開啟解碼器
  6. av_read_frame:一幀一幀讀取壓縮資料
  7. avcodec_decode_video2:解碼一幀視訊壓縮資料,得到視訊畫素資料

接著,我們來具體實現

在VideoUtils中新增decode方法

/**
 *
 * @param input 輸入的視訊檔案路徑
 * @param output 輸出的視訊檔案路徑
 */
public native static void decode(String input,String output);  

然後再native-lib.c中實現該方法

JNIEXPORT void JNICALL
Java_com_ethanco_ffmpegtest_VideoUtils_decode(JNIEnv *env, jclass type, jstring input_jstr,
                                              jstring output_jstr) {

}  

獲取輸入和輸出視訊路徑

const char *input_cstr = (*env)->GetStringUTFChars(env, input_jstr, NULL);
const char *output_cstr = (*env)->GetStringUTFChars(env, output_jstr, NULL);  

註冊所有元件

//1.註冊所有元件
av_register_all();
	
//封裝格式上下文,統領全域性的結構體,儲存了視訊檔案封裝格式的相關資訊
AVFormatContext *pFormatCtx = avformat_alloc_context();  

開啟輸入視訊檔案

  //2.開啟輸入視訊檔案
  if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
       LOGE("無法開啟視訊檔案:%s", input_cstr);
       return;
   }

獲取視訊檔案資訊

if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
    LOGE("%s", "無法獲取視訊檔案資訊")
    return;
}  

//獲取視訊流的索引位置
//遍歷所有型別的流 (音訊流、視訊流、字幕流),找到視訊流
int v_stream_idx = -1;
//number of streams
for (int i = 0; i < pFormatCtx->nb_streams; ++i) {
    //流的型別
    if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
        v_stream_idx = i;
        break;
    }
}

if (v_stream_idx == -1) {
    LOGE("%s", "找不到視訊流\n");
    return;
}

//只有知道視訊的編碼方式,才能夠根據編碼方式去找到解碼器
//獲取視訊流中的編碼上下文
AVCodecContext *pCodecCtx = pFormatCtx->streams[v_stream_idx]->codec;

根據編解碼上下文中的編碼id查詢對應的解碼

 AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);

if (pCodec == NULL) {
    //這裡可以臨時下載一個解碼器
    LOGE("%s", "找不到解碼器\n");
    return;
}

開啟解碼器

if (avcodec_open2(pCodecCtx, pCodec, NULL < 0)) {
    LOGE("%s", "解碼器無法開啟\n");
    return;
}  

//準備讀取
//AVPacket用於儲存一幀一幀的壓縮資料 (H264)
//緩衝區,開闢空間
AVPacket *packet = (AVPacket *) av_malloc(sizeof(AVPacket));

//AVFrame用於儲存解碼後的畫素資料(YUV)
//記憶體分配
AVFrame *pFrame = av_frame_alloc();
//YUV420
AVFrame *pFrameYUV = av_frame_alloc();
//只有指定了AVFrame的畫素格式、畫面大小才能真正分配記憶體
//緩衝區分配記憶體
uint8_t *out_buffer = (uint8_t *) av_malloc(
        avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));

//初始化緩衝區
avpicture_fill((AVPicture *) pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width,
               pCodecCtx->height);

//用於轉碼 (縮放) 的引數,轉之前的寬高,轉之後的寬高,格式等
struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
                                            pCodecCtx->pix_fmt,
                                            pCodecCtx->width, pCodecCtx->height,
                                            AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);  

一幀一幀讀取壓縮資料,並進行解碼,得到畫素資料

int got_picture, ret;
FILE *fp_yuv = fopen(output_cstr, "wb+");
int frame_count = 0;

//6.一幀一幀讀取壓縮資料
while (av_read_frame(pFormatCtx, packet) >= 0) {
    //只要視訊壓縮資料 (根據流的索引位置判斷)
    if(packet->stream_index == v_stream_idx){
        //7.解碼一幀視訊壓縮資料,得到視訊畫素資料
        ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
        if(ret < 0){
            LOGE("%s","解碼錯誤");
            return;
        }

        //為0說明解碼完成,非0正在解碼
        if(got_picture){
            //AVFrame轉為畫素格式YUV420,寬高
            //引數2、6:輸入、輸出資料
            //引數3、7:輸入、輸出畫面一行的資料大小 AVFrame轉換是一行一行轉換的
            //引數4:輸入資料第一列要轉碼的位置 從0開始
            //引數5:輸入畫面的高度
            sws_scale(sws_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                      pFrameYUV->data, pFrameYUV->linesize);

            //輸出到YUV檔案
            //AVFrame畫素幀寫入檔案
            //data解碼後的影象畫素資料 (音訊取樣資料)
            //Y 亮度 U 色度 (壓縮了) 人對亮度更加敏感
            //U V 個數是Y的1/4
            int y_size = pCodecCtx->width * pCodecCtx->height;
            fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv); //Y
            fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv); //U
            fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv); //V

            frame_count++;
            LOGI("解碼第%d幀",frame_count);
        }
    }

    //釋放資源
    av_free_packet(packet);
}

釋放資源

fclose(fp_yuv);

(*env)->ReleaseStringUTFChars(env,input_jstr,input_cstr);
(*env)->ReleaseStringUTFChars(env,output_jstr,output_cstr);

av_frame_free(&pFrame);

avcodec_close(pCodecCtx);

avformat_free_context(pFormatCtx);  

在Java層進行呼叫

注意這裡輸出的視訊檔名最好是按照output_1280x720_yuv420p.yuv這個格式來,這樣YUV player可以自動識別視訊解析度進行播放。

new Thread(){
   @Override
   public void run() {
       super.run();

       String input = new File(Environment.getExternalStorageDirectory(),"input.mp4").getAbsolutePath();
       String output = new File(Environment.getExternalStorageDirectory(),"output_1280x720_yuv420p.yuv").getAbsolutePath();
       VideoUtils.decode(input, output);
   }
}.start();  

執行程式,進行視訊轉換

視訊轉換成功後,我們可以看到一個output_1280x720_yuv420p.yuv檔案,我們使用adb將該檔案匯出,然後下載專門的播放器YUV player 進行播放,可以看到,視訊播放成功。

在這裡插入圖片描述

至此,我們通過FFmpeg進行視訊轉碼就成功了。

其他

YUV格式說明

Y只包含亮度資訊,而UV只包含色度資訊。
Y佔了1/2,U和V分別佔了1/4
詳見 音視訊基礎知識

程式碼