主要流程 :
根据输入的时间,向前seek到最近的I帧,读取I帧,解码,将得到的I帧写为JPEG保存。
主要接口:
av_seek_frame();
av_read_frame();
avcodec_decode_video2();
注意问题:
1.输入的时间戳单位是秒,需要转换成ffmpeg的时间戳,输入到av_seek_frame(),主要使用av_rescale()实现转换。
2.ffmpeg解码另开线程,所以decode不是同步返回结果,代码中使用while(){sleep()}的逻辑获取解码结果。
3.解码得到的frame需要先转换成YUVJ420p,利用sws_scale()实现,转换成YUV420p存在color_range的问题,导致输出的jpeg图像与原图像存在对比度差异,详见: 点击打开链接
//
// main.cpp
// test_keyframe
//
// Created by shiyao.xsy on 16/1/26.
// Copyright © 2016年 rq. All rights reserved.
//
#include <iostream>
#include <stdio.h>
extern "C" {
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavcodec/avcodec.h"
#include "libavutil/time.h"
}
int SavetoJPEG(AVFrame *pFrameYUV,AVStream *pVStream,char *filepath,int width, int height){
AVFormatContext* pFormatCtx;
AVOutputFormat* fmt;
AVStream* video_st;
AVCodecContext* pCodecCtx;
AVCodec* pCodec;
uint8_t* picture_buf;
AVFrame* picture;
AVPacket pkt;
int y_size;
int got_picture=0;
int size;
int ret=0;
int in_w=width,in_h=height; //YUV's width and height
char* out_file = filepath; //Output file
//Method 1
pFormatCtx = avformat_alloc_context();
//Guess format
fmt = av_guess_format("mjpeg", NULL, NULL);
pFormatCtx->oformat = fmt;
//Output URL
if (avio_open(&pFormatCt