ffmpeg录制视频

#if 0

#include 
#include 

#include "libavutil/avstring.h"
#include "libavutil/mathematics.h"
#include "libavutil/pixdesc.h"
#include "libavutil/imgutils.h"
#include "libavutil/dict.h"
#include "libavutil/parseutils.h"
#include "libavutil/samplefmt.h"
#include "libavutil/avassert.h"
#include "libavutil/time.h"

#include "libavformat/avformat.h"
#include "libavdevice/avdevice.h"
#include "libswscale/swscale.h"
#include "libavutil/opt.h"
#include "libavcodec/avfft.h"
#include "libswresample/swresample.h"

#include "libavcodec/avcodec.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/hwcontext.h"

/*
 * * Video encoding example
 * */
static void video_encode_example(const char* filename)
{
    AVCodec* codec;
    AVCodecContext* c = NULL;
    int i, ret, x, y, got_output;
    AVFrame* frame;
    AVPacket pkt;
    uint8_t endcode[] = { 0, 0, 1, 0xb7 };

    av_log_set_level(64);

    //AVBufferRef *device_ref = NULL;
    //AVBufferRef *hw_frames_ctx = NULL;
    //hw_frames_ctx = (AVBufferRef *)av_mallocz(sizeof(AVBufferRef));
    //if (!hw_frames_ctx) {
    //    ret = AVERROR(ENOMEM);
    //    return ;
    //}

    //ret = av_hwdevice_ctx_create(&device_ref, AV_HWDEVICE_TYPE_CUDA,"CUDA", NULL, 0);
    //if (ret < 0)
    //    return;

    //hw_frames_ctx = av_hwframe_ctx_alloc(device_ref);
    //if (!hw_frames_ctx) {
    //    av_log(NULL, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
    //    ret = AVERROR(ENOMEM);
    //    return;
    //}
    //av_buffer_unref(&device_ref);

    //c->hw_frames_ctx = av_buffer_ref(hw_frames_ctx);
    //if (!hw_frames_ctx) {
    //    av_log(NULL, AV_LOG_ERROR, "av_buffer_ref failed\n");
    //    ret = AVERROR(ENOMEM);
    //    return;
    //}

    printf("Encode video file %s\n", filename);

    /* find the video encoder */
    //codec = avcodec_find_encoder_by_name("hevc_nvenc");
    //codec = avcodec_find_encoder(AV_CODEC_ID_H265);
    codec = avcodec_find_encoder_by_name("h264_nvenc");
    //codec = avcodec_find_encoder(AV_CODEC_ID_H264);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }

    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }

    /* put sample parameters */
    c->bit_rate = 400000;
    /* resolution must be a multiple of two */
    c->width = 352;
    c->height = 288;
    /* frames per second */
    c->time_base.num = 1;
    c->time_base.den = 25;
    /* emit one intra frame every ten frames
     * check frame pict_type before passing frame
     * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
     * then gop_size is ignored and the output of encoder
     * will always be I frame irrespective to gop_size
     */
    c->gop_size = 10;
    c->max_b_frames = 1;
    c->pix_fmt = AV_PIX_FMT_YUV420P;//AV_PIX_FMT_CUDA;
    c->max_b_frames = 0;

    AVDictionary* param = 0;
    //H.264
    if (codec->id == AV_CODEC_ID_H264) {
        av_dict_set(¶m, "preset", "medium", 0);
        //av_dict_set(¶m, "tune", "zerolatency", 0);
    }
    //H.265
    if (codec->id == AV_CODEC_ID_H265 || codec->id == AV_CODEC_ID_HEVC) {
        //av_dict_set(¶m, "x265-params", "qp=20", 0);
        av_dict_set(¶m, "x265-params", "crf=25", 0);
        av_dict_set(¶m, "preset", "fast", 0);
        av_dict_set(¶m, "tune", "zero-latency", 0);
    }

    /* open it */
    if (avcodec_open2(c, codec, ¶m) < 0) {
        fprintf(stderr, "Could not open codec\n");
        system("pause");
        exit(1);
    }

    FILE* f;
    f = fopen(filename, "wb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }

    frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Could not allocate video frame\n");
        exit(1);
    }
    frame->format = c->pix_fmt;
    frame->width = c->width;
    frame->height = c->height;

    /* the image can be allocated by any means and av_image_alloc() is
     * just the most convenient way if av_malloc() is to be used */
    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 buffer\n");
        exit(1);
    }

    const int kFrameSize = 5000;    // 5000 / 25 = 200s
    for (i = 0; i < kFrameSize; i++) {
        av_init_packet(&pkt);
        pkt.data = NULL;    // packet data will be allocated by the encoder
        pkt.size = 0;

        fflush(stdout);
        /* prepare a dummy image */
        /* Y */
        for (y = 0; y < c->height; y++) {
            for (x = 0; x < c->width; x++) {
                frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
            }
        }

        /* Cb and Cr */
        for (y = 0; y < c->height / 2; y++) {
            for (x = 0; x < c->width / 2; x++) {
                frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
            }
        }

        frame->pts = i;

        /* encode the image */
        //ret = avcodec_encode_video2(c, &pkt, frame, &got_output);

        //avcodec_encode_video2(pCodecCtx, pPacket, pFrame, &got_picture);
        //avcodec_send_frame(pCodecCtx, pFrame);
        //avcodec_receive_packet(pCodecCtx, pPacket);

        //avcodec_send_frame(c, frame);
        //avcodec_receive_packet(c, &pkt);


        if (ret < 0) {
            fprintf(stderr, "Error encoding frame\n");
            exit(1);
        }
        got_output = 0;
        if (got_output) {
            printf("Write frame %3d (size=%5d)\n", i, pkt.size);
            fwrite(pkt.data, 1, pkt.size, f);
            av_packet_unref(&pkt);
        }



        //编码
        if (avcodec_send_frame(c, frame) >= 0)
        {
            while (avcodec_receive_packet(c, &pkt) >= 0)
            {
                printf("encoder success!\n");
                printf("Write frame %3d (size=%5d)\n", i, pkt.size);
                fwrite(pkt.data, 1, pkt.size, f);
                av_packet_unref(&pkt);

            }
        }






    }
    printf("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\n");
    /* get the delayed frames */
    for (got_output = 1; got_output; i++) {
        fflush(stdout);

        ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
        if (ret < 0) {
            fprintf(stderr, "Error encoding frame\n");
            exit(1);
        }

        if (got_output) {
            printf("Write frame %3d (size=%5d)\n", i, pkt.size);
            fwrite(pkt.data, 1, pkt.size, f);
            av_packet_unref(&pkt);
        }
    }

    /* add sequence end code to have a real MPEG file */
    fwrite(endcode, 1, sizeof(endcode), f);
    fclose(f);

    avcodec_close(c);
    av_free(c);
    av_freep(&frame->data[0]);
    av_frame_free(&frame);
    printf("\n");
}

