1. 前言
前面已經介紹了播放一個視頻文件的流程圖:
1.png
而視頻解碼是播放視頻文件的一個步驟绷雏,本篇博客將介紹FFmpeg視頻解碼欢搜。
首先我們簡單的了解一下FFmpeg八大庫:
2. FFmpeg庫簡介
庫的名稱 | 庫的作用 |
---|---|
avcodec | 該庫是音視頻編解碼的核心庫,用于各種類型聲音查剖、圖像編解碼 |
avformat | 各種音視頻封裝格式的處理忘嫉,為avcodec庫提供獨立的音頻或視頻碼流源 |
avfilter | 音視頻濾波器的開發(fā)渴丸,濾鏡特效的處理 |
avdevice | 硬件采集、加速日戈、顯示询张,各種設備的輸入輸出 |
avutil | 工具庫,大部分庫都需要這個庫的支持 |
postproc | 音視頻應用后期效果處理浙炼,如圖像的去塊效應 |
swresample | 音頻采樣數(shù)據(jù)格式轉換 |
swscale | 視頻像素數(shù)據(jù)格式轉換 |
而視頻轉碼將用到其中的三個庫份氧,分別是avcodec、avformat弯屈、swscale半火。
3. FFmpeg解碼的函數(shù)
3.1 FFmpeg解碼流程圖
3.2 FFmpeg解碼函數(shù)簡介
av_register_all():注冊所有組件
avformat_open_input():打開輸入視頻文件
avformat_find_stream_info():獲取視頻文件信息
avcodec_find_decoder():查找解碼器
avcodec_open2():打開解碼器
av_read_frame():從輸入文件讀取一幀壓縮數(shù)據(jù)
avcodec_decode_video2():解碼一幀壓縮數(shù)據(jù)
avcodec_close():關閉解碼器
avformat_close_input():關閉輸入視頻文件
開始接觸這些函數(shù)時,必然很陌生季俩,我們需要熟記這些函數(shù)钮糖,因為即將進行的視頻解碼,這些函數(shù)都會用到。
4. FFmpeg數(shù)據(jù)結構簡介
-
AVFormatContext
封裝格式上下文結構體店归,也是統(tǒng)領全局的結構體阎抒,保存了視頻文件封裝格式相關信息。
- iformat:輸入視頻的AVInputFormat
- nb_streams :輸入視頻的AVStream 個數(shù)
- streams :輸入視頻的AVStream []數(shù)組
- duration :輸入視頻的時長(以微秒為單位)
- bit_rate :輸入視頻的碼率
-
AVInputFormat
每種封裝格式(例如FLV消痛、MKV且叁、MP4、AVI)對應一個該結構體秩伞。
- name:封裝格式名稱
- long_name:封裝格式的長名稱
- extensions:封裝格式的擴展名
- id:封裝格式ID
- 一些封裝格式處理的接口函數(shù)
-
AVStream
視頻文件中每個視頻(音頻)流對應一個該結構體逞带。
- id:序號
- codec:該流對應的AVCodecContext
- time_base:該流的時基
- r_frame_rate: 該流的幀率
-
AVCodeContext
編碼器上下文結構體,保存了視頻(音頻)編解碼相關信息纱新。
- codec:編解碼器的AVCodec
- width, height:圖像的寬高(只針對視頻)
- pix_fmt:像素格式(只針對視頻)
- sample_rate:采樣率(只針對音頻)
- channels:聲道數(shù)(只針對音頻)
- sample_fmt:采樣格式(只針對音頻)
-
AVCodec
每種視頻(音頻)編解碼器(例如H.264解碼器)對應一個該結構體展氓。
- name:編解碼器名稱
- long_name:編解碼器長名稱
- type:編解碼器類型
- id:編解碼器ID
- 一些編解碼的接口函數(shù)
-
AVPacket
存儲一幀壓縮編碼數(shù)據(jù)。
- pts:顯示時間戳
- dts :解碼時間戳
- data :壓縮編碼數(shù)據(jù)
- size :壓縮編碼數(shù)據(jù)大小
- stream_index :所屬的AVStream
-
AVFrame
存儲一幀解碼后像素(采樣)數(shù)據(jù)脸爱。
- data:解碼后的圖像像素數(shù)據(jù)(音頻采樣數(shù)據(jù))
- linesize:對視頻來說是圖像中一行像素的大杏龉;對音頻來說是整個音頻幀的大小
- width, height:圖像的寬高(只針對視頻)
- key_frame:是否為關鍵幀(只針對視頻)
- pict_type:幀類型(只針對視頻) 簿废,例如I空入, P, B
有人要說了族檬,這么多數(shù)據(jù)結構我怎么記啊歪赢,其實并不需要大家去記,我們只要心里有個印象单料,在用的時候能用起來就行埋凯,通過用也能幫助我們記憶。
4. 原理簡述
本次我們要做的是把一個mp4視頻文件轉換成yuv視頻文件看尼,所以我們拿到mp4視頻文件獲取到視頻流的位置递鹉,從而獲取編解碼上下文,然后循環(huán)讀取數(shù)據(jù)包獲取AVFrame像素數(shù)據(jù)藏斩,而最后想要轉換成yuv視頻文件躏结,所以需要將此時的像素數(shù)據(jù)轉換成YUV420P像素數(shù)據(jù),最后寫入輸出文件中狰域。
5. FFmpeg解碼過程
5.1 注冊所有組件
av_register_all();
5.2 打開輸入視頻文件
//封裝格式上下文
AVFormatContext* pFormatCtx = avformat_alloc_context();
//2. 打開輸入視頻文件媳拴,成功返回0,第三個參數(shù)為NULL兆览,表示自動檢測文件格式
if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
LOGE("%s", "打開輸入視頻文件失敗");
return;
}
當我們不知道某個函數(shù)怎么使用的時候屈溉,我們可以點進去,查看它函數(shù)的注釋抬探,通過這些去了解函數(shù)使用和需要傳入什么樣的值子巾,比如avformat_open_input
函數(shù):
/**
* Open an input stream and read the header. The codecs are not opened.
* The stream must be closed with avformat_close_input().
*
* @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context).
* May be a pointer to NULL, in which case an AVFormatContext is allocated by this
* function and written into ps.
* Note that a user-supplied AVFormatContext will be freed on failure.
* @param url URL of the stream to open.
* @param fmt If non-NULL, this parameter forces a specific input format.
* Otherwise the format is autodetected.
* @param options A dictionary filled with AVFormatContext and demuxer-private options.
* On return this parameter will be destroyed and replaced with a dict containing
* options that were not found. May be NULL.
*
* @return 0 on success, a negative AVERROR on failure.
*
* @note If you want to use custom IO, preallocate the format context and set its pb field.
*/
從函數(shù)注釋中我們得知第三個參數(shù)為NULL的時候帆赢,就表示自動檢測文件格式,還有需要關流线梗,通過調用avformat_close_input()
函數(shù)去實現(xiàn)椰于,......,很多信息都可以從這里得到仪搔,我們需要學會這種方式去了解函數(shù)使用瘾婿。
5.3 獲取視頻文件信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
LOGE("%s", "獲取視頻文件信息失敗");
return;
}
//查找視頻流所在的位置
//遍歷所有類型的流(視頻流、音頻流可能還有字幕流)烤咧,找到視頻流的位置
int video_stream_index = -1;
int i = 0;
for(; i < pFormatCtx -> nb_streams; i++) {
if (pFormatCtx->streams[i]->codec-> codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
break;
}
}
5.4 查找解碼器
//編解碼上下文
AVCodecContext* pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;
//4. 查找解碼器 不能通過pCodecCtx->codec獲得解碼器
AVCodec* pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
LOGE("%s", "查找解碼器失敗");
return;
}
5.5 打開解碼器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
LOGE("%s", "打開解碼器失敗");
return;
}
5.6 讀取壓縮的視頻數(shù)據(jù)AVPacket
av_read_frame(pFormatCtx, pPacket)
5.7 解碼一幀壓縮數(shù)據(jù)AVPacket ---> AVFrame
avcodec_decode_video2(pCodecCtx, pFrame, &got_frame, pPacket);
6. 完整JNI代碼zp_decode.c
//
// Created by zp on 2017/12/5.
//
#include <jni.h>
#include <android/log.h>
//解碼
#include "libavcodec/avcodec.h"
//封裝格式
#include "libavformat/avformat.h"
//縮放
#include "libswscale/swscale.h"
#define LOGI(FORMAT, ...) __android_log_print(ANDROID_LOG_INFO, "zp", FORMAT, ##__VA_ARGS__);
#define LOGE(FORMAT, ...) __android_log_print(ANDROID_LOG_ERROR, "zp", FORMAT, ##__VA_ARGS__);
JNIEXPORT void JNICALL
Java_com_zhangpan_zpplayer_util_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. 打開輸入視頻文件偏陪,成功返回0,第三個參數(shù)為NULL煮嫌,表示自動檢測文件格式
if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
LOGE("%s", "打開輸入視頻文件失敗");
return;
}
//3. 獲取視頻文件信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
LOGE("%s", "獲取視頻文件信息失敗");
return;
}
//查找視頻流所在的位置
//遍歷所有類型的流(視頻流笛谦、音頻流可能還有字幕流),找到視頻流的位置
int video_stream_index = -1;
int i = 0;
for(; i < pFormatCtx -> nb_streams; i++) {
if (pFormatCtx->streams[i]->codec-> codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
break;
}
}
//編解碼上下文
AVCodecContext* pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;
//4. 查找解碼器 不能通過pCodecCtx->codec獲得解碼器
AVCodec* pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
LOGE("%s", "查找解碼器失敗");
return;
}
//5. 打開解碼器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
LOGE("%s", "打開解碼器失敗");
return;
}
//編碼數(shù)據(jù)
AVPacket* pPacket = (AVPacket*)av_malloc(sizeof(AVPacket));
//像素數(shù)據(jù)(解碼數(shù)據(jù))
AVFrame* pFrame = av_frame_alloc();
AVFrame* pYuvFrame = av_frame_alloc();
FILE* fp_yuv = fopen(output_cstr, "wb");
//只有指定了AVFrame的像素格式立膛、畫面大小才能真正分配內存
//緩沖區(qū)分配內存
uint8_t* out_buffer = (uint8_t*)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
//初始化緩沖區(qū)
avpicture_fill((AVPicture*)pYuvFrame, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
//srcW:源圖像的寬
//srcH:源圖像的高
//srcFormat:源圖像的像素格式
//dstW:目標圖像的寬
//dstH:目標圖像的高
//dstFormat:目標圖像的像素格式
//flags:設定圖像拉伸使用的算法
struct SwsContext* pSwsCtx = sws_getContext(
pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P,
SWS_BILINEAR, NULL, NULL, NULL);
int got_frame, len, frameCount = 0;
//6. 從輸入文件一幀一幀讀取壓縮的視頻數(shù)據(jù)AVPacket
while(av_read_frame(pFormatCtx, pPacket) >= 0) {
if (pPacket->stream_index == video_stream_index) {
//7. 解碼一幀壓縮數(shù)據(jù)AVPacket ---> AVFrame揪罕,第3個參數(shù)為0時表示解碼完成
len = avcodec_decode_video2(pCodecCtx, pFrame, &got_frame, pPacket);
if (len < 0) {
LOGE("%s", "解碼失敗");
return;
}
//AVFrame ---> YUV420P
//srcSlice[]梯码、dst[] 輸入宝泵、輸出數(shù)據(jù)
//srcStride[]、dstStride[] 輸入轩娶、輸出畫面一行的數(shù)據(jù)的大小 AVFrame 轉換是一行一行轉換的
//srcSliceY 輸入數(shù)據(jù)第一列要轉碼的位置 從0開始
//srcSliceH 輸入畫面的高度
sws_scale(pSwsCtx,
pFrame->data, pFrame->linesize, 0, pFrame->height,
pYuvFrame->data, pYuvFrame->linesize);
//非0表示正在解碼
if (got_frame) {
//圖像寬高的乘積就是視頻的總像素儿奶,而一個像素包含一個y,u對應1/4個y鳄抒,v對應1/4個y
int yuv_size = pCodecCtx->width * pCodecCtx->height;
//寫入y的數(shù)據(jù)
fwrite(pYuvFrame->data[0], 1, yuv_size, fp_yuv);
//寫入u的數(shù)據(jù)
fwrite(pYuvFrame->data[1], 1, yuv_size/4, fp_yuv);
//寫入v的數(shù)據(jù)
fwrite(pYuvFrame->data[2], 1, yuv_size/4, fp_yuv);
LOGI("解碼第%d幀", frameCount++);
}
av_free_packet(pPacket);
}
}
fclose(fp_yuv);
av_frame_free(&pFrame);
av_frame_free(&pYuvFrame);
avcodec_free_context(&pCodecCtx);
avformat_free_context(pFormatCtx);
(*env) -> ReleaseStringUTFChars(env, input_jstr, input_cstr);
(*env) -> ReleaseStringUTFChars(env, output_jstr, output_cstr);
}
解碼主要是在C中做的闯捎,Java中只是簡單的調用了,具體的配置许溅,請看我的上一篇博客:Android Studio NDK開發(fā)(十二):FFmpeg編譯與配置瓤鼻,直接看測試FFmpeg模塊。
編譯運行完之后贤重,將輸出文件復制到電腦中茬祷,用YUV專屬播放器播放,能完整且流暢播放并蝗,表示解碼成功祭犯。
項目源碼:
展望
喜歡本篇博客的簡友們,就請來一波點贊滚停,您的每一次關注沃粗,將成為我前進的動力,謝謝键畴!