使用FFMPEG抓取UVC摄像头照片

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "avformat.h"
#include "avcodec.h"
#include "avdevice.h"

char* input_name= "video4linux2";
char* file_name = "/dev/video0";
char* out_file = "test.yuv";

void captureOneFrame(void){
AVFormatContext *fmtCtx = NULL;
AVPacket *packet;
AVInputFormat *inputFmt;
FILE *fp;
int ret;


inputFmt = av_find_input_format (input_name);

if (inputFmt == NULL) {
printf("can not find_input_format\n");
return;
}

if (avformat_open_input ( &fmtCtx, file_name, inputFmt, NULL) < 0){
printf("can not open_input_file\n"); return;
}
/* print device information*/
av_dump_format(fmtCtx, 0, file_name, 0);

packet = (AVPacket *)av_malloc(sizeof(AVPacket));
av_read_frame(fmtCtx, packet);
printf("data length = %d\n",packet->size);

fp = fopen(out_file, "wb");
if (fp < 0) {
printf("open frame data file failed\n");
return ;
}

fwrite(packet->data, 1, packet->size, fp);

fclose(fp);
av_free_packet(packet);
avformat_close_input(&fmtCtx);
}

int main(void){
avcodec_register_all();
avdevice_register_all();
captureOneFrame();
return 0;
}

Makefile

OUT_APP    = test
INCLUDE_PATH = /usr/include/x86_64-linux-gnu/
INCLUDE = -I$(INCLUDE_PATH)libavutil/ -I$(INCLUDE_PATH)libavdevice/ \
-I$(INCLUDE_PATH)libavcodec/ -I$(INCLUDE_PATH)libswresample \
-I$(INCLUDE_PATH)libavfilter/ -I$(INCLUDE_PATH)libavformat \
-I$(INCLUDE_PATH)libswscale/

FFMPEG_LIBS = -lavformat -lavutil -lavdevice -lavcodec -lswresample -lavfilter -lswscale
SDL_LIBS =
LIBS = $(FFMPEG_LIBS)$(SDL_LIBS)

COMPILE_OPTS = $(INCLUDE)
C = c
OBJ = o
C_COMPILER = cc
C_FLAGS = $(COMPILE_OPTS) $(CPPFLAGS) $(CFLAGS)

LINK = cc -o
LINK_OPTS = -lz -lm -lpthread
LINK_OBJ = ffmpeg.o

.$(C).$(OBJ):
$(C_COMPILER) -c -g $(C_FLAGS) $<


$(OUT_APP): $(LINK_OBJ)
$(LINK)$@ $(LINK_OBJ) $(LIBS) $(LINK_OPTS)

clean:
-rm -rf *.$(OBJ) $(OUT_APP) core *.core *~ *.jpeg

编译:

caozilong@caozilong-Vostro-3268:~/ffmpeg$ make
cc -c -g -I/usr/include/x86_64-linux-gnu/libavutil/ -I/usr/include/x86_64-linux-gnu/libavdevice/ -I/usr/include/x86_64-linux-gnu/libavcodec/ -I/usr/include/x86_64-linux-gnu/libswresample -I/usr/include/x86_64-linux-gnu/libavfilter/ -I/usr/include/x86_64-linux-gnu/libavformat -I/usr/include/x86_64-linux-gnu/libswscale/ ffmpeg.c
ffmpeg.c: In function ‘captureOneFrame’:
ffmpeg.c:53:5: warning: ‘av_free_packet’ is deprecated [-Wdeprecated-declarations]
av_free_packet(packet);
^~~~~~~~~~~~~~
In file included from /usr/include/x86_64-linux-gnu/libavformat/avformat.h:319:0,
from ffmpeg.c:11:
/usr/include/x86_64-linux-gnu/libavcodec/avcodec.h:4650:6: note: declared here
void av_free_packet(AVPacket *pkt);
^~~~~~~~~~~~~~
cc -o test ffmpeg.o -lavformat -lavutil -lavdevice -lavcodec -lswresample -lavfilter -lswscale -lz -lm -lpthread
caozilong@caozilong-Vostro-3268:~/ffmpeg$

测试:

ffplay -i test.yuv -pixel_format yuyv422 -video_size 640*480

使用FFMPEG抓取UVC摄像头照片


关于"video4linux2"和V4L2设备的关联

使用FFMPEG抓取UVC摄像头照片


结束!