Showing posts with label VirtualDub. Show all posts
Showing posts with label VirtualDub. Show all posts

Wednesday, May 27, 2009

VirtualDub

What is VirtualDub?

VirtualDub is a video capture/processing utility for 32-bit Windows platforms (95/98/ME/NT4/2000/XP), licensed under the GNU General Public License (GPL). It lacks the editing power of a general-purpose editor such as Adobe Premiere, but is streamlined for fast linear operations over video. It has batch-processing capabilities for processing large numbers of files and can be extended with third-party video filters. VirtualDub is mainly geared toward processing AVI files, although it can read (not write) MPEG-1 and also handle sets of BMP images.

I basically started VirtualDub in college to do some quick capture-and-encoding that I wanted done; from there it's basically grown into a more general utility that can trim and clean up video before exporting to tape or processing with another program. I released it on the web and others found it useful, so I've been tinkering around with its code ever since. If you have the time, please download and enjoy.

§ GPU acceleration of video processing

I've gotten to a stable enough point that I feel comfortable in revealing what I've been working on lately, which is GPU acceleration for video filters in VirtualDub. This is something I've been wanting to try for a while. I hacked a video filter to do it a while back, but it had the severe problems of (a) only supporting RGB32, and (b) being forced to upload and download immediately around each instance. The work I've been doing in the past year to support YCbCr processing and to decouple the video filters from each other cleaned up the filter system enough that I could actually put in GPU acceleration without significantly increasing the entropy of the code base.

There are two problems with the current implementation.

The first problem is the API that it uses, which is Direct3D 9. I chose Direct3D 9 as the baseline API for several reasons:

  • It's the API I'm most familiar with, by far.
  • The debug runtime is much more thorough than what I've had available with other APIs.
  • PIX and NVPerfHUD are free.
  • It runs on just about any modern video card.
  • Shaders have well-defined profiles, are portable between graphics card vendors, and use standardized byte code.

On top of this are a 3D portability layer, then the filter acceleration layer (VDXA). The API for the low level layer is designed so that it could be retargeted to Direct3D 9Ex, D3D10 and OpenGL; the VDXA layer is much more heavily restricted in feature set, but also adds easier to use 2D abstractions on top. The filter system in turn has been extended so that it inserts filters as necessary to upload or download frames from the accelerator and can initiate RGB<->YUV conversions on the graphics device. So far, so good...

...except for getting data back off the video card.

There are only two ways to download non-trivial quantities of data from the video card in Direct3D 9, which are (1) GetRenderTargetData() and (2) lock and copy. In terms of speed, the two methods are slow and pathetically slow, respectively. GetRenderTargetData() is by far the preferred method nowadays as it is decently well optimized to copy down 500MB/sec+ on any decent graphics card. The problem is that it is impossible to keep the CPU and GPU smoothly running in parallel if you use it, because it blocks the CPU until the GPU completes all outstanding commands. The result is that you spend far more time blocking on the GPU than actually doing the download and your effective throughput drops. The popular suggestion is to double-buffer render target and readback surface pairs, and as far as I can tell this doesn't help because you'll still stall on any new commands that are issued even if they go to a different render target. This means that the only way to keep the GPU busy is to sit on it with the CPU until it becomes idle, issue a single readback, and then immediately issue more commands. That sucks, and to circumvent it I'm going to have to implement another back end to see if another platform API is faster at readbacks.

The other problem is that even after loading up enough filters to ensure that readback and scheduling are not the bottlenecks, I still can't get the GPU to actually beat the CPU.

