Using libavformat and libavcodec(2)

来源:互联网 发布:php编程培训 编辑:程序博客网 时间:2024/06/05 07:02

Decoding Video Frames

As I've already mentioned, a video file can contain several audio and video streams, and each of those streams is split up into packets of a particular size. Our job is to read these packets one by one using libavformat, filter out all those that aren't part of the video stream we're interested in, and hand them on to libavcodec for decoding. In doing this, we'll have to take care of the fact that the boundary between two frames can occur in the middle of a packet.

 

Sound complicated? Luckily, we can encapsulate this whole process in a routine that simply returns the next video frame:

 

Now, all we have to do is sit in a loop, calling GetNextFrame() until it return false. Just one more thing to take care of: Most codecs return images in YUV420(one luminance and two chrominance channels, with the chrominance channels samples at half the spatial resolution of the luminance channel). Depending on what you want to do with the video data, you may want to convert this to RGB. (Note, though, that this is not necessary if all you want to do is diplay the video data; take a look at the X11 Xvideo extension, which does YUV-to-RGB and scaling in hardware.) Fortunately, libavcodec provides a conversion routine called img_convert, which does conversion between YUV and RGB as well as a variety of other image formats. The loop that decodes the video thus becomes:

 

The RGB image pFrameRGB(of type AVFrame*) is allocated like this: