ffmpeg读取本地视频,获取视频帧

本文转自:https://blog.csdn.net/yinsui1839/article/details/80519742

/********
*本代码参考自雷神博客 
*
**********/
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavdevice/avdevice.h>
#include<libswresample/swresample.h>
#include <libavutil/pixfmt.h>
#include <libswscale/swscale.h>
#ifdef __cplusplus
};
#endif
 
#define MAX_AUDIO_FRAME_SIZE  192000
#define SAMPLE_PRT(fmt...)   \
    do {\
        printf("[%s]-%d: ", __FUNCTION__, __LINE__);\
        printf(fmt);\
       }while(0)
 
//'1': Use H.264 Bitstream Filter
#define USE_H264BSF 1
 
void save_pnm(AVFrame *pFrame, int w, int h,int index)
{
 
  FILE *fl;
  char szFilename[32];
  int  y;
 
  // Open file
  sprintf(szFilename, "%d.pnm", index);
  fl=fopen(szFilename, "wb");
 
  if(fl==NULL)
    return;
 
  fprintf(fl, "P6\n%d %d\n255\n", w, h); // 加入pnm文件头
  // Write pixel data
  for(y=0; y<h; y++)
  {
    fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, w*3, fl);
  }
 
  // Close file
  fclose(fl);
 
}
 
 
int main(int argc, char *argv[])
{
    char *file_path = "/home/grid/hefang";
 
    AVFormatContext *pFormatCtx;
    AVCodecContext *pCodecCtx;
    AVCodec *pCodec;
    AVFrame *pFrame, *pFrameRGB;
    AVPacket *packet;
    uint8_t *out_buffer;
 
    static struct SwsContext *img_convert_ctx;
 
    int videoStream, i, numBytes;
    int ret, got_picture;
 
    av_register_all(); //初始化FFMPEG  调用了这个才能正常适用编码器和解码器
 
    //Allocate an AVFormatContext.
    pFormatCtx = avformat_alloc_context();
 
    if (avformat_open_input(&pFormatCtx, file_path, NULL, NULL) != 0) {
        SAMPLE_PRT("open file error\n");
        return -1;
    }
 
    if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
        SAMPLE_PRT("Could't find stream infomation\n");
        return -1;
    }
 
    videoStream = -1;
 
    for (i = 0; i < pFormatCtx->nb_streams; i++) {
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStream = i;
        }
    }
 
    if (videoStream == -1) {
        SAMPLE_PRT("no find vedio_stream");
        return -1;
    }
 
    ///查找解码器
    pCodecCtx = pFormatCtx->streams[videoStream]->codec;
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
 
    if (pCodec == NULL) {
        SAMPLE_PRT(" not found decodec.\n");
        return -1;
    }
 
    ///打开解码器
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        SAMPLE_PRT("Could not open decodec.");
        return -1;
    }
 
    pFrame = av_frame_alloc();
    pFrameRGB = av_frame_alloc();
 
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
            pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,
            AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
 
    numBytes = avpicture_get_size(AV_PIX_FMT_RGB24, pCodecCtx->width,pCodecCtx->height);
 
    out_buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
    avpicture_fill((AVPicture *) pFrameRGB, out_buffer, AV_PIX_FMT_RGB24,
            pCodecCtx->width, pCodecCtx->height);
 
    int y_size = pCodecCtx->width * pCodecCtx->height;
 
    packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
    av_new_packet(packet, y_size); //分配packet的数据
 
    av_dump_format(pFormatCtx, 0, file_path, 0); //输出视频信息
 
    int index = 0;
 
    while (av_read_frame(pFormatCtx, packet) >=0){
        if (packet->stream_index == videoStream) {
            ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture,packet);
 
            if (ret < 0) {
                SAMPLE_PRT("decode error.");
                return -1;
            }
 
            if (got_picture) {
                sws_scale(img_convert_ctx,
                        (uint8_t const * const *) pFrame->data,
                        pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data,
                        pFrameRGB->linesize);
 
                save_pnm(pFrameRGB, pCodecCtx->width,pCodecCtx->height,index++); //保存图片
                if (index > 100) return 0; //100张
            }
        }
        av_free_packet(packet);
    }
    av_free(out_buffer);
    av_free(pFrameRGB);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);
 
    return 0;
}

以下代码转自:https://blog.csdn.net/boonya/article/details/79474754

#include <stdio.h>
#include <stdlib.h>
//编码
#include "libavcodec/avcodec.h"
//封装格式处理
#include "libavformat/avformat.h"
//像素处理
#include "libswscale/swscale.h"

