采集到的yuv视频播放异常

来源:9-9 实战从视频设备上采集数据1

邓丹俊

2025-02-06

图片描述
代码如下:
extern “C”
{
#define __STDC_CONSTANT_MACROS 1
#include “libavutil/avutil.h”
#include “libavdevice/avdevice.h”
#include “libavformat/avformat.h”
#include “libavcodec/avcodec.h”
#include “libswresample/swresample.h”
#include “libavutil/audio_fifo.h”
}
#include
#include
#include
#include

using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::copy;
using std::ofstream;
using std::cout;

int main()
{
int ret{}, count{};
char err[1024];
ofstream file;
file = ofstream(“d:/video.yuv”, std::ios::trunc);
if (!file)
return -1;
file << “”;
file.close();
file = ofstream(“d:/video.yuv”, std::ios::app);
if (!file)
return -1;

avdevice_register_all();

auto fmt = av_find_input_format("dshow");
if (!fmt)
{
	cout << "av_find_input_format fail\n";
	return -1;
}

AVFormatContext *ps{};
const char *url{ u8"video=Surface Camera Front" };

AVDictionary *options{};

ret = av_dict_set(&options, "video_size", "640x480",0);
if (ret < 0)
{
	av_strerror(ret, err, 1024);
	cout << "av_dict_set video_size:" << ret << ":" << err << "\n";
	return -1;
}
ret = av_dict_set(&options, "framerate", "30", 0);
if (ret < 0)
{
	av_strerror(ret, err, 1024);
	cout << "av_dict_set framerate:" << ret << ":" << err << "\n";
	return -1;
}
ret = av_dict_set(&options, "pix_fmt", "yuv420p", 0);
if (ret < 0)
{
	av_strerror(ret, err, 1024);
	cout << "av_dict_set pix_fmt:" << ret << ":" << err << "\n";
	return -1;
}

ret = avformat_open_input(&ps,url,fmt,&options);
if (ret < 0)
{
	av_strerror(ret, err, 1024);
	cout << "avformat_open_input:" << ret << ":" << err << "\n";
	return -1;
}

AVPacket pkt[200],*newpkt;
newpkt = av_packet_alloc();
if (!newpkt)
{
cout << “av_packet_alloc fail\n”;
return -1;
}

for (int i = 0; i != 200; ++i)
{
	ret = av_read_frame(ps, &pkt[i]);
	if (ret < 0)
	{
		av_strerror(ret, err, 1024);
		cout << "av_read_frame:" << ret << ":" << err << "\n";
		return -1;
	}

}

avformat_close_input(&ps);

for (int i = 0; i != 200; ++i)
{
	file.write(reinterpret_cast<char*>(pkt[i].data), 460800);
	av_packet_unref(&pkt[i]);
}

av_packet_free(&newpkt);
file.close();

return 0;

}

写回答

1回答

邓丹俊

提问者

2025-02-06

老师,我知道为什么了,我用av_dump_format查看过,摄像头录制的原始视频格式是yuyv422的,用这条命令就录制成功了ffplay -pixel_format yuyv422 -video_size 640x480 d:/video.yuv

0
1
李超
👍👍👍
2025-02-06
共1条回复

音视频小白系统入门课 音视频基础+ffmpeg原理

掌握音视频采集、编解码、RTMP传输协议等核心基础

2317 学习 · 813 问题

查看课程