ビデオプレーヤー (2): ビデオデコード

1.FFmpegデコード処理

ここに画像の説明を挿入

2. コード

    std::string input_file = "1.mp4";
    std::string output_file = "1.yuv";

    // 创建输出文件
    FILE *out_fd = nullptr;
    out_fd = fopen(output_file.c_str(), "wb");
    if (!out_fd)
    {
    
    
        printf("can't open output file");
        return;
    }

    AVFormatContext *fmt_ctx = nullptr;
    fmt_ctx = avformat_alloc_context();

	// 打开输入视频文件
    int ret = avformat_open_input(&fmt_ctx, input_file.c_str(), nullptr, nullptr);
    if(ret < 0)
    {
    
    
        av_log(nullptr, AV_LOG_ERROR, "can not open input: %s \n", err2str(ret).c_str());
        return;
    }
    
	// 获取视频文件信息
    ret = avformat_find_stream_info(fmt_ctx, nullptr);
    if(ret < 0)
    {
    
    
        av_log(nullptr, AV_LOG_ERROR, "avformat_find_stream_info failed: %s \n", err2str(ret).c_str());
        return;
    }

	// 打印视频信息
    //av_dump_format(fmt_ctx, 0, input_file.c_str(), 0);   // 第四个参数,输入流为0, 输出流为1

	// 查找视频流序号
    int video_index = -1;
    for (int i = 0; i < fmt_ctx->nb_streams; ++i)
    {
    
    
        if(fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
    
    
            video_index = i;
        }
    }

    if(video_index == -1)
    {
    
    
        av_log(nullptr, AV_LOG_ERROR, "can not find video \n");
        return;
    }

    // 找视频流解码器
    const AVCodec *video_codec = avcodec_find_decoder(fmt_ctx->streams[video_index]->codecpar->codec_id);

    AVCodecContext *codec_ctx = avcodec_alloc_context3(video_codec);
    avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[video_index]->codecpar);

    // 打开视频解码器
    ret = avcodec_open2(codec_ctx, video_codec, nullptr);
    if(ret < 0)
    {
    
    
        av_log(nullptr, AV_LOG_ERROR, "avcodec_open2 failed: %s \n", err2str(ret).c_str());
        return;
    }

	// 其他YUV格式转换成YUV420P
    SwsContext *img_convert_ctx = nullptr;
    img_convert_ctx = sws_getContext(codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt,
                                     codec_ctx->width, codec_ctx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);

    // 创建packet,用于存储解码前的数据
    AVPacket packet;
    av_init_packet(&packet);

    // 创建Frame,用于存储解码后的数据
    AVFrame *frame = av_frame_alloc();
    frame->width = fmt_ctx->streams[video_index]->codecpar->width;
    frame->height = fmt_ctx->streams[video_index]->codecpar->height;
    frame->format = fmt_ctx->streams[video_index]->codecpar->format;
    av_frame_get_buffer(frame, 32);

	// 创建YUV Frame,用于存储解码后的数据
    AVFrame *yuv_frame = av_frame_alloc();
    yuv_frame->width = fmt_ctx->streams[video_index]->codecpar->width;
    yuv_frame->height = fmt_ctx->streams[video_index]->codecpar->height;
    yuv_frame->format = AV_PIX_FMT_YUV420P;
    av_frame_get_buffer(yuv_frame, 32);

    // while循环,每次读取一帧,并转码
    while (av_read_frame(fmt_ctx, &packet) >= 0)
    {
    
    
        if(packet.stream_index == video_index)
        {
    
    
            // 开始解码
            // 发送数据到解码队列
            // 旧API:avcodec_decode_video2
            // 新API:avcodec_send_packet与avcodec_receive_frame
            ret = avcodec_send_packet(codec_ctx, &packet);
            if (ret < 0)
            {
    
    
                av_log(nullptr, AV_LOG_ERROR, "avcodec_send_packet failed: %s \n", err2str(ret).c_str());
                break;
            }

            while (avcodec_receive_frame(codec_ctx, frame) >= 0)
            {
    
    
                // 
                sws_scale(img_convert_ctx,
                          (const uint8_t **)frame->data,
                          frame->linesize,
                          0,
                          codec_ctx->height,
                          yuv_frame->data,
                          yuv_frame->linesize);
				
				// 数据写入到yuv文件中
                int y_size = codec_ctx->width * codec_ctx->height;
                fwrite(yuv_frame->data[0], 1, y_size, out_fd);
                fwrite(yuv_frame->data[1], 1, y_size/4, out_fd);
                fwrite(yuv_frame->data[2], 1, y_size/4, out_fd);
            }

        }

        av_packet_unref(&packet);
    }


    if (out_fd)
    {
    
    
        fclose(out_fd);
    }

    avcodec_free_context(&codec_ctx);
    avformat_close_input(&fmt_ctx);
    avformat_free_context(fmt_ctx);
    

