【FFMPEG】以mjpeg(MJPG)格式解码采集摄像头

背景

  在开发中,由于项目需要,使用ffmpeg开源库进行摄像头的采集,但是由于没有相关开发经验,只能慢慢摸索,其中,由于ffmpeg默认解码摄像头采集格式为YUY2(我的摄像头仅支持YUY2以及MJPG两种格式解码),但项目需求在高分辨率下流畅度也要最高,我的摄像头YUY2的解码格式不能满足要求,必须使用MJPG,于是需要采用MJPG进行解码。但苦于不知道如何设置,一直在网上搜寻答案

解决方法

  如何以MJPG方式解码采集摄像头

pFormatCtx_ = avformat_alloc_context();

AVDictionary* options = NULL;

//这里的input_format并不会直接决定设备解码出来的格式,
//而是要和底下的framrate以及video_size配合使用,
//当摄像头当前支持这个解码格式,同时支持这个分辨率以及这个帧率的解码格式时
//才会正确打开你所想要的摄像头,否则即使打开摄像头可能也不会输出你设定的解码格式
//目前来看,mjpeg的优先级大于yuy2格式
//也就是说当你的设备支持mjpeg且该分辨率以及帧率都指针mjpeg解码时,
//即使不设置input_format字段,也会自动按照 mjpeg 格式解码
av_dict_set(&options, "input_format", "mjpeg", 0);
av_dict_set(&options, "framerate", "30", 0);
av_dict_set(&options, "video_size", "1280x720", 0);

AVInputFormat *ifmt = av_find_input_format(optFrame.c_str());
if (!ifmt) {
	fprintf(stderr, "av_find_input_format error, ret = %d\n", ret);
	return 0;
}

ret = avformat_open_input(&pFormatCtx_, in_file.c_str(), ifmt, &options);
if (ret) {
	fprintf(stderr, "avformat_open_input error, ret = %d\n", ret);
	return 0;
}

ret = avformat_find_stream_info(pFormatCtx_, NULL);
if (ret < 0) {
	fprintf(stderr, "avformat_find_stream_info error, ret = %d\n", ret);
	return 0;
}



AVPacket *pkt = av_packet_alloc();
if (!pkt) {
	fprintf(stderr, "av_packet_alloc error, ret = %d\n", ret);
	return 0;
}

ret = av_read_frame(pFormatCtx_, pkt);
if (ret) {
	fprintf(stderr, "av_read_frame error, ret = %d\n", ret);
	return 0;
}

注释的内容非常重要,请仔细阅读

全文完,感谢浏览

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章