Chinaunix首页 | 论坛 | 博客
  • 博客访问: 388921
  • 博文数量: 55
  • 博客积分: 1907
  • 博客等级: 上尉
  • 技术积分: 869
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-04 19:30
文章分类

全部博文(55)

文章存档

2011年(32)

2010年(23)

分类: 嵌入式

2011-02-14 15:25:08

An ffmpeg and SDL Tutorial
 
Tutorial 01: Making ScreencapsCode:
(截取于ffplay)
 
Overview

Movie files have a few basic components. First, the file itself is called a container, and the type of container determines where the information in the file goes. Examples of containers are AVI and Quicktime(Apple公司开发的一种音视频文件格式). Next, you have a bunch of streams; for example, you usually have an audio stream and a video stream. (A "stream" is just a fancy word for "a succession of data elements made available over time".) The data elements in a stream are called frames. Each stream is encoded by a different kind of codec. The codec defines how the actual data is COded and DECoded - hence the name CODEC. Examples of codecs are DivX(一种数字多媒体压缩技术) and MP3(一种音频压缩格式). Packets are then read from the stream. Packets are pieces of data that can contain bits of data that are decoded into raw frames that we can finally manipulate for our application. For our purposes, each packet contains complete frames, or multiple frames in the case of audio.

At its very basic level, dealing with video and audio streams is very easy:

  1. 10 OPEN video_stream FROM video.avi
  2. 20 READ packet FROM video_stream INTO frame
  3. 30 IF frame NOT COMPLETE GOTO 20
  4. 40 DO SOMETHING WITH frame
  5. 50 GOTO 20
Handling multimedia with ffmpeg is pretty much as simple as this program, although some programs might have a very complex "DO SOMETHING" step. So in this tutorial, we're going to open a file, read from the video stream inside it, and our DO SOMETHING is going to be writing the frame to a PPM file.

Opening the File

First, let's see how we open a file in the first place. With ffmpeg, you have to first initialize the library. (Note that some systems might have to use and instead.)

  1. #include <avcodec.h>
  2. #include <avformat.h>
  3. ...
  4. int main(int argc, charg *argv[]) {
  5. av_register_all();
This registers all available file formats and codecs with the library so they will be used automatically when a file with the corresponding format/codec is opened. Note that you only need to call () once, so we do it here in main(). If you like, it's possible to register only certain individual file formats and codecs, but there's usually no reason why you would have to do that.

Now we can actually open the file:

  1. AVFormatContext *pFormatCtx;

  2. // Open video file

  3. if(av_open_input_file(&pFormatCtx, argv[1], NULL, 0, NULL)!=0)
  4.   return -1;  // could not open file
We get our filename from the first argument. This function reads the file header and stores information about the file format in the structure we have given it. The last three arguments are used to specify the file format, buffer size, and format options, but by setting this to NULL or 0, libavformat will auto-detect these.

This function only looks at the header, so next we need to check out the stream information in the file.:

  1. // Retrieve stream information

  2. if(av_find_stream_info(pFormatCtx)<0)
  3.   return -1;  // could not find stream information
This function populates pFormatCtx->streams with the proper information. We introduce a handy debugging function to show us what's inside:
  1. // Dump information about file onto standard error

  2. dump_format(pFormatCtx, 0, argv[1], 0);
Now pFormatCtx->streams is just an array of pointers, of size pFormatCtx->nb_streams, so let's walk through it until we find a video stream.
  1. int i;
  2. AVCodecContext *pCodecCtx;

  3. // Find the first video stream

  4. videoStream=-1;
  5. for(i=0; i<pFormatCtx->nb_streams; i++)
  6.   if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO) {
  7.     videoStream=i;
  8.     break;
  9.   }
  10. if(videoStream==-1)
  11.   return -1; // Didn't find a video stream


  12. // Get a pointer to the codec context for the video stream

  13. pCodecCtx=pFormatCtx->streams[videoStream]->codec;
The stream's information about the codec is in what we call the "codec context." This contains all the information about the codec that the stream is using, and now we have a pointer to it. But we still have to find the actual codec and open it:
  1. AVCodec *pCodec;

  2. // Find the decoder for the video stream

  3. pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
  4. if(pCodec==NULL) {
  5.   fprintf(stderr, "Unsupported codec!\n");
  6.   return -1; // Codec not found

  7. }
  8. // Open codec

  9. if(avcodec_open(pCodecCtx, pCodec)<0)
  10.   return -1;
Some of you might remember from the old tutorial that there were two other parts to this code: adding CODEC_FLAG_TRUNCATED to pCodecCtx->flags and adding a hack to correct grossly incorrect frame rates. These two fixes aren't in ffplay.c anymore, so I have to assume that they are not necessary anymore. There's another difference to point out since we removed that code: pCodecCtx->time_base now holds the frame rate information. time_base is a struct that has the numerator and denominator (). We represent the frame rate as a fraction because many codecs have non-integer frame rates (like NTSC's 29.97fps).

Storing the Data

Now we need a place to actually store the frame:

  1. AVFrame *pFrame;

  2. // Allocate video frame

  3. pFrame=avcodec_alloc_frame();
Since we're planning to output PPM files, which are stored in 24-bit RGB, we're going to have to convert our frame from its native format to RGB. ffmpeg will do these conversions for us. For most projects (including ours) we're going to want to convert our initial frame to a specific format. Let's allocate a frame for the converted frame now.
  1. // Allocate an AVFrame structure

  2. pFrameRGB=avcodec_alloc_frame();
  3. if(pFrameRGB==NULL)
  4.   return -1;
Even though we've allocated the frame, we still need a place to put the raw data when we convert it. We use to get the size we need, and allocate the space manually:
  1. uint8_t *buffer;
  2. int numBytes;
  3. // Determine required buffer size and allocate buffer

  4. numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,
  5.                             pCodecCtx->height);
  6. buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