の:

std::string err2str(int err)
{
    
    
    char errStr[1024] = {
    
    0};
    av_strerror(err, errStr, sizeof(errStr));
    return errStr;
}

トランスコード後、pplay を使用して再生します。

转换成yuv后,播放: ffplay -s 640x352 -pix_fmt yuv420p 1.yuv

-s 640x352 はビデオの幅 x 高さです。


3. 説明する

3.1 sws_getContext

struct SwsContext* sws_getContext(int srcW,
                                  int srcH,
                                  enum AVPixelFormat srcFormat,
                                  int dstW,
                                  int dstH,
                                  enum AVPixelFormat dstFormat,
                                  int flags,
                                  SwsFilter *srcFilter,
                                  SwsFilter *dstFilter,
                                  const double *param )	

パラメータ:

  • srcW ソースビデオフレームの幅。
  • srcH ソースビデオフレームの高さ。
  • srcFormat ソースビデオフレームのピクセル形式フォーマット。
  • dstW 変換されたビデオ フレームの幅。
  • dstH 変換されたビデオ フレームの高さ。
  • dstFormat 変換されたビデオ フレームのピクセル フォーマット形式。
  • フラグ変換のアルゴリズム
  • srcFilter と dstFilter は、それぞれ入力/出力画像フィルタ情報を定義します。前面および背面画像フィルタリングを実行しない場合は、NULL を入力します。
  • param は、特定のスケーリング アルゴリズムに必要なパラメータを定義します。デフォルトは NULL です。

この関数は、基本的な変換情報を定義する SwsContext 構造体を返します。

例:

sws_getContext(w, h, YV12, w, h, NV12, 0, NULL, NULL, NULL);      // YV12->NV12 色彩空间转换
sws_getContext(w, h, YV12, w/2, h/2, YV12, 0, NULL, NULL, NULL);  // YV12图像缩小到原图1/4
sws_getContext(w, h, YV12, 2w, 2h, YN12, 0, NULL, NULL, NULL);    // YV12图像放大到原图4倍,并转换为NV12结构


3.2 sws_scale

int sws_scale(struct SwsContext *c,
              const uint8_t *const srcSlice[],
              const int srcStride[],
              int srcSliceY,
              int srcSliceH,
              uint8_t *const dst[],
              const int dstStride[] )		

パラメータ:

  • c は sws_getContext によって取得されるパラメータです。
  • srcSlice[] 入力データバッファ。
  • srcStride[] 各列のバイト数が実際の幅の値より大きくなります。
  • srcSliceY 最初の列で処理する位置。ここでは最初から処理するため、直接 0 を入力します。
  • srcSliceH の高さ;
  • dst[] ターゲット データ バッファ;
  • dstStride[] と同じ srcStride[]

デコード後のYUV形式のビデオピクセルデータはAVFrameのdata[0]、data[1]、data[2]に格納されますが、これらのピクセル値は連続して格納されるわけではなく、各行の後にいくつかの無効なピクセルが格納されます。有効なピクセル。
輝度 Y データを例にとると、data[0] には linesize[0] * height データの合計が含まれます。ただし、最適化などを考慮して、linesize[0]は実際にはwidth幅と等しくなく、widthよりも大きい値となります。そのため、sws_scale()による変換が必要となり、変換後は無効なデータが削除され、widthとlinesize[0]の値が等しくなります。
ここに画像の説明を挿入

4. 参考文献

https://ffmpeg.org/doxygen/trunk/group__libsws.html#gae531c9754c9205d90ad6800015046d74
https://www.cnblogs.com/cyyljw/p/8676062.html
ffmpeg コードで h264 から yuv を実現する
「FFmpeg + SDL ベースのビデオプレーヤーの作成」コースビデオ

おすすめ

転載: blog.csdn.net/Jay_Xio/article/details/125478945