2011年11月19日 星期六

在 Visual Studio 2010 中使用 FFmpeg 程式庫

ffmpeg 是一個免費開源的 codec library. 由於 ffmpeg 是使用 C 程式語言所編寫之程式庫, 而Visual Studio 到目前尚未完整地支援 C99, 因此 ffmpeg 本身無法用VS來編譯. 想要在 Windows 環境中編譯 ffmpeg 則必需在 minGW 配合 MSYS 方可編譯. 在本文中並不討論如何編譯 ffmpeg 程式庫, 而是討論如何在 Visual Studio 2010 中編寫使用 ffmpeg 功能之應用程式.

本範例之環境為: win7 + VS2010 + FFmpeg-full-SDK-3.2

1. FFmpeg-full-SDK-3.2 可到 http://www.ffmpeg.com.cn/index.php/SDK_Download 下載
2. 解壓縮之後預設之目錄為:  FFmpeg-full-SDK-3.2, 其中有bin, lib, include三個子目錄
3. 取得 inttypes.h 和 stdint.h, 可放在 include 子目錄中. 請參考:
  http://ffmpeg.arrozcru.org/wiki/index.php?title=Inttypes.h
4. 在VS2010中建立一個新 Project ( C++ Console ), 例: AVSample
5. 設定編譯所需之 header 檔及 .lib 位置; 修改在此新 Project 之 Property pages properties 選項:
        在 C/C++ 之Additional Include Directories: 加入, 例: C:\FFmpeg-full-SDK-3.2\include
        在 Linker 之 Additional Library Directories: 加入, 例: C:\FFmpeg-full-SDK-3.2\lib
6. 修改 AVSample.cpp 之內容如下方所列程式碼, 由於是 C++專案, 因此在 include ffmpeg 之header時要加上:        extern "C"
7. Build 專案, 編譯成功
8. 執行時會出現缺少 avcodec.dll 等訊息, 把bin 中的 dll 都複製到 exe 所在的目錄即可.
9. 此為初步完成, 確認成功後即可依所要完成功能自行編寫所需之程式.

Note:  FFmpeg-full-SDK-3.2 在本文發表時已屬較舊之版本, 如果取得新版本之 ffmpeg 則可能因一些 function 之停用或修改導致以下範例某些行在編譯產生 error 時需要適當修改.

#include "stdafx.h"
#include "stdio.h"
extern "C" {
#include  <libavcodec/avcodec.h>
#include  <libavformat/avformat.h>
}
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
  FILE *pFile;
  char szFilename[32];
  int  y;

  // Open file
  sprintf(szFilename, "frame%d.ppm", iFrame);
  pFile=fopen(szFilename, "wb");
  if(pFile==NULL)
    return;

  // Write header
  fprintf(pFile, "P6\n%d %d\n255\n", width, height);

  // Write pixel data
  for(y=0; y     fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);

  // Close file
  fclose(pFile);
}

int _tmain(int argc, _TCHAR* argv[])
{
  AVFormatContext *pFormatCtx;
  int             i, videoStream;
  AVCodecContext  *pCodecCtx;
  AVCodec         *pCodec;
  AVFrame         *pFrame;
  AVFrame         *pFrameRGB;
  AVPacket        packet;
  int             frameFinished;
  int             numBytes;
  uint8_t         *buffer;

  if(argc < 2) {
    printf("Please provide a movie file\n");
    return -1;
  }

  // Register all formats and codecs
  av_register_all();

  // Open video file
  if(av_open_input_file(&pFormatCtx, "myFilename.x", NULL, 0, NULL)!=0)
    return -1; // Couldn't open file

  // Retrieve stream information
  if(av_find_stream_info(pFormatCtx)<0)
    return -1; // Couldn't find stream information

  // Dump information about file onto standard error
  dump_format(pFormatCtx, 0, "myOutfile.x", 0);

  // Find the first video stream
  videoStream=-1;
  for(i=0; inb_streams; i++)
    if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO) {
      videoStream=i;
      break;
    }
  if(videoStream==-1)
    return -1; // Didn't find a video stream

  // Get a pointer to the codec context for the video stream
  pCodecCtx=pFormatCtx->streams[videoStream]->codec;

  // Find the decoder for the video stream
  pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
  if(pCodec==NULL) {
    fprintf(stderr, "Unsupported codec!\n");
    return -1; // Codec not found
  }

  // Open codec
  if(avcodec_open(pCodecCtx, pCodec)<0)
    return -1; // Could not open codec

  // Allocate video frame
  pFrame=avcodec_alloc_frame();

  // Allocate an AVFrame structure
  pFrameRGB=avcodec_alloc_frame();
  if(pFrameRGB==NULL)
    return -1;

  // Determine required buffer size and allocate buffer
  numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,
     pCodecCtx->height);
  buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

  // Assign appropriate parts of buffer to image planes in pFrameRGB
  // Note that pFrameRGB is an AVFrame, but AVFrame is a superset
  // of AVPicture
  avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,
pCodecCtx->width, pCodecCtx->height);

  // Read frames and save first five frames to disk
  i=0;
  while(av_read_frame(pFormatCtx, &packet)>=0) {
    // Is this a packet from the video stream?
    if(packet.stream_index==videoStream) {
      // Decode video frame
      avcodec_decode_video(pCodecCtx, pFrame, &frameFinished, packet.data, packet.size);

      // Did we get a video frame?
      if(frameFinished) {
        // Convert the image from its native format to RGB

// Save the frame to disk
if(++i<=5)
 SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height, i);
      }
    }

    // Free the packet that was allocated by av_read_frame
    av_free_packet(&packet);
  }

  // Free the RGB image
  av_free(buffer);
  av_free(pFrameRGB);

  // Free the YUV frame
  av_free(pFrame);

  // Close the codec
  avcodec_close(pCodecCtx);

  // Close the video file
  av_close_input_file(pFormatCtx);

  return 0;
}