int main(int argc, char** argv)
{
    /* register all the codecs */
    avcodec_register_all();
    avdevice_register_all();
    avfilter_register_all();
    av_register_all();
    avformat_network_init();

    video_encode_example("test.h264");

    getchar();

    return 0;
}
#endif


/*
 * Copyright (c) 2010 Nicolas George
 * Copyright (c) 2011 Stefano Sabatini
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

 /**
  * @file
  * API example for decoding and filtering
  * @example filtering_video.c
  */

#define _XOPEN_SOURCE 600 /* for usleep */

#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 


#include 
#include 

  //const char* filter_descr = "scale=78:24,transpose=cclock";
//const char* filter_descr = "[in]drawtext=fontfile='C\\:/Windows/Fonts/arial.ttf':fontsize=40:fontcolor=yellow:x=352/2:y=288/2:textfile=credits.txt:enable='between(t,6,12)'[out]";
const char* filter_descr = "drawtext=fontfile=adobe楷体.otf:text='AAAAAAAAA':x=200:y=200:fontsize=30:fontcolor=yellow:shadowy=0";





/* other way:
   scale=78:24 [scl]; [scl] transpose=cclock // assumes "[in]" and "[out]" to be input output pads respectively
 */

static AVFormatContext* fmt_ctx;
static AVCodecContext* dec_ctx;
AVFilterContext* buffersink_ctx;
AVFilterContext* buffersrc_ctx;
AVFilterGraph* filter_graph;
static int video_stream_index = -1;
static int64_t last_pts = AV_NOPTS_VALUE;


//保存PPM文件
void SaveFrame(AVFrame* pFrame, int width, int height, int iFrame) {
    FILE* pFile;//定义文件对象
    char szFilename[32];//定义输出文件名

    // Open file,打开文件
    sprintf(szFilename, "frame%d.ppm", iFrame);//格式化输出文件名
    pFile = fopen(szFilename, "wb");//打开输出文件
    if (pFile == NULL) {//检查输出文件是否打开成功
        return;
    }

    // Write header indicated how wide & tall the image is,向输出文件中写入文件头
    fprintf(pFile, "P6\n%d %d\n255\n", width, height);

    // Write pixel data,write the file one line a time,一次一行循环写入RGB24像素值
    int y;
    for (y = 0; y < height; y++) {
        fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, width * 3, pFile);
    }

    // Close file,关闭文件
    fclose(pFile);
}

static int open_input_file(const char* filename)
{
    int ret;
    AVCodec* dec;

    if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }

    if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }

    /* select the video stream */
    ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
        return ret;
    }
    video_stream_index = ret;

    /* create decoding context */
    dec_ctx = avcodec_alloc_context3(dec);
    if (!dec_ctx)
        return AVERROR(ENOMEM);
    avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);

    /* init the video decoder */
    if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
        return ret;
    }

    return 0;
}

