The simplest Video Encoder Based on FFMPEG-new version (YUV encoding is hevc (h.265 ))

Source: Internet
Author: User
An example of a video encoder based on FFMPEG was created a while ago:
The simplest Video Encoder Based on FFMPEG (YUV encoding: H.264)
In this example, YUV pixel data (yuv420p) can be encoded as H.264 code streams. Because FFMPEG now supports libx265, the above example of H.264 encoding is upgraded to h.265 (hevc.
The earlier FFMPEG class library (about a few months ago, my Compilation Time is 5.4.05.06) has a problem with h.265 encoding support. When I started debugging, I thought there was a problem with my code. After several modifications, I did not find a solution. The problem was finally found to be a problem with the class library itself. The problem was solved after the new version of the class library was changed (I compile the time here is 4.04.09.16.
Process

The following is a flowchart of the FFMPEG video. This process not only can encode the H.264/h.265 code streams, but also can encode MPEG4/MPEG2/VP9/Vp8 and other code streams. In fact, FFmpeg is used to encode videos in the same way. In the figure, the blue background function is the function that actually outputs data. The Light Green function is the video encoding function.


 

Briefly introduce the meaning of each function in the process (the previous YUV code was written in H.264. copy and paste it here ):
Av_register_all (): registers all the codecs of FFMPEG.
Avformat_alloc_output_context2 (): Initialize avformatcontext of the output code stream.
Avio_open (): Open the output file.
Av_new_stream (): creates an avstream of the output code stream.
Avcodec_find_encoder (): Find the encoder.
Avcodec_open2 (): Enable the encoder.
Avformat_write_header (): Write a file header (this function is not required for some encapsulation formats without a file header. For example, mpeg2ts ).
Avcodec_encode_video2 (): encode a video. Encode avframe (storing YUV pixel data) into avpacket (storing stream data in H.264 and other formats ).
Av_write_frame (): Write the encoded video stream to a file.
Flush_encoder (): This function is called after the input pixel data is read. Used to output the remaining avpacket In the encoder.
Av_write_trailer (): Write the end of a file (this function is not required for some encapsulation formats without a file header. For example, mpeg2ts ).


Directly paste the code below the code
/*** The simplest FFMPEG-Based Video Encoder ** simplest FFMPEG Video Encoder ** leixiao Lei Xiaohua * [email protected] * China Media University/Digital TV technology * Communication University of China/Digital TV technology * http://blog.csdn.net/leixiaohua1020 ** this program realizes the YUV pixel data encoding as video code stream (hevc (h.265 ), h264, MPEG2, Vp8, etc ). * Is the simplest tutorial on FFMPEG video encoding. * By studying this example, you can understand the FFMPEG encoding process. * This software encode yuv420p data to hevc (h.265) bitstream (or * H. 264, MPEG2, Vp8 etc .). * it's the simplest video encoding software based on FFMPEG. * suitable for beginner of FFMPEG */# include <stdio. h> extern "C" {# include "libavutil \ OPT. H "# include" libavcodec \ avcodec. H "# include" libavformat \ avformat. H "# include" libswscale \ swscale. H "}; int flush_encoder (avformatcontext * fmt_ctx, unsigned int Str Eam_index) {int ret; int got_frame; avpacket enc_pkt; If (! (Fmt_ctx-> streams [stream_index]-> codec-> capabilities & codec_cap_delay) return 0; while (1) {printf ("flushing stream # % u encoder \ n", stream_index); // ret = encode_write_frame (null, stream_index, & got_frame); enc_pkt.data = NULL; enc_pkt.size = 0; av_init_packet (& enc_pkt); ret = avcodec_encode_video2 (fmt_ctx-> streams [stream_index]-> codec, & enc_pkt, null, & got_frame); av_frame_free (null ); if (Ret <0) B Reak; If (! Got_frame) {ret = 0; break;} printf ("succeed to encode 1 frame! Encoding successful 1 frame! \ N ");/* MUX encoded frame */ret = av_write_frame (fmt_ctx, & enc_pkt); If (Ret <0) break;} return ret ;} int main (INT argc, char * argv []) {avformatcontext * pformatctx; avoutputformat * FMT; avstream * video_st; avcodeccontext * pcodecctx; avcodec * pcodec; uint8_t * picture_buf; avframe * picture; int size; // file * in_file = fopen ("src0415480x272.yuv", "rb"); // input YUV data video YUV source file * in_file = fopen ("ds_480x272.yu V "," rb "); // input YUV data video YUV source file int in_w = 480, in_h = 272; // width/height // frames to encodeint framenum = 100; // const char * out_file = "src01.h264"; // output filepath output file path // const char * out_file = "src01.ts"; // const char * out_file = "src01.hevc "; const char * out_file = "Ds. hevc "; av_register_all (); // Method1 method 1. combined use several functions pformatctx = avformat_alloc_context (); // guess format FMt = av_guess_format (null, out_file, Null); pformatctx-> oformat = FMT; // method 2 method 2. more automated // avformat_alloc_output_context2 (& pformatctx, null, null, out_file); // FMt = pformatctx-> oformat; // output format pay attention to the output path if (avio_open (& pformatctx-> Pb, out_file, avio_flag_read_write) <0) {printf ("failed to open output file! Failed to open the output file "); Return-1;} video_st = avformat_new_stream (pformatctx, 0); video_st-> time_base.num = 1; video_st-> time_base.den = 25; if (video_st = NULL) {return-1 ;}// Param that must setpcodecctx = video_st-> codec; // pcodecctx-> codec_id = av_codec_id_hevc; pcodecctx-> codec_id = FMT-> video_codec; pcodecctx-> codec_type = avmedia_type_video; pcodecctx-> pix_fmt = bytes; pcodecctx-> width = in_w; pcodecctx -> Height = in_h; pcodecctx-> time_base.num = 1; pcodecctx-> time_base.den = 25; pcodecctx-> bit_rate = 400000; pcodecctx-> gop_size = 250; // h264 // pcodecctx-> me_range = 16; // pcodecctx-> max_qdiff = 4; // pcodecctx-> qcompress = 0.6; pcodecctx-> qmin = 10; pcodecctx-> Qmax = 51; // optional parampcodecctx-> max_ B _frames = 3; // set optionavdictionary * Param = 0; // h.2if (pcodecctx-> codec_id = Hangzhou) {av_dict _ Set (? M, "preset", "slow", 0); av_dict_set (? M, "tune", "zerolatency", 0);} // h.265if (pcodecctx-> codec_id = av_codec_id_h265) {av_dict_set (? M, "x265-params", "QP = 20", 0); av_dict_set (? M, "preset", "ultrafast", 0); av_dict_set (? M, "tune", "zero-latency", 0);} // dump information output format information av_dump_format (pformatctx, 0, out_file, 1 ); pcodec = avcodec_find_encoder (pcodecctx-> codec_id); If (! Pcodec) {printf ("can not find encoder! No suitable encoder found! \ N "); Return-1;} If (avcodec_open2 (pcodecctx, pcodec ,? M) <0) {printf ("failed to open encoder! An error occurred while enabling the encoder! \ N "); Return-1;} picture = avcodec_alloc_frame (); size = avpicture_get_size (pcodecctx-> pix_fmt, pcodecctx-> width, pcodecctx-> height ); picture_buf = (uint8_t *) av_malloc (size); watermark (avpicture *) picture, picture_buf, pcodecctx-> pix_fmt, pcodecctx-> width, pcodecctx-> height ); // Write File Header avformat_write_header (pformatctx, null); avpacket Pkt; int y_size = pcodecctx-> width * pcodecctx-> Hei Ght; av_new_packet (& Pkt, y_size * 3); For (INT I = 0; I <framenum; I ++) {// read YUV to read yuvif (fread (picture_buf, 1, y_size * 3/2, in_file) <0) {printf ("failed to read YUV data! File Read error \ n "); Return-1;} else if (feof (in_file) {break;} picture-> data [0] = picture_buf; // brightness ypicture-> data [1] = picture_buf + y_size; // U picture-> data [2] = picture_buf + y_size * 5/4; // v // ptspicture-> PTS = I; int got_picture = 0; // encode: int ret = avcodec_encode_video2 (pcodecctx, & Pkt, picture, & got_picture ); if (Ret <0) {printf ("failed to encode! Encoding Error! \ N "); Return-1;} If (got_picture = 1) {printf (" succeed to encode 1 frame! Encoding successful 1 frame! \ N "); Pkt. stream_index = video_st-> index; ret = av_write_frame (pformatctx, & Pkt); av_free_packet (& Pkt) ;}// flush encoderint ret = flush_encoder (pformatctx, 0 ); if (Ret <0) {printf ("flushing encoder failed \ n"); Return-1;} // Write File trailer write the end Of the file av_write_trailer (pformatctx ); // clean if (video_st) {avcodec_close (video_st-> codec); av_free (picture); av_free (picture_buf);} avio_close (pformatctx-> Pb ); avformat_free_context (pformatctx); fclose (in_file); Return 0 ;}





Result

Software running (limited by the file volume, the number of original YUV frames is only 100 ):


This time I changed an interesting YUV sequence. I have been tired of reading the YUV standard test sequence before. The sequence in this new TV series is more vivid. Shows the YUV sequence.

The encoded hevc (h.265) code stream:
 

Download

SourceForge Project address:

Https://sourceforge.net/projects/simplestffmpegvideoencoder/

Csdn:

Http://download.csdn.net/detail/leixiaohua1020/8001515


The simplest Video Encoder Based on FFMPEG-new version (YUV encoding is hevc (h.265 ))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.