Libavformat
lastmod 2026-11-10created 2015-04-098 edits
libavformat은 FFmpeg 프로젝트에 속한 라이브러리로, 컨테이너 포맷의 디멀티플렉싱(demuxing)과 멀티플렉싱(muxing)을 담당한다. 미디어 파일이나 네트워크 스트림을 열어 스트림 정보를 읽고 패킷 단위로 꺼내 주며, 실제 디코딩은 libavcodec 이 맡는다. 이 문서는 AVFormatContext로 영상 길이와 프레임레이트를 구하는 방법, 커스텀 IO, OpenCV 이미지 변환 예제를 정리한다.
AVFrame to IplImage
#include <libavutil/pixdesc.h>
IplImage * createRgb24CvImage(int const & pixel_format, AVFrame const * frame)
{
if (pixel_format != PIX_FMT_BGR24) {
return nullptr;
}
AVPixFmtDescriptor const * desc = av_pix_fmt_desc_get(static_cast<AVPixelFormat>(pixel_format));
int depth = av_get_bits_per_pixel(desc); // maybe 8
int width = frame->width;
int height = frame->height;
int linesize = frame->linesize[0];
int channel = frame->channels; // maybe 3
uint8_t * frame_data = NULL;
uint8_t * cvframe_date = NULL;
IplImage * image = cvCreateImage(cvSize(width, height), depth, channel);
for (int y = 0; y < height; y++) {
frame_data = (frame->data[0] + y * linesize);
cvframe_date = (uint8_t *) (image->imageData + y * image->widthStep);
for (int x = 0; x < width; x++) {
// BGR24 Format Copy.
cvframe_date[3 * x + 2] = frame_data[3 * x + 2]; // r
cvframe_date[3 * x + 1] = frame_data[3 * x + 1]; // g
cvframe_date[3 * x + 0] = frame_data[3 * x + 0]; // b
}
}
return image;
}
Duration 구하기
AVFormatContext* pFC;
int ret;
pFC = avformat_alloc_context();
ret = avformat_open_input(&pFC, filename, NULL, NULL);
if (ret < 0) {
// fail .
}
ret = avformat_find_stream_info(pFC, NULL);
if (ret < 0) {
// fail
}
printf("duration %ld", pFC->duration);
FFMPEG Custom IO
check the AVFMT_FLAG_CUSTOM_IO macro.
How to get the duration and frame rate using libavformat
int64_t AVFormatContext::duration
AVRational AVStream::avg_frame_rate
static double av_q2d ( AVRational a )