I currently have five filters accelerated: invert, deinterlace (yadif), resize, blur, blur more, and warp sharp. At full load, five out of the six are faster on the CPU by about 20-30%, and I cheated on warp sharp by implementing bilinear sampling on the GPU instead of bicubic. Part of the reason is that the CPU has less of a disadvantage on these algorithms: when dealing with 8-bit data using SSE2 it has 2-4x bandwidth than with 32-bit float data, since the narrower data types have 2-4x more parallelism in 128-bit registers. The GPU's texture cache also isn't as advantageous when the algorithm simply walks regularly over the source buffers. Finally, the systems I have for testing are a bit lopsided in terms of GPU vs. CPU power. For instance, take the back-of-the-envelope calculations for the secondary system:

  • GPU (GeForce 6800): 2600Mpix/sec * 4 components/vector = 10.4 billion operations/sec
  • CPU (Pentium M): 1.86GHz * 8 components / vector / clock = 14.8 billion operations/sec

It's even worse for my primary system (which I've already frequently complained about):

  • GPU (Quadro NVS 140M): 3200Mpix/sec * 4 components / vector = 12.8 billion operations/sec
  • CPU (Core 2): 2.5GHz * 16 components / vector / clock = 40 billion operations/sec (single core)

There are, of course, a ton of caveats in these numbers, such as memory bandwidth and the relationship between theoretical peak ops and pixel throughput. The Quadro, for instance, is only about half as fast as the GeForce in real-world benchmarks. Still, it's plausible that the CPU isn't at a disadvantage here, particularly when you consider the extra overhead in uploading and downloading frames and that some fraction of the GPU power is already used for display. I need to try a faster video card, but I don't really need one for anything else, and more importantly, I no longer have a working desktop. But then again, I could also get a faster CPU... or more cores.

The lesson here appears to be that it isn't necessarily a given that the GPU will beat the CPU, even if you're doing something that seems GPU-friendly like image processing, and particularly if you're on a laptop where the GPUs tend to be a bit underpowered. That probably explains why we haven't seen a huge explosion of GPU-accelerated apps yet, although they do exist and are increasing in number.

(Read more....)

§ Template madness

Templates are a feature in C++ where you can create functions and class types that are parameterized on other types and values. An example is the min() function. Without templates, your choices in C++ would be a macro, which has problems with side effects; a single function, which locks you down to a single type; or multiple overloads, which drives you nuts. Templates allow you to declare a min() that works with any type that has a less-than predicate without having to write all of the variants explicitly.

The problem with templates is that they're (a) awful to use and (b) very powerful. The C++ template syntax is horrible, with all sorts of notorious problems with angle brackets and typename and other issues, and anyone who used VC6 still shudders at the mention of STL errors. The thing is, I still like templates, because they're compile-time and extremely versatile. The last time I had to use generics in C#, I ran into so many limitations that I really wished I'd had templates instead. C# generics are a mixture of both compile-time and run-time instantiation, which means they're more constrained. In particular, the inability to use constructors with parameters or to cast to the generic type is crippling, especially if you're working with enums. In C++, you can pretty much do anything with T that you could with using an explicit type.

Function template instantiation is one of the areas that I have the most problem with. The idea is simple: you specify the function you want, and the compiler finds the best template to fit. In reality, you're in a role-playing game where you wish for the function you want and the compiler GM does whatever it can to do precisely what you ask and still screw you, like implicitly convert a double through type bool. I got burned by this tonight when I tried to port VirtualDub to Visual Studio 2010 beta 1. I had expected this to be quick since everything just worked in the CTP, but with beta 1 it took hours due to several nasty bugs in the project system. The first time I was able to run the program it asserted before it even opened the main window. The problem was in this code:

int nItems = std::min<int>(mMaxCount, s.length());

mMaxCount was 4, s.length() was 2, and I ended up with min(4, 2) == 4. WTF?

First, I should note the reason for the explicit call. I often end up with situations where I need to do a min() or a max() against mixed signed and unsigned types, and usually I know that the value ranges are such that it's OK to force to one type, such as if I've already done some clamping. To do this, I force the template type. Well, it turns out that specifying min() doesn't do what I had expected. It doesn't force a call to the version of min() with one template parameter of type int -- it forces a call to any template with int as the first type parameter. This used to be OK because std::min() only had one overload that took two parameters, so no other template could match. However, VS2010 beta 1 adds this evil overload:

