简述
本文是参照雷霄骅博士的博客实现的Android平台视频解码器,使用FFmpeg实现将视频文件解码为YUV数据。 文中代码与原博客一致,针对FFmpeg4.2.2更换了一些api函数,梳理解码流程,并对关键函数进行简要解析。
准备
- 交叉编译arm平台的ffmpeg so库
- 包含native的Android project
基础知识
音视频从解封装到播放的流程

解协议
主要是将网络流媒体格式的数据,解析为相应的封装格式的数据。音视频信息在网络中是以某种协议在通信双方中传输的,常用的流媒体协议有RTMP、MMS、HTTP等。
解封装
是指把封装格式数据分离成音频部分和视频部分,常见的文件如MP4、MKV、FLV等都是将已编码压缩的音频数据和已编码压缩的视频数据按一定的格式封装在一起。
解码
是音视频处理中最重要的环节,将已编码压缩的数据,解码成原始数据。常见的音频压缩编码标准如AAC,MP3等,视频压缩编码标准有H.264,MPEG2,VC-1等。解码操作后,音频部分得到音频抽样数据,如PCM,视频部分得到颜色数据,如YUV420P,RGB等。
格式及编码标准对应表
参阅雷霄骅博士的视音频编解码技术零基础学习方法
此示例中使用到的FFmpeg的相关库简介
Libavformat
解封装器类库,用于对音频,视频和字幕流进行多路复用和多路分解(混合和解混合),它包含多种用于多媒体封装格式的复用器和解复用器。
Libavcodec
编码/解码器类库,包含用于音频,视频和字幕流的解码器和编码器,以及几个码流过滤器。
Libswscale
用于图像缩放以及色彩空间和像素格式转换操作。
使用FFmpeg进行视频解封装和解码流程

