在视频媒体播放,监控系统的构建当中,经常会涉及到YUV数据的显示问题。一般的播放控件以及SDK都是通过使用Window句柄,利用DirectDraw直接在窗口上渲染。但是,如果用户界面是使用WPF开发的时候,通常只能通过WinFormHost在WPF界面中嵌入WinForm来完成。但这么做会遇到AeroSpace的问题,即winform的控件永远浮在WPF的最上层,任何WPF元素都会被盖住,同时缩放和拖动的时候都会造成很差的用户体验。原因是由于WPF和Winform使用了不同的渲染技术。
要在WPF中完美的支持YUV数据的显示,通常的解决方式是使用先把YUV数据转换成WPF可以支持的RGB数据,然后利用类似于WriteableBitmap的控件,把他展现在WPF上。这么做的主要问题是在做RGB转换的时候,需要消耗大量的CPU, 效率比较低。一种优化方式是使用FFMPEG里的SwScale或者Intel的IPP库,这些库经过了一定的优化,可以有限度的使用硬件加速。下面为一个使用WritableBitmap的例子。
WriteableBitmap imageSource = new WriteableBitmap(videoWidth, videoHeight, DPI_X, DPI_Y, System.Windows.Media.PixelFormats.Bgr32, null); ... int rgbSize = width * height * 4; // bgr32 IntPtr rgbPtr = Marshal.AllocHGlobal(rgbSize); YV12ToRgb(yv12Ptr, rgbPtr, width, height); // 更新图像 imageSource.Lock(); Interop.Memcpy(this.imageSource.BackBuffer, rgbPtr, rgbSize); imageSource.AddDirtyRect(this.imageSourceRect); imageSource.Unlock(); Marshal.FreeHGlobal(rgbPtr);
另一种解决方法是使用D3DImage作为WPF与显卡的桥梁。我们可以借助D3DImage,直接将D3D渲染过后的部分送到WPF中显示。一个参考就是VMR9在WPF中的应用。VMR9是微软提供的DirectShow的Render。经过仔细参考了WpfMediaTookit中VMR9相关的代码后,其核心的思想就是在初始化DirectShow构建VMR9渲染器时,让其输出一个D3D9Surface,D3DImage将使用该Surface作为BackBuffer。当有新的视频帧在该Surface渲染完成后,VMR9将发送一个事件通知。收到通知后,D3DImage刷新一下BackBuffer即可。下面代码展现了核心思想部分。
private VideoMixingRenderer9 CreateRenderer() { var result = new VideoMixingRenderer9(); var cfg = result as IVMRFilterConfig9; cfg.SetNumberOfStreams(1); cfg.SetRenderingMode(VMR9Mode.Renderless); var notify = result as IVMRSurfaceAllocatorNotify9; var allocator = new Vmr9Allocator(); notify.AdviseSurfaceAllocator(m_userId, allocator); allocator.AdviseNotify(notify); // 在构建VMR9 Render时,注册新视频帧渲染完成事件 allocator.NewAllocatorFrame += new Action(allocator_NewAllocatorFrame); // 注册接收新D3DSurface被创建的事件 allocator.NewAllocatorSurface += new NewAllocatorSurfaceDelegate(allocator_NewAllocatorSurface); return result; } void allocator_NewAllocatorSurface(object sender, IntPtr pSurface) { // 为了方便理解,只保留核心部分。省略改写了其他部分 ... // 将pSurface设置为D3DImage的BackBuffer this.m_d3dImage.Lock(); this.m_d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, pSurface); this.m_d3dImage.Unlock(); ... } void allocator_NewAllocatorFrame() { ... // 重绘 this.m_d3dImage.Lock(); this.m_d3dImage.AddDirtyRect(new Int32Rect(0, /* Left */ 0, /* Top */ this.m_d3dImage.PixelWidth, /* Width */ this.m_d3dImage.PixelHeight /* Height */)); this.m_d3dImage.Unlock(); ... }
新闻热点
疑难解答
图片精选