template
inline const T& min(const T&, Pred);

Why you would ever want a min() that takes a single value and a predicate is beyond me. However, since I was calling min() with an int and an unsigned int, the compiler decided that min(int, unsigned) was a better match than min(int, int). The odd result is that 2 got turned into an ignored predicate and min(2, 4) == 4. Joy. I hacked the build into working by writing my own min() and max() and doing a massive Replace In Files.

I love templates, but I wish they didn't have so many gotchas.

(Read more....)

download

Thursday, May 14, 2009

VirtualDub

VirtualDub is a video capture/processing utility for 32-bit Windows platforms (95/98/ME/NT4/2000/XP), licensed under the GNU General Public License (GPL). It lacks the editing power of a general-purpose editor such as Adobe Premiere, but is streamlined for fast linear operations over video. It has batch-processing capabilities for processing large numbers of files and can be extended with third-party video filters. VirtualDub is mainly geared toward processing AVI files, although it can read (not write) MPEG-1 and also handle sets of BMP images.

I basically started VirtualDub in college to do some quick capture-and-encoding that I wanted done; from there it's basically grown into a more general utility that can trim and clean up video before exporting to tape or processing with another program. I released it on the web and others found it useful, so I've been tinkering around with its code ever since. If you have the time, please download and enjoy.

§ Altirra 1.1 released

I finally have some time lately to flush out some of the stuff I've had going on lately, and since all my latest VirtualDub work went out with 1.9.2, it's time for something else. A while ago I posted the first version of Altirra, my Atari 8-bit computer emulator. Due to some encouragement from some friendly people on AtariAge, I went back and fixed a whole bunch of emulation bugs in the emulator, and the result is version 1.1:

http://www.virtualdub.org/beta/Altirra-1.1.zip
http://www.virtualdub.org/beta/Altirra-1.1-src.zip

As proof of its worthiness of release, I present my in-emulator triumph over evil in The Last Starfighter:

[The Last Starfighter victory screen]

The primary improvements are a lot of undocumented features implemented in GTIA, a couple of fixes to POKEY, and several tricky but important timing fixes in ANTIC. The display code now also does aspect ratio locking (a feature that I need to integrate back to VirtualDub).

Working on an emulator for an old computer system is basically working to an inflexible, and unfortunately incomplete, spec. I have access to the official Atari Hardware and OS reference manuals, which describe all hardware registers and kernel calls in the system. You can write an emulator that exactly conforms to those specifications and the result is that you will be able to run maybe half of the software that was released. The other half won't work because it depends on undocumented behavior such as when the display list interrupt bit resets (scan line 248) and the exact number of clock cycles it takes to enter the vertical blank routine (47-53 for XL OS). The spec is unrelenting and frozen -- unless you have a time machine, there is no way to change it. Therefore, you will implement exactly what the hardware does, period, and anything less is a bug. It gives you some appreciation for when you do have leeway to get specs changed to ease implementation.

There is one feature that I wanted to get into this version that I couldn't, which is artifacting. Artifacting is a phenomenon of composite video where unfiltered high frequencies in luminance are misinterpreted by the TV as colors. In NTSC Ataris, the high-resolution modes output pixels at a rate exactly twice the color subcarrier, which means that alternating luminance values produce colors instead of patterns. NTSC is designed with frequency interleaving to mitigate this somewhat, but the Atari produces non-interlaced video with a constant color subcarrier phase, defeating this. The way I tried to simulate this was brute-force, simply converting the video screen to a virtual 13.5MHz (4*Fsc) signal and then separating it out to Y/I/Q with FIR low pass and high pass filters. Well, the result kind of sucked, with an exceptionally blurry luma output and visible rippling in artifacted areas. The result on a real Atari with my LCD monitor's composite input looks significantly better, which leads me to believe there's something I'm missing, possibly a non-linear separation algorithm.

Changelist after the jump.

(Read more....)

