On the internet for a long time this aspect of the content, found that the online code is too old, the use of the old to even the latest version of the FFmpeg are not included, so for me this beginner is too pit pull. But after many times to find FFmpeg's header files and combined with the content of the Internet, finally successful can decode pull. Now put it out.
The first is to initialize some of the parameters
[CPP]View Plaincopy
- The following initializes the H264 decoding library
- Avcodec_init ();
- Av_register_all ();
- Avframe *pframe_ = NULL;
- Avcodeccontext *codec_ = Avcodec_alloc_context ();
- /* Find the Video encoder */
- Avcodec *videocodec = Avcodec_find_decoder (codec_id_h264);
- if (!VIDEOCODEC)
- {
- cout << "codec not found!" << Endl;
- return-1;
- }
- Initialization parameters, the following parameters should be determined by the specific business
- Codec_->time_base.num = 1;
- Codec_->frame_number = 1; //One video frame per package
- Codec_->codec_type = Avmedia_type_video;
- codec_->bit_rate = 0;
- Codec_->time_base.den = 30; //Frame rate
- Codec_->width = 1280; //Video width
- Codec_->height = 720; //Video High
- if (Avcodec_open (codec_, Videocodec) >= 0)
- Pframe_ = Avcodec_alloc_frame (); //Allocate video frame
- Else
- return-1;
The following is the specific decoding code
[CPP]View Plaincopy
- Avpacket packet = {0};
- int framefinished = dwbufsize; //This is a random number, no effect
- Packet.data = pbuffer; //Fill in a pointer to the full H264 data frame here
- Packet.size = dwbufsize; //This fills in the size of the H264 data frame
- Let's start with the real decoding.
- Avcodec_decode_video2 (Codec_, Pframe_, &framefinished, &packet);
- if (framefinished)//Successful decoding
- {
- int picsize = codec_->height * codec_->width;
- int newSize = picsize * 1.5;
- //Request Memory
- unsigned char *buf = new unsigned char[newsize];
- int height = p->codec->height;
- int width = p->codec->width;
- //Write Data
- int a=0,i;
- For (i=0; i
- {
- memcpy (buf+a,pframe_->data[0] + i * pframe_->linesize[0], width);
- A+=width;
- }
- For (i=0; i
- {
- memcpy (buf+a,pframe_->data[1] + i * pframe_->linesize[1], WIDTH/2);
- A+=WIDTH/2;
- }
- For (i=0; i
- {
- memcpy (buf+a,pframe_->data[2] + i * pframe_->linesize[2], WIDTH/2);
- A+=WIDTH/2;
- }
- //===============
- //Come here, buf inside is already the data of yuv420p, can do any processing to it pull!
- //===============
- Delete [] buf;
- }
But I found that this decoding is CPU intensive, my Core2 E7400 2.8G processor, decoding 1920x1080 resolution 30 frames per second of video, CPU utilization can be used to nearly 50%.
PS: The original Avcodec_decode_video2 This function will modify the parameters inside the codec_, that is, if the original filling rate is 1280x720, run Avcodec_decode_video2 after codec_ It becomes the resolution of the actual video.
Decode the H264 data stream into yuv420p with FFmpeg