FFMPEG 压缩JPEG流程


1.注册库 
    avcodec_register_all();
2. 创建编码器
    AVCodecID codec_id = AV_CODEC_ID_MJPEG;
     AVCodec *pCodec;
    pCodec = avcodec_find_encoder(codec_id);
    
3.创建环境
    AVCodecContext *pCodecCtx = NULL;
    pCodecCtx = avcodec_alloc_context3(pCodec);
    pCodecCtx->bit_rate = 4000000;
    pCodecCtx->width = in_w;
    pCodecCtx->height = in_h;
    pCodecCtx->time_base.num = 1;
    pCodecCtx->time_base.den = 11;
    pCodecCtx->gop_size = 75;
    //pCodecCtx->max_b_frames = 0;
    //pCodecCtx->global_quality = 1;
    pCodecCtx->pix_fmt = AV_PIX_FMT_YUVJ420P;

4.打开编码器
    avcodec_open2(pCodecCtx, pCodec, NULL)
5.创建帧1
    AVFrame *pFrame2;
    pFrame = av_frame_alloc();
    pFrame->format = pCodecCtx->pix_fmt;
    pFrame->width = pCodecCtx->width;
    pFrame->height = pCodecCtx->height;
    
    av_image_alloc(pFrame->data, pFrame->linesize, pCodecCtx->width, pCodecCtx->height,pCodecCtx->pix_fmt, 16);
6.创建帧2
    pFrame2 = av_frame_alloc();
    pFrame2->format = AV_PIX_FMT_YUV420P;
    pFrame2->width = pCodecCtx->width;
    pFrame2->height = pCodecCtx->height;

    ret = av_image_alloc(pFrame2->data, pFrame2->linesize, pCodecCtx->width, pCodecCtx->height,AV_PIX_FMT_YUV420P, 16);
7.创建格式转换 yuv420-->yuvj420
    struct SwsContext *img_convert_ctx;
     img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUVJ420P, SWS_BICUBIC, NULL, NULL, NULL);
     
8.读取yuv420数据给pFrame2赋值
     fread(pFrame2->data[0], 1, y_size, fp_in) 
     fread(pFrame2->data[1], 1, y_size / 4, fp_in) 
     fread(pFrame2->data[2], 1, y_size / 4, fp_in)
9.格式转换
     sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame2->data, pFrame2->linesize, 0, pCodecCtx->height, pFrame->data, pFrame->linesize);
10压缩JPEG
    av_init_packet(&pkt);
    pkt.data = NULL;    // packet data will be allocated by the encoder
    pkt.size = 0;
    avcodec_encode_video2(pCodecCtx, &pkt,picture, &got_picture)
    av_free_packet(&pkt);
    
11
     avcodec_close(pCodecCtx);
     av_free(pCodecCtx);
     av_freep(&pFrame->data[0]);
     av_frame_free(&pFrame);
     av_frame_free(&pFrame2);

你可能感兴趣的:(ffmpeg)