§ UI rendering in Windows 7

I spent some time downloading and Windows 7 RC today. I installed the beta a while ago, but didn't do too much with it since I had only installed it on a VM, which invalidated any comparisons in graphics performance and prevented any access to 3D acceleration. Well, this time I took advantage of the uber-cool install to VHD feature to install and run Windows 7 without having to repartition my hard drive, so that I could run it directly on real hardware. I get the feeling that I'm pretty far behind in noticing some of the improvements in Windows 7, but hey... better late than never.

Now, to understand where I'm coming from, I've had both 32-bit XP and 64-bit Vista installed on dual-boot for some time, but I almost never boot into Vista 64 unless I need to test some 64-bit code. The reason is that Vista 64 runs like complete crap. CPU and memory aren't a problem, because I have a 2.5GHz Core 2 and 2GB of RAM. The problem is my somewhat mediocre NVIDIA Quadro NVS 140M, which is 8400GS based, compounded by my 1920x1200 display. It runs like a slug with Aero Glass enabled, and is still laggy and runs at low frame rates with it off. The result is that Visual Studio 2005 is noticeably more sluggish on Vista 64 than in XP, and thus I spend all my time in XP instead.

The main reason that Vista performs worse is that, despite all the hype about the new desktop hardware acceleration, the WDDM 1.0 display driver model introduced in Vista actually forces all GDI and DirectDraw rendering to occur in software on the CPU. Since most UI in Windows is based off one of those two APIs -- including Win32 UI and .NET's GDI+ based UI -- this results in significantly slower UI performance. Well, unfortunately, it doesn't seem that Windows 7 runs Aero Glass any better, and in fact on this system VirtualDub has trouble breaking around 25 fps due to the low desktop composition frame rate. It runs noticeably better with composition disabled however: stretching video to 1920x1200 through DirectDraw now takes about 0-2% of the CPU instead of 6-10%.

The reason for this, as it turns out, is that the new WDDM 1.1 DDI in Windows 7 reintroduces support for adds several GDI optimizations, including reducing lock contention and reintroducing some hardware acceleration. The DDI documentation for GDI hardware acceleration reveals seven primitive operations that are supported for acceleration: alpha blend, BitBlt, ClearType blend (text rendering), solid color rect fill, StretchBlt, and transparent blit (color key). That covers a lot, but the one notable omission is line draw. In theory it would be possible to accelerate those by rasterizing the line to spans, and it'd be trivial to do so for the common cases of horizontal and vertical lines, but I don't know if Windows 7 actually does this. In any case, reintroduction of basic GDI acceleration is welcome. This also appears to extend to DirectDraw blits, although those are still not bilinearly filtered as they usually are with XP drivers.

Another interesting change is that WDDM 1.1 reintroduces support for DirectDraw hardware video overlays. In Vista, attempting to use a hardware overlay either resulted in the overlay calls silently failing or desktop composition being forced off. It appears that overlays work again on Windows 7. You can't test this with current versions of VirtualDub since I added code to force them off on Windows Vista or later due to the poor OS behavior, but you can see them in action if you get an old version of VirtualDub like 1.6.0. They don't work quite like on XP, though, because for some reason they don't update except when a GDI repaint occurs. I'm not sure if it's worth investigating this since any video card that supports WDDM 1.1 supports DirectX 9, and at that point it's better just to use Direct3D.

I have noticed a couple of occasional weirdnesses in the USER layer in Windows 7 that I haven't pinned down yet. In the beta at high DPI, one specific item in VirtualDub's display pane context menu bizarrely shows up in a different font. Altirra also occasionally shows a vertically displaced window caption in one of its tool windows after a full-screen mode switch. I suppose it's possible that these are video driver related, as the WDDM 1.1 drivers are still very new.

In any case, since I don't intend to buy a new computer any time soon, it's looking like I might be leapfrogging Vista to Windows 7 as my main OS, now that some of the 2D performance gaffes are getting addressed.

(Read more....)