static int init_filters(const char* filters_descr)
{
    char args[512];
    int ret = 0;
    const AVFilter* buffersrc = avfilter_get_by_name("buffer");
    const AVFilter* buffersink = avfilter_get_by_name("buffersink");
    AVFilterInOut* outputs = avfilter_inout_alloc();
    AVFilterInOut* inputs = avfilter_inout_alloc();
    AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };

    filter_graph = avfilter_graph_alloc();
    if (!outputs || !inputs || !filter_graph) {
        ret = AVERROR(ENOMEM);
        goto end;
    }

    /* buffer video source: the decoded frames from the decoder will be inserted here. */
    snprintf(args, sizeof(args),
        "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
        dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
        time_base.num, time_base.den,
        dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);

    ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
        args, NULL, filter_graph);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
        goto end;
    }

    /* buffer video sink: to terminate the filter chain. */
    ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
        NULL, NULL, filter_graph);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
        goto end;
    }

    ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,
        AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
        goto end;
    }

    /*
     * Set the endpoints for the filter graph. The filter_graph will
     * be linked to the graph described by filters_descr.
     */

     /*
      * The buffer source output must be connected to the input pad of
      * the first filter described by filters_descr; since the first
      * filter input label is not specified, it is set to "in" by
      * default.
      */
    outputs->name = av_strdup("in");
    outputs->filter_ctx = buffersrc_ctx;
    outputs->pad_idx = 0;
    outputs->next = NULL;

    /*
     * The buffer sink input must be connected to the output pad of
     * the last filter described by filters_descr; since the last
     * filter output label is not specified, it is set to "out" by
     * default.
     */
    inputs->name = av_strdup("out");
    inputs->filter_ctx = buffersink_ctx;
    inputs->pad_idx = 0;
    inputs->next = NULL;

    if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
        &inputs, &outputs, NULL)) < 0)
        goto end;

    if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
        goto end;

end:
    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);

    return ret;
}

static void display_frame(const AVFrame* frame, AVRational time_base)
{
    int x, y;
    uint8_t* p0, * p;
    int64_t delay;

    if (frame->pts != AV_NOPTS_VALUE) {
        if (last_pts != AV_NOPTS_VALUE) {
            /* sleep roughly the right amount of time;
             * usleep is in microseconds, just like AV_TIME_BASE. */
            delay = av_rescale_q(frame->pts - last_pts,
                time_base, AV_TIME_BASE_Q);
            if (delay > 0 && delay < 1000000)
            {
               // usleep(delay);
                Sleep(delay/1000);
            }
        }
        last_pts = frame->pts;
    }

    /* Trivial ASCII grayscale display. */
    p0 = frame->data[0];
    puts("\033c");
    for (y = 0; y < frame->height; y++) {
        p = p0;
        for (x = 0; x < frame->width; x++)
            putchar(" .-+#"[*(p++) / 52]);
        putchar('\n');
        p0 += frame->linesize[0];
    }
    fflush(stdout);
}

int main(int argc, char** argv)
{
    int ret;
    AVPacket packet;
    AVFrame* frame;
    AVFrame* filt_frame;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    frame = av_frame_alloc();
    filt_frame = av_frame_alloc();
    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }






    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;


#if 1
    struct SwsContext* sws_ctx = NULL;

    AVFrame* pFrameRGB = NULL;//保存输出24-bit RGB的PPM文件数据
    pFrameRGB = av_frame_alloc();
    if (pFrameRGB == NULL) {//检查初始化操作是否成功
        return -1;
    }

    AVCodecContext* pCodecCtx = dec_ctx;
    // Determine required buffer size and allocate buffer,根据像素格式及图像尺寸计算内存大小
    int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height, 1);
    uint8_t* buffer = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t));//为转换后的RGB24图像配置缓存空间

    // Assign appropriate parts of buffer to image planes in pFrameRGB Note that pFrameRGB is an AVFrame, but AVFrame is a superset of AVPicture
    // 为AVFrame对象安装图像缓存,将out_buffer缓存挂到pFrameYUV->data指针结构上
    av_image_fill_arrays(pFrameRGB->data, pFrameRGB->linesize, buffer, AV_PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height, 1);

    // Initialize SWS context for software scaling,设置图像转换像素格式为AV_PIX_FMT_RGB24
    sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_GRAY8,
                             pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB24, 
                             SWS_BILINEAR, NULL, NULL, NULL);





#endif


    int i = 0;

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index) {
            ret = avcodec_send_packet(dec_ctx, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
                break;
            }

            while (ret >= 0) {
                ret = avcodec_receive_frame(dec_ctx, frame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
                    break;
                }
                else if (ret < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
                    goto end;
                }

                frame->pts = frame->best_effort_timestamp;

                /* push the decoded frame into the filtergraph */
                if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    break;
                }

                /* pull filtered frames from the filtergraph */
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    //display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
                    //sws_scale(sws_ctx, (uint8_t const* const*)frame->data, frame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
                    sws_scale(sws_ctx, (uint8_t const* const*)filt_frame->data, filt_frame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);

                    if (++i <= 5)
                    {// Save the frame to disk,将前5帧图像存储到磁盘上
                        SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height, i);
                    }
                    else
                    {
                        goto end;
                    }

                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_packet_unref(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_free_context(&dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        exit(1);
    }

    exit(0);
}

你可能感兴趣的:(ffmpeg,c++,开发语言)