DxPackNet 5.视频高质量的压缩和传输
DxPackNet 对视频的压缩和解压也提供了很好的支持,且系统不需要装第三方解码器哦~
主要用到了 IxVideoEncoder 视频编码器 和 IxVideoDecoder 两个接口
这里只做简单的组件功能使用介绍,实际应用中可能涉及到 UDP分包,包顺序控制,
音视频传输协议制定, P2P,这就不在本文的讨论范围
private void Form1_Load(object sender, EventArgs e) { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 38000));//绑定端口号 threadRecv = new Thread(new ThreadStart(ReviceMsg)); threadRecv.Start(); client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); svpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 38000); //初始化视频编码环境 IxVideoCoderEnv Env = DxFactory.CreateDxCompent<IxVideoCoderEnv>(); Env.Init(); //创建编码器 encoder = DxFactory.CreateDxCompent<IxVideoEncoder>(); encoder.Quant = 30;//视频质量 0~31 之间的数字 越小画质越好, 越大越流畅 //创建解码器 decoder = DxFactory.CreateDxCompent<IxVideoDecoder>(); cameras = DxFactory.CreateDxCompent<DxDeviceCollection>(DxDeviceCollection.ENVIRONMENT_CAMERAS); camCapture = DxFactory.CreateDxCompent<IDxCameraCapture>(this, panel1); camCapture.FrameCb = camerasFrameCb; camCapture.Init(cameras[0]); } byte[] outBuffer = new byte[1024 * 1024 * 2];//2M byte[] imgBuffer = new byte[1024 * 1024 * 2];//2M private void camerasFrameCb(byte[] buffer, int size) { Array.Clear(outBuffer, 0, outBuffer.Length); //压缩视频流 int outSz = encoder.Encode(buffer, size, outBuffer); client.SendTo(outBuffer,outSz,SocketFlags.None,svpoint);//客户端发送压缩后的视频流 } private void ReviceMsg() //服务端接收视频流后解压显示 { byte[] bufferRecv=new byte[1024 * 1024 * 2];////2M while (!bExit) { if (server.Poll(0, SelectMode.SelectRead)) { EndPoint clpoint1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 38000); //接收压缩流 int revLen = server.ReceiveFrom(bufferRecv, SocketFlags.None, ref clpoint1); reviceSize += revLen; Array.Clear(imgBuffer, 0, imgBuffer.Length); //解压缩视频流 int outSz = decoder.Decode(bufferRecv, revLen, imgBuffer); this.BeginInvoke(new camerasFrameCbHandler(_camerasFrameCb), imgBuffer, 640 * 480 * 3); } } } delegate void camerasFrameCbHandler(byte[] buffer, int size); public void _camerasFrameCb(byte[] buffer, int size) { //将视频流转换为帧图片 Bitmap bmp = camCapture.BmpFromBuffer(buffer, size); if (bmp != null) { Image oimg = pictureBox1.Image; pictureBox1.Image = bmp; if (oimg != null) oimg.Dispose(); } }
效果图:
最后附上demo VideoTransferDemo.zip