FFmpeg H265编码->解码,C ++

时间:2019-03-15 18:36:43

标签: c++ encoding ffmpeg

嗨,我已经有一些适用于h264的编码和直接解码代码。 我正在尝试使代码适合h265,但由于我总是收到错误消息,因此我在解码方面做错了:

[hevc @ 0x78eca0] PPS id out of range: 0
[hevc @ 0x78eca0] Error parsing NAL unit #0.

解码初始化:

decoder = avcodec_find_decoder(AV_CODEC_ID_H265);

ctx = avcodec_alloc_context3(decoder);
ctx->extradata = NULL;
ctx->width = 400;
ctx->height = 256;
ctx->pix_fmt = AV_PIX_FMT_YUV420P;

avcodec_open2(ctx,decoder,NULL);

编码似乎还可以,因为我只处理小型视频,所以我只能得到一个信号:

x265_nal* nals;
unsigned int i_nals;

int ret = x265_encoder_encode(m_x265Encoder, &nals, &i_nals, m_picIn, m_picOut);

AVPacket avpkt;
av_init_packet(&avpkt);
avpkt.size = nals[0].sizeBytes;
avpkt.data = nals[0].payload;
AVFrame* frame = avcodec_alloc_frame();

int got=0;
avcodec_decode_video2(ctx,frame,&got,&avpkt);

有人可以帮我吗?

br 迈克

2 个答案:

答案 0 :(得分:0)

确定要在实际压缩图片之前将SPS,PPS,VPS NAL单元传递给解码器吗?似乎解码器有图片但还没有PPS。

答案 1 :(得分:0)

实际上我找到了一个可行的解决方案,它不是最好的代码,并且主要用于测试,最终x265只是降低了CPU的速度,无法跟上实时流:

    AVFrame* avpic = av_frame_alloc();
    avpic->pts = msg.TimeStampCapture;
    avpic->format = AV_PIX_FMT_YUV420P;
    avpic->width = _dstFrameWidth;
    avpic->height = _dstFrameHeight;

    AVPicture tmppic;
    avpicture_fill(&tmppic, pSrc, _rawFormat, _srcFrameWidth, _srcFrameHeight);
    int err_sws = sws_scale(pSWSContext, tmppic.data, tmppic.linesize, 0, _srcFrameHeight, avpic->data, avpic->linesize);

    int ret = av_image_alloc(avpic->data, avpic->linesize, avpic->width, avpic->height,AV_PIX_FMT_YUV420P,8 );

    // Using scale Context to create avpic fore video2 encode
    SwsContext* pSWSContext = sws_getContext(_srcFrameWidth, _srcFrameHeight, _rawFormat, _dstFrameWidth, _dstFrameHeight, AV_PIX_FMT_YUV420P, SWS_BILINEAR , 0, 0, 0);

    sws_freeContext(pSWSContext);
    int got_packet;
    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = NULL;    // packet data will be allocated by the encoder
    pkt.size = 0;

    ret = avcodec_encode_video2(_ectx,&pkt,avpic,&got_packet);
    //count ++;
    msg.pts = pkt.pts;
    msg.dts = pkt.dts;
    msg.count = count++;
    msg.flags = pkt.flags;


    nEncodedSize = pkt.size;


    /// Decoder test
    AVPacket avpkt;
    av_init_packet(&avpkt);
    avpkt.data = pkt.data;
    avpkt.size = pkt.size;
    avpkt.pts = pkt.pts;
    avpkt.dts = pkt.dts;
    avpkt.flags = pkt.flags;
    avpkt.stream_index = pkt.stream_index;
    AVFrame* frame = av_frame_alloc();


    int got_picture = 0;
    avcodec_decode_video2(m_cc,frame,&got_picture,&avpkt)

    av_frame_free(&avpic);
    av_packet_unref(&pkt);