is ffmpeg's malloc that is just a simple wrapper around malloc that makes sure the memory addresses are aligned and such. It will not protect you from memory leaks, double freeing, or other malloc problems.

Now we use to associate the frame with our newly allocated buffer. About the cast: the AVPicture struct is a subset of the struct - the beginning of the AVFrame struct is identical to the AVPicture struct.

  1. // Assign appropriate parts of buffer to image planes in pFrameRGB

  2. // Note that pFrameRGB is an AVFrame, but AVFrame is a superset

  3. // of AVPicture

  4. avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,
  5.                 pCodecCtx->width, pCodecCtx->height);
Finally! Now we're ready to read from the stream!

Reading the Data

What we're going to do is read through the entire video stream by reading in the packet, decoding it into our frame, and once our frame is complete, we will convert and save it.

  1. int frameFinished;
  2. AVPacket packet;

  3. i=0;
  4. while(av_read_frame(pFormatCtx, &packet)>=0) {
  5.   // Is this a packet from the video stream?

  6.   if(packet.stream_index==videoStream) {
  7.     // Decode video frame

  8.     avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,
  9.                          packet.data, packet.size);
  10.     
  11.     // Did we get a video frame?

  12.     if(frameFinished) {
  13.     // Convert the image from its native format to RGB

  14.         img_convert((AVPicture *)pFrameRGB, PIX_FMT_RGB24,
  15.             (AVPicture*)pFrame, pCodecCtx->pix_fmt,
  16.             pCodecCtx->width, pCodecCtx->height);
  17.     
  18.         // Save the frame to disk

  19.         if(++i<=5)
  20.           SaveFrame(pFrameRGB, pCodecCtx->width,
  21.                     pCodecCtx->height, i);
  22.     }
  23.   }
  24.     
  25.   // Free the packet that was allocated by av_read_frame

  26.   av_free_packet(&packet);
  27. }
  1. A note on packets
  2. Technically a packet can contain partial frames or other bits of data, but ffmpeg's parser ensures that the packets we get contain either
  3. complete or multiple frames.
The process, again, is simple: () reads in a packet and stores it in the struct. Note that we've only allocated the packet structure - ffmpeg allocates the internal data for us, which is pointed to by packet.data. This is freed by the () later. () converts the packet to a frame for us. However, we might not have all the information we need for a frame after decoding a packet, so avcodec_decode_video() sets frameFinished for us when we have the next frame. Finally, we use () to convert from the native format (pCodecCtx->pix_fmt) to RGB. Remember that you can cast an pointer to an pointer. Finally, we pass the frame and height and width information to our SaveFrame function.

Now all we need to do is make the SaveFrame function to write the RGB information to a file in PPM format. We're going to be kind of sketchy on the PPM format itself; trust us, it works.

  1. void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
  2.   FILE *pFile;
  3.   char szFilename[32];
  4.   int y;
  5.   
  6.   // Open file

  7.   sprintf(szFilename, "frame%d.ppm", iFrame);
  8.   pFile=fopen(szFilename, "wb");
  9.   if(pFile==NULL)
  10.     return;
  11.   
  12.   // Write header

  13.   fprintf(pFile, "P6\n%d %d\n255\n", width, height);
  14.   
  15.   // Write pixel data

  16.   for(y=0; y<height; y++)
  17.     fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);
  18.   
  19.   // Close file

  20.   fclose(pFile);
  21. }
We do a bit of standard file opening, etc., and then write the RGB data. We write the file one line at a time. A PPM file is simply a file that has RGB information laid out in a long string. If you know HTML colors, it would be like laying out the color of each pixel end to end like #ff0000#ff0000.... would be a red screen. (It's stored in binary and without the separator, but you get the idea.) The header indicated how wide and tall the image is, and the max size of the RGB values.

Now, going back to our main() function. Once we're done reading from the video stream, we just have to clean everything up:

  1. // Free the RGB image

  2. av_free(buffer);
  3. av_free(pFrameRGB);

  4. // Free the YUV frame

  5. av_free(pFrame);

  6. // Close the codec

  7. avcodec_close(pCodecCtx);

  8. // Close the video file

  9. av_close_input_file(pFormatCtx);

  10. return 0;
You'll notice we use for the memory we allocated with avcode_alloc_frame and .

That's it for the code! Now, if you're on Linux or a similar platform, you'll run:

  1. gcc -o tutorial01 tutorial01.c -lavutil -lavformat -lavcodec -lz -lavutil -lm
If you have an older version of ffmpeg, you may need to drop -lavutil:
  1. gcc -o tutorial01 tutorial01.c -lavformat -lavcodec -lz -lm
Most image programs should be able to open PPM files. Test it on some movie files.
 

>>

原文链接

 

阅读(1350) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~