ffmpeg4.1 压缩图片为视频
int save_jpeg(char* filepath, void* vp, void* service) {
Rtmp_tool *rtmp_tool = (Rtmp_tool *)vp;
DemoDevice *pDev = (DemoDevice *)service;
av_log_set_level(AV_LOG_WARNING);
AVCodecContext *c = rtmp_tool->c;
AVPacket avpkt;
//AVFrame *m_pRGBFrame = rtmp_tool->m_pRGBFrame;
//AVFrame *m_pYUVFrame = rtmp_tool->m_pYUVFrame;
AVPixelFormat pixFormat = AV_PIX_FMT_YUV420P;
AVFormatContext *avFormatCtx = NULL;
AVCodecContext *avCodecCtx = NULL;
AVFrame *pFrameYUV = NULL;
AVCodec *avCodec = NULL;
AVPacket packet;
if (avformat_open_input(&avFormatCtx, filepath, NULL, NULL) != 0)
{
printf("phase_1,couldn't open input file\n");
return -1;
}
if (avformat_find_stream_info(avFormatCtx, NULL) < 0)
{
printf("phase_1,stream_info error\n");
return -1;
}
int videoStream =0;
avCodecCtx = avcodec_alloc_context3(NULL);
avcodec_parameters_to_context(avCodecCtx, avFormatCtx->streams[videoStream]->codecpar);
avCodec = avcodec_find_decoder(avCodecCtx->codec_id);
if (avCodec == NULL)
{
printf("phase_1,cant find decoder\n");
return -1;
}
if (avcodec_open2(avCodecCtx, avCodec, NULL) < 0)
{
printf("phase_1,cant open decoder!\n");
return -1;
}
pFrameYUV = av_frame_alloc();
if ( pFrameYUV == NULL)
{
printf("phase_1,cant open a frame to store data\n");
return -1;
}
int frameFinish = 0;
int decLen = 0;
while (av_read_frame(avFormatCtx, &packet) >= 0)
{
if (packet.stream_index == videoStream)
{
if (avcodec_send_packet(avCodecCtx, &packet) != 0) {
cout << "avcodec_send_packet错误" << endl;
break;
}
while (avcodec_receive_frame(avCodecCtx, pFrameYUV) == 0) {
printf("avcodec_receive_frame for encoding\n");
avcodec_flush_buffers(avCodecCtx);
av_init_packet(&avpkt);// av_packet_alloc();
int ret = avcodec_send_frame(c, pFrameYUV);
pFrameYUV->pts++;
if (ret < 0)
{
printf("Error sending a frame for encoding\n");
exit(1);
}
while (ret >= 0)
{
ret = avcodec_receive_packet(c, &avpkt);
if (ret != 0) {
if (ret == -11 || ret == AVERROR(EAGAIN)) {//-11
printf("avcodec_receive_packet AVERROR(EAGAIN) %d\n",AVERROR(EAGAIN));
}
else if (ret == AVERROR(EINVAL)) {//-22
printf("avcodec_receive_packet AVERROR(EINVAL)\n");
}
else {
printf("avcodec_receive_packet error %d\n", ret);
}
av_packet_unref(&avpkt);
break;
}
//printf("Write packet %3(size=%5d)\n", avpkt->pts, avpkt->size);
if (!pDev->m_token.empty()) {
InfoFrame data_send;
data_send.video = CODEC_H264;
struct timeval tv;
gettimeofday(&tv, NULL);
if (pDev->stream_open) {
pDev->send_data(avpkt.data, avpkt.size, tv.tv_sec, tv.tv_usec / 1000, data_send);
}
//fwrite(avpkt->data, 1, avpkt->size, rtmp_tool->f);
}
av_packet_unref(&avpkt);
}
//packet.data += decLen;
//packet.size -= decLen;
av_packet_unref(&packet);
}
}
}
avCodec->close(avCodecCtx);
printf("2222\n");
avcodec_close(avCodecCtx);
printf("555\n");
avcodec_free_context(&avCodecCtx);
printf("66666\n");
avformat_close_input(&avFormatCtx);
printf("7777\n");
av_frame_free(&pFrameYUV);
printf("222\n");
av_packet_unref(&packet);
printf("send ok\n");
return 0;
}