FFmepg 解码码流数据
FILE *p = fopen(FileName,"rb+");
int fill_iobuffer(void * opaque,uint8_t *buf,int buf_size)
{
if(!feof(p))
{
int true_size=fread(buf,1,buf_size,p);
return true_size;
}
else
{
return -1;
}
}
int main()
{
av_register_all();
AVFormatContext *fmatC = avformat_alloc_context();
unsigned char * iobuffer=(unsigned char *)av_malloc(100000);
if(iobuffer == NULL)
{
qDebug()<<"iobuff is null";
}
AVInputFormat* in_fmt = av_find_input_format("mjpeg");
AVIOContext *avio =avio_alloc_context(iobuffer,100000,0,NULL,fill_iobuffer,NULL,NULL);
int err = -1;
fmatC->pb=avio;
err = avformat_open_input(&fmatC,"",in_fmt,NULL);
if(err < 0)
{
qDebug()<<"open error";
return 0;
}
int ret = -1;
ret = avformat_find_stream_info(fmatC, NULL);
if(ret < 0)
{
qDebug()<<":find stream info failed!";
return 0;
}
int videoIndex = -1;
for(int i = 0; i < fmatC->nb_streams; i++)
if(fmatC->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoIndex = i;
break;
}
AVCodecContext *codec = fmatC->streams[0]->codec;
AVCodec *decodec = avcodec_find_decoder(codec->codec_id);
if(decodec == NULL)
{
qDebug()<<":find decodec failed!";
return 0;
}
ret = -1;
ret = avcodec_open2(codec,decodec, NULL);
if(ret != 0)
{
qDebug()<<":open decodec failed!";
return 0;
}
uint8_t *buffer;
SwsContext *sws_context;
AVPacket *pkt = (AVPacket *)malloc(sizeof(AVPacket));
int frameSize = codec->width * codec->height;
av_new_packet(pkt, frameSize);
AVFrame *dstFrame;
AVFrame *picture;
picture = av_frame_alloc();
dstFrame = av_frame_alloc();
int numByte = avpicture_get_size(AV_PIX_FMT_RGB32, codec->width,codec->height);
buffer = (uint8_t *)av_malloc(numByte * sizeof(uint8_t));
avpicture_fill((AVPicture *)dstFrame, buffer, AV_PIX_FMT_RGB32,codec->width,codec->height);
sws_context = sws_getContext(codec->width,codec->height,codec->pix_fmt,codec->width,codec->height, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
ret = 0;
int count = 0;
while(av_read_frame(fmatC, pkt) == 0)
{
if(pkt->stream_index == 0)
{
count++;
int got_picture_ptr = -1;
avcodec_decode_video2(codec,picture, &got_picture_ptr, pkt);
if(got_picture_ptr)
{
ret = 1;
sws_scale(sws_context,picture->data,picture->linesize, 0,picture->height,dstFrame->data,dstFrame->linesize);
QImage((uchar *)dstFrame->data[0],codec->width, codec->height, QImage::Format_RGB32).save(QString("D://CheckImage/%1.png").arg(QString::number(count)));
}
}
}
}