如何在Android用FFmpeg解码图像

发布网友 发布时间:2022-04-24 14:22

我来回答

1个回答

热心网友 时间:2023-10-16 04:50

这涉及到两个问题,一个是解码,另一个是显示,解码问题要先交叉编译ffmpeg,然后参考下面的解码流程

avcodec_register_all();
/*
########################################
[1]
########################################
*/
av_register_all();
/*
// Open video file
########################################
[2]
########################################
*/
pFormatCtx = avformat_alloc_context();

if(avformat_open_input(&pFormatCtx, filename, NULL, NULL)!=0)
return -1; // Couldn't open file

// Retrieve stream information
/*
########################################
[3]
########################################
*/
if(avformat_find_stream_info(pFormatCtx,NULL)<0)
return -1; // Couldn't find stream information

// Dump information about file onto standard error
// mp_format(pFormatCtx, 0, argv[1], 0);

// Find the first video stream
videoStream=-1;
for(i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
videoStream=i;
break;
}
if(videoStream==-1)
return -1; // Didn't find a video stream

// Get a pointer to the codec context for the video stream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;

// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {
fprintf(stderr, "Unsupported codec!\n");
return -1; // Codec not found
}
// Open codec
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)

pFrame=avcodec_alloc_frame();

// Allocate an picture structure
avpicture_alloc(&picture, PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);

// Determine required buffer size and allocate buffer
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
if(img_convert_ctx == NULL)
{
fprintf(stderr, "Cannot initialize the conversion context!\n");
exit(1);
}

// Read frames and save first five frames to disk
/*
########################################
[4]
########################################
*/
i=0;
dirtyRegion.set(android::Rect(0x3FFF, 0x3FFF));
while(av_read_frame(pFormatCtx, &packet)>=0) {
// Is this a packet from the video stream?
if(packet.stream_index==videoStream) {
// Decode video frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished,
&packet);

// Did we get a video frame?
if(frameFinished) {
// Convert the image from its native format to RGB

sws_scale(img_convert_ctx,
pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
picture.data, picture.linesize);

}
}

// Free the packet that was allocated by av_read_frame
av_free_packet(&packet);
}
pFrame为解码后的数据,将它显示在画布上,就完成了FFMEPG解码

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com