示例代码片段
引入FFmpeg相关头文件及Android日志头文件,定义日志打印宏。
#include <android/log.h>
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
}
#define LOGD(format, ...) __android_log_print(ANDROID_LOG_DEBUG, "xeemon", format, ##__VA_ARGS__)
#define LOGE(format, ...) __android_log_print(ANDROID_LOG_ERROR, "xeemon", format, ##__VA_ARGS__)
编写av_log()回调函数,用于将日志写到sdcard文件中。
//Output FFmpeg's av_log()
void custom_log(void *ptr, int level, const char *fmt, va_list vl) {
FILE *fp = fopen("/storage/emulated/0/av_log.txt", "a+");
if (fp) {
vfprintf(fp, fmt, vl);
fflush(fp);
fclose(fp);
}
}
Java部分定义native方法,接收两个参数,分别是视频文件路径和待输出的yuv文件路径
public native void decode(String input_url, String output_url);
在C++编写逻辑
extern "C" JNIEXPORT jint JNICALL
Java_cn_helloworld_FFmpegUtils_decode(JNIEnv *env, jobject thiz,
jstring input_url, jstring output_url) {
//定义相关结构体变量
AVFormatContext *pFormatCtx;
int i, videoIndex;
AVCodecContext *pCodecCtx;
AVCodecParameters *pCodecpar;
AVCodec *pCodec;
AVFrame *pFrame, *pFrameYUV;
uint8_t *out_buffer;
AVPacket *packet;
int y_size;
int ret;
struct SwsContext *img_convert_ctx;
FILE *fp_yuv;
int frame_cnt;
clock_t time_start, time_finish;
double time_duration = 0.0;
char input_str[500] = {0};
char output_str[500] = {0};
char info[1000] = {0};
//接收传入的视频路径和待输出的yuv文件路径
sprintf(input_str, "%s", env->GetStringUTFChars(input_url, NULL));
sprintf(output_str, "%s", env->GetStringUTFChars(output_url, NULL));
//av_log()写到sdcard
av_log_set_callback(custom_log);
初始化解封装器,查找video stream
avformat_network_init(); //初始化和启动底层TLS库. 不开网络流的情况下可选,官方建议添加.
pFormatCtx = avformat_alloc_context(); //创建AVFormatContext结构体。
// tips:此处也可以不写,接下来的avformat_open_input()函数内发现它没有初始化时会调用它
// 什么时候需要预先自行初始化AVFormatContext?
// 官网:一种情况是当需要使用自定义函数读取输入数据而不是lavf内部I/O层时
//avformat_open_input()为AVFormatContext分配内存,
//探测视频文件的封装格式并将视频源加入内部buffer中,最后读取视频头信息
if (avformat_open_input(&pFormatCtx, input_str, NULL, NULL) != 0) {
LOGE("Couldn't open input stream.\n");
return -1;
}
//某些格式的文件没有标头信息或者标头没有存储足够的信息
//avformat_find_stream_info()用于进一步解析视频文件信息,该函数尝试读取和解码一些帧以查找丢失的信息
//主要是解析AVFormatContext结构体的AVStream,
//该函数内部已经做了一套完整的解码流程,获取了多媒体流的信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
LOGE("Couldn't find stream information.\n");
return -1;
}
videoIndex = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
if (videoIndex < 0) {
LOGE("Couldn't find a video stream.\n");
return -1;
}
解封装器读取文件成功后,会将文件信息存储在 AVFormatContext
结构体中,接下来通过AVFormatContext
->streams
->codecpar
拿到codec_id
,查找对应的解码器。
pCodecpar = pFormatCtx->streams[videoIndex]->codecpar;
pCodec = avcodec_find_decoder(pCodecpar->codec_id); //寻找合适的解码器
pCodecCtx = avcodec_alloc_context3(pCodec); //为AVCodecContext分配内存
if (pCodec == NULL) {
LOGE("Couldn't find Codec, codec is NULL.\n");
return -1;
}
if (pCodecCtx == NULL) {
LOGE("Couldn't allocate decoder context.\n");
return -1;
}
//avcodec_parameters_to_context()真正对AVCodecContext执行了内容拷贝
if (avcodec_parameters_to_context(pCodecCtx, pCodecpar) < 0) {
LOGE("Couldn't copy decoder context.\n");
return -1;
}
//avcodec_open2()打开解码器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
LOGE("Couldn't open Codec.\n");
return -1;
}
通过以上步骤,就可以开始循环调用av_read_frame()
进行解析了,不过为了输出yuv数据,还必须准备接收的存储空间。
pFrame = av_frame_alloc();
pFrameYUV = av_frame_alloc();
out_buffer = (unsigned char *) av_malloc(
av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1));
//av_image_fill_arrays() 把AVFrame的data成员关联到某个地址空间
//此处是为后面av_read_frame()和sws_scale()处理后的帧信息输出提供存储位置
av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, out_buffer,
AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
packet = (AVPacket *) av_malloc(sizeof(AVPacket));
初始化SwsContext是为了接下来使用sws_scale()
做准备。由于AVFrame中存储的yuv视频数据不是连续的有效像素,这其中还包含一些由于优化等原因产生的无效数据,因此,需要通过调用sws_scale()
进行转换。
//sws_getContext() 初始化SwsContext,函数参数解释:
// srcW:源图像的宽
// srcH:源图像的高
// srcFormat:源图像的像素格式
// dstW:目标图像的宽
// dstH:目标图像的高
// dstFormat:目标图像的像素格式
// flags:设定图像拉伸使用的算法
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P,
SWS_BICUBIC, NULL, NULL, NULL);
sprintf(info, "[Input ]%s\n", input_str);
sprintf(info, "%s[Output ]%s\n", info, output_str);
sprintf(info, "%s[Format ]%s\n", info, pFormatCtx->iformat->name);
sprintf(info, "%s[Codec ]%s\n", info, pCodecCtx->codec->name);
sprintf(info, "%s[Resolution]%dx%d\n", info, pCodecCtx->width, pCodecCtx->height);
这里开始真正的解码环节。调用av_read_frame()
成功时将返回一个AVPacket
,然后调用avcodec_send_packet()
发送一个packet到解码队列,解码成功后从avcodec_receive_frame()
将会返回一个已解码的AVFrame
。
fp_yuv = fopen(output_str, "wb+");
if (fp_yuv == NULL) {
LOGE("Cannot open output file.\n");
return -1;
}
frame_cnt = 0;
time_start = clock();
//通过重复调用av_read_frame()从打开的AVFormatContext中读取数据
//每次调用av_read_frame()成功时将返回一个AVPacket
//AVPacket中包含一个AVStream的编码数据
while (av_read_frame(pFormatCtx, packet) >= 0) {
if (packet->stream_index == videoIndex) {
ret = avcodec_send_packet(pCodecCtx, packet);
if (ret < 0) {
LOGE("Decode error.\n");
return -1;
}
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret != 0) {
// TODO 第一次调用avcodec_receive_frame()返回ret = -11,原因不明,先continue吧
continue;
}
// sws_scale() 主要工作是进行图像转换
if (sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
pFrameYUV->data, pFrameYUV->linesize) > 0) {
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
//Output info
char pictype_str[10] = {0};
switch (pFrame->pict_type) {
case AV_PICTURE_TYPE_I:
strcpy(pictype_str, "I");
break;
case AV_PICTURE_TYPE_P:
strcpy(pictype_str, "P");
break;
case AV_PICTURE_TYPE_B:
strcpy(pictype_str, "B");
break;
default:
strcpy(pictype_str, "Other");
}
LOGD("Frame Index: %5d. Type:%s", frame_cnt, pictype_str);
frame_cnt++;
}
}
av_packet_unref(packet);
}
这里暂时没有完全理解,好像是刷新输出剩下的帧。
//flush decoder
while (true) {
ret = avcodec_send_packet(pCodecCtx, packet);
if (ret < 0) {
break;
}
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret != 0) {
continue;
}
sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
pFrameYUV->data, pFrameYUV->linesize);
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
//Output info
char pictype_str[10] = {0};
switch (pFrame->pict_type) {
case AV_PICTURE_TYPE_I:
strcpy(pictype_str, "I");
break;
case AV_PICTURE_TYPE_P:
strcpy(pictype_str, "P");
break;
case AV_PICTURE_TYPE_B:
strcpy(pictype_str, "B");
break;
default:
strcpy(pictype_str, "Other");
}
LOGD("Frame Index: %5d. Type:%s", frame_cnt, pictype_str);
frame_cnt++;
}
time_finish = clock();
time_duration = (double) (time_finish - time_start);
sprintf(info, "%s[Time ]%fms\n", info, time_duration);
sprintf(info, "%s[Count ]%d\n", info, frame_cnt);
LOGD("Info:\n%s", info);
关闭前面打开的资源。好些函数都是配套使用的,编写代码的时候应该配套地写好,再在中间编写其他逻辑,以免忘记。
//与sws_getContext()配套使用
sws_freeContext(img_convert_ctx);
fclose(fp_yuv);
av_frame_free(&pFrameYUV);
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
//与avformat_open_input()配套使用
avformat_close_input(&pFormatCtx);
return 0;
}