音视频

ffmpeg_sample解读_encode_audio

2020-10-28  本文已影响0人  刘佳阔

title: ffmpeg_sample解读_encode_audio
date: 2020-10-23 10:15:02
tags: [读书笔记]
typora-copy-images-to: ./imgs
typora-root-url: ./imgs


总结

和编码音频类似.这是编码产生视频文件.所以视频需要的一些额外参数需要我们手动指定

流程图如下.直接用别人的了

8744338-0c1dd5621924ac5a

源码



/**
 * @file
 * video encoding with libavcodec API example
 *
 * @example encode_video.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <libavcodec/avcodec.h>

#include <libavutil/opt.h>
#include <libavutil/imgutils.h>

static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt,
                   FILE *outfile) {
    int ret;

    /* send the frame to the encoder */
    if (frame)
        printf("Send frame %3"PRId64"\n", frame->pts);

    //把原始帧送入编码器. 编码器由编码器上下文的参数决定
    ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending a frame for encoding\n");
        exit(1);
    }

    while (ret >= 0) {
        //从编码器中得到编码完成后的数据packet.如果有的话
        ret = avcodec_receive_packet(enc_ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during encoding\n");
            exit(1);
        }
        //向outfile 写入 已1字节为单位.共pkt->size个数据.数据来自pkt->data. 是之前编码来的
        printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
        fwrite(pkt->data, 1, pkt->size, outfile);
        av_packet_unref(pkt);
    }
}

/** 编码视频
 * avcodec_find_encoder_by_name:根据指定的编码器名称查找注册的解码器。
avcodec_alloc_context3:为AVCodecContext分配内存。
avcodec_open2:打开解码器。
avcodec_send_frame:将AVFrame非压缩数据给编码器。详细介绍见FFmpeg音频解码的编解码API介绍部分。
avcodec_receive_packet:获取到编码后的AVPacket数据。
av_frame_get_buffer: 为音频或视频数据分配新的buffer。在调用这个函数之前,
 必须在AVFame上设置好以下属性:format(视频为像素格式,音频为样本格式)、nb_samples(样本个数,针对音频)、
 channel_layout(通道类型,针对音频)、width/height(宽高,针对视频)。
av_frame_make_writable:确保AVFrame是可写的,尽可能避免数据的复制。
如果AVFrame不是是可写的,将分配新的buffer和复制数据。

作者:smallest_one
链接:https://www.jianshu.com/p/7543458706ed
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 * @param argc
 * @param argv
 * @return
 */
int encode_video_main(int argc, char **argv) {
    const char *filename, *codec_name;
    const AVCodec *codec;
    AVCodecContext *c = NULL;
    int i, ret, x, y;
    FILE *f;
    AVFrame *frame;
    AVPacket *pkt;
    uint8_t endcode[] = {0, 0, 1, 0xb7};

    if (argc <= 2) {
        fprintf(stderr, "Usage: %s <output file> <codec name>\n", argv[0]);
        exit(0);
    }
    filename = argv[1];
    codec_name = argv[2];

    /* find the mpeg1video encoder */
    //通过名称查找编码器.和通过编码id查找是一样的
    codec = avcodec_find_encoder_by_name(codec_name);
    if (!codec) {
        fprintf(stderr, "Codec '%s' not found\n", codec_name);
        exit(1);
    }
// 分配编码器上下文
    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }
//初始化编码文件后的packet
    pkt = av_packet_alloc();
    if (!pkt)
        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 = (AVRational) {1, 25}; //  1/25
    c->framerate = (AVRational) {25, 1}; //  25/1

    /* 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
     */
    //每10秒发送一个i帧,帧作为关键帧.会忽略gop大小, 两个i帧的间隔就是gop_zise的大小
    c->gop_size = 10;
    c->max_b_frames = 1;//最大b帧数目. b帧是双向帧.
    c->pix_fmt = AV_PIX_FMT_YUV420P; // 视频格式 yvu420p

    if (codec->id == AV_CODEC_ID_H264)
        //给 编码上下文的priv_data中设置 preset属性. 值是slow
        av_opt_set(c->priv_data, "preset", "slow", 0);

    /* open it *///用编码器初始化 编码器上下文
    ret = avcodec_open2(c, codec, NULL);
    if (ret < 0) {
        fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
        exit(1);
    }

    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);
    }
    //指定帧的格式和宽高  pix_fmt 是yuv420p
    frame->format = c->pix_fmt;
    frame->width = c->width;
    frame->height = c->height;

    //给帧里的data缓冲分配控件.编码需要向data里写数据
    ret = av_frame_get_buffer(frame, 0);
    if (ret < 0) {
        fprintf(stderr, "Could not allocate the video frame data\n");
        exit(1);
    }

    /* encode 1 second of video */
    //编码1s的视频数据. 产生25帧.也就是25个frame.
    for (i = 0; i < 25; i++) {
        //清空命令行输出
        fflush(stdout);

        /* make sure the frame data is writable */
        //确保frame里的data缓冲可以写入数据.如果不能写如.就重新分配空间给data
        ret = av_frame_make_writable(frame);
        if (ret < 0)
            exit(1);

        /* prepare a dummy image *///随机产生的yuv数据 yuv 是4 :1:1 产生
        /* 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;
            }
        }
//pts  播放时间戳.就是按帧生成的顺序来的. 目前到这里.还没有看到i帧相关的东西
        frame->pts = i;

        /* encode the image *///编码原始帧
        encode(c, frame, pkt, f);
    }

    /* flush the encoder */
    encode(c, NULL, pkt, f);

    /* add sequence end code to have a real MPEG file */
    if (codec->id == AV_CODEC_ID_MPEG1VIDEO || codec->id == AV_CODEC_ID_MPEG2VIDEO)
        fwrite(endcode, 1, sizeof(endcode), f);
    fclose(f);

    avcodec_free_context(&c);
    av_frame_free(&frame);
    av_packet_free(&pkt);

    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读