You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将缩放帧传入MP4编码器时出现PTS异常错误,求排查方案

问题解决:Encoder did not produce proper pts, making some up

这个错误的核心原因是缩放后的scaled_frame没有继承原帧input_frame的时间戳(PTS/DTS)及关键时序属性,编码器无法确定帧的播放顺序和时长,只能自动生成不准确的时间戳,从而触发警告。

具体修复步骤:

  1. 为scaled_frame分配数据缓冲区
    av_frame_alloc()仅分配帧的结构体,并未为像素数据分配内存,需要手动调用av_frame_get_buffer完成缓冲区初始化:

    AVFrame *scaled_frame = av_frame_alloc();
    scaled_frame->width = 854;
    scaled_frame->height = 480;
    scaled_frame->format = AV_PIX_FMT_YUV420P;
    // 分配帧数据缓冲区,第二个参数为对齐方式,0表示使用默认对齐
    if (av_frame_get_buffer(scaled_frame, 0) < 0) {
        av_frame_free(&scaled_frame);
        return -1;
    }
    
  2. 复制原帧的时序属性到scaled_frame
    缩放完成后,必须将原帧的时间戳、时长、宽高比等属性同步到缩放帧:

    sws_scale_frame(encoder->sws_ctx, scaled_frame, input_frame);
    
    // 复制时间戳与时长
    scaled_frame->pts = input_frame->pts;
    scaled_frame->dts = input_frame->dts;
    scaled_frame->duration = input_frame->duration;
    
    // 复制样本宽高比(保证画面比例正确)
    scaled_frame->sample_aspect_ratio = input_frame->sample_aspect_ratio;
    
    // 关键:将时间戳转换为编码器流的时基
    // 如果解码流与编码流的时基不同,必须做此转换
    scaled_frame->pts = av_rescale_q(scaled_frame->pts, decoder->stream->time_base, encoder->stream->time_base);
    scaled_frame->dts = av_rescale_q(scaled_frame->dts, decoder->stream->time_base, encoder->stream->time_base);
    scaled_frame->duration = av_rescale_q(scaled_frame->duration, decoder->stream->time_base, encoder->stream->time_base);
    
    if (encode_video(decoder, encoder, scaled_frame))
        return -1;
    
  3. 验证SWS上下文的正确性
    你的SWS上下文初始化是正确的,但可以确保目标帧的格式、宽高与初始化参数一致,避免因参数不匹配导致的隐性问题。

为什么直接传input_frame无报错?

原input_frame从解码器输出时,已经携带了正确的PTS/DTS、时长等时序信息,编码器可以直接使用这些属性生成符合规范的MP4流;而缩放后的帧默认没有这些属性,编码器只能尝试自动生成,从而触发警告。

内容的提问来源于stack exchange,提问作者user16570427

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:17:11