int main()
{
    //获取输入输出文件名
    const char *input = "test.mp4";
    const char *output = "test.yuv";

    //1.注册所有组件
    av_register_all();

    //封装格式上下文,统领全局的结构体,保存了视频文件封装格式的相关信息
    AVFormatContext *pFormatCtx = avformat_alloc_context();

    //2.打开输入视频文件
    if (avformat_open_input(&pFormatCtx, input, NULL, NULL) != 0)
    {
        printf("%s","无法打开输入视频文件");
        return;
    }

    //3.获取视频文件信息
    if (avformat_find_stream_info(pFormatCtx,NULL) < 0)
    {
        printf("%s","无法获取视频文件信息");
        return;
    }

    //获取视频流的索引位置
    //遍历所有类型的流(音频流、视频流、字幕流),找到视频流
    int v_stream_idx = -1;
    int i = 0;
    //number of streams
    for (; i < pFormatCtx->nb_streams; i++)
    {
        //流的类型
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            v_stream_idx = i;
            break;
        }
    }

    if (v_stream_idx == -1)
    {
        printf("%s","找不到视频流\n");
        return;
    }

    //只有知道视频的编码方式,才能够根据编码方式去找到解码器
    //获取视频流中的编解码上下文
    AVCodecContext *pCodecCtx = pFormatCtx->streams[v_stream_idx]->codec;
    //4.根据编解码上下文中的编码id查找对应的解码
    AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if (pCodec == NULL)
    {
        printf("%s","找不到解码器\n");
        return;
    }

    //5.打开解码器
    if (avcodec_open2(pCodecCtx,pCodec,NULL)<0)
    {
        printf("%s","解码器无法打开\n");
        return;
    }

    //输出视频信息
    printf("视频的文件格式:%s",pFormatCtx->iformat->name);
    printf("视频时长:%d", (pFormatCtx->duration)/1000000);
    printf("视频的宽高:%d,%d",pCodecCtx->width,pCodecCtx->height);
    printf("解码器的名称:%s",pCodec->name);

    //准备读取
    //AVPacket用于存储一帧一帧的压缩数据(H264)
    //缓冲区,开辟空间
    AVPacket *packet = (AVPacket*)av_malloc(sizeof(AVPacket));

    //AVFrame用于存储解码后的像素数据(YUV)
    //内存分配
    AVFrame *pFrame = av_frame_alloc();
    //YUV420
    AVFrame *pFrameYUV = av_frame_alloc();
    //只有指定了AVFrame的像素格式、画面大小才能真正分配内存
    //缓冲区分配内存
    uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
    //初始化缓冲区
    avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);

    //用于转码(缩放)的参数,转之前的宽高,转之后的宽高,格式等
    struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,
                                                pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P,
                                                SWS_BICUBIC, NULL, NULL, NULL);
    int got_picture, ret;

    FILE *fp_yuv = fopen(output, "wb+");

    int frame_count = 0;

    //6.一帧一帧的读取压缩数据
    while (av_read_frame(pFormatCtx, packet) >= 0)
    {
        //只要视频压缩数据(根据流的索引位置判断)
        if (packet->stream_index == v_stream_idx)
        {
            //7.解码一帧视频压缩数据,得到视频像素数据
            ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
            if (ret < 0)
            {
                printf("%s","解码错误");
                return;
            }

            //为0说明解码完成,非0正在解码
            if (got_picture)
            {
                //AVFrame转为像素格式YUV420,宽高
                //2 6输入、输出数据
                //3 7输入、输出画面一行的数据的大小 AVFrame 转换是一行一行转换的
                //4 输入数据第一列要转码的位置 从0开始
                //5 输入画面的高度
                sws_scale(sws_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                          pFrameYUV->data, pFrameYUV->linesize);

                //输出到YUV文件
                //AVFrame像素帧写入文件
                //data解码后的图像像素数据(音频采样数据)
                //Y 亮度 UV 色度(压缩了) 人对亮度更加敏感
                //U V 个数是Y的1/4
                int y_size = pCodecCtx->width * pCodecCtx->height;
                fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv);
                fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv);
                fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv);

                frame_count++;
                printf("解码第%d帧\n",frame_count);
            }
        }

        //释放资源
        av_free_packet(packet);
    }

    fclose(fp_yuv);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_free_context(pFormatCtx);
}

Reference:

https://blog.csdn.net/yinsui1839/article/details/80519742

https://blog.csdn.net/boonya/article/details/79474754

https://blog.csdn.net/leixiaohua1020/article/details/8652605

https://blog.csdn.net/u011304970/article/details/72995308

猜你喜欢

转载自blog.csdn.net/piaopiaopiaopiaopiao/article/details/88183523