用ffmpeg编码:视频质量下降

Encoding with ffmpeg: video quality drops

本文关键字:视频 ffmpeg 编码      更新时间:2023-10-16

我正在尝试用ffmpeg将一组图片编码为视频。我是新手,但我还是学会了。我只有一个问题:视频的前一两秒看起来不错,但随着时间的推移,视频质量不断下降。最后(这是一个大约16秒的视频),质量真的很差,我不明白为什么。

我使用AV_CODEC_ID_MPEG1VIDEO作为视频编解码器(坦率地说,这是我唯一可以工作的),这里是我的代码示例:

c = avcodec_alloc_context3(codec);
if (!c) {
    fprintf(stderr, "Could not allocate video codec contextn");
    exit(1);
}
c->bit_rate = 400000;
c->width = width;
c->height = height;
struct AVRational time_base = {1, 25};
c->time_base = time_base;
c->gop_size = 10;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec_id == AV_CODEC_ID_H264)
    av_opt_set(c->priv_data, "preset", "slow", 0);
// Open the codec
if (avcodec_open2(c, codec, NULL) < 0) {
    fprintf(stderr, "Could not open codecn");
    exit(1);
}
fopen_s(&f, filename, "wb");
if (!f) {
    fprintf(stderr, "Could not open %sn", filename);
    exit(1);
}
frame = av_frame_alloc();
if (!frame) {
    fprintf(stderr, "Could not allocate video framen");
    exit(1);
}
frame->format = c->pix_fmt;
frame->width  = c->width;
frame->height = c->height;
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
                     c->pix_fmt, 32);
if (ret < 0) {
    fprintf(stderr, "Could not allocate raw picture buffern");
    exit(1);
}
struct SwsContext *frameConvertContext = sws_getContext(width, height,
      PIX_FMT_RGB24,
      c->width, c->height,
      c->pix_fmt,
      SWS_LANCZOS | SWS_ACCURATE_RND, NULL, NULL, NULL);
for (i = 0; i < framesNr; i++) {
    // Read an image
    std::stringstream filename;
    filename << "input/image-" << (i+1) << ".jpg";
    Image* img;
    img = Image::fromJpeg((char*) filename.str().c_str());
    int srcSliceY[1] = { img->getWidth() * 3 };
    const uint8_t* imgbuf[1] = { (uint8_t*) img->getData(sizeof(uint8_t)) };
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;
    fflush(stdout);
    frameConvertContext = sws_getCachedContext(frameConvertContext, width, height,
      PIX_FMT_RGB24,
      c->width, c->height,
      c->pix_fmt,
      SWS_LANCZOS | SWS_ACCURATE_RND, NULL, NULL, NULL);
    sws_scale(frameConvertContext, imgbuf, srcSliceY, 0, img->getHeight(), frame->data, frame->linesize);
    frame->pts = i;
    /* encode the image */
    ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
    if (ret < 0) {
        fprintf(stderr, "Error encoding framen");
        exit(1);
    }
    if (got_output) {
        printf(".");
        fwrite(pkt.data, 1, pkt.size, f);
        av_free_packet(&pkt);
    }
    // Free the memory
    delete img;
}

提示吗?非常感谢!

400kb mpeg 1?是的,质量会很差。使用更高的比特率或更好的编解码器。