Original URL: http://www.reghardware.co.uk/2009/06/25/beginners_guide_avisynth/
Getting Started with Avisynth
Turn your PC into a video powerhouse
25th June 2009 11:02 GMT
Conventional wisdom tells us that to be truly useful, computers need to be tamed to work the way we work, not the way they want to do things. Following this philosophy, movie-editing software like Apple's Final Cut Pro and Adobe's Premier emulate reels of celluloid that you can wind through to find your edit points. Unfortunately, this emulation eats up computer resources. Dispense with it, and there's a great way you can do movie editing without having to lash out on a quad-core machine with multi-gigabytes of Ram.
The secret is a software application called Avisynth. I mainly use it for cleaning up films recorded off the telly. But Avisynth is perfect for taking control of your own home-video footage, perhaps turning it into DVDs for the family time-capsule. Or whatever.
Of course, professional editing software offers non-linear editing (NLE) - the ability to access frames at random and do virtual cuts without modifying the original clip - and a feast of instantly deliverable transitions - dissolves, wipes, and so forth. Not stuff you'd expect to do on an 800MHz single-core Celeron system. But guess what? With Avisynth, yes you can.
Because it's not NLE and transitions that eat up computer resources, it's that pretty interface emulating a pre-war Moviola reel-to-reel editor. Take that away, and what you have got is something that looks like this:
video = MPEG2Source("Clip1.d2v", cpu=0)
audio = NicMPG123Source("Clip1 DELAY -746ms.mp2")
AudioDub(video, audio).DelayAudio(-0.746)
Trim(29, 162052)
Dissolve(Trim(0, 28648) , Trim(35426, 162023), 5)
Trim(0, 61566) ++ Trim(68844, 155241)
Dissolve(Trim(0, 98264) , Trim(105041, 147964), 50)
Trim(0, 141032)
Yes, it's a script. The bad news is the only thing in the world that can understand it is Avisynth. But now for the good news.
1. Avisynth is free software.
2. Avisynth runs on 98 per cent of the the world's computers. That's the upside spin - "runs only on Windows" would be the pessimist's version.
3. That eight-line script is all you need to (in this case) turn a TV recording of a movie, with junk at the beginning and end, and three ad breaks in between, into a continuous presentation that wouldn't disgrace a small cinema. By "continuous presentation" I don't just mean ad removal, I mean a proper rebuild of the movie that totally conceals the fact that ads were ever there in the first place.
There's more good news. With a few extra lines of script we can seamlessly eliminate the tendency some TV channels have of ruining the finale by sliding in visuals announcing what's coming next and/or talking over the closing music. We can even blot out - and in many cases virtually make invisible - those eye-grabbing logos that channels like More 4 and ITV 2 stamp on every frame of the movie footage they transmit.
That should have cheered you up a bit about Avisynth, so perhaps you're now in the mood to go back to the script (http://www.reghardware.co.uk/2009/06/25//beginners_guide_avisynth/page1.html#script1) and give it another read. Actually, it's not that opaque. In line one we have some kind of input file called Clip1.d2v to which we apply a function called MPEG2Source and then assign the result to an arbitrary variable we call video. Something very similar goes on in line two, where the result is assigned to audio.
Line three dubs the audio onto the video. Line four trims the result, removing the first 29 frames, keeping all the remaining frames up to and including frame 162052, and junking any frames after that. And so on...
This is all very wonderful, you might be saying, but no darn use to me if it involves having to write a script like that. So here's where I drop my mask of advanced geekery and tell you that I didn't actually write that script. Nor did anybody else. It was written for me by a particularly neat piece of software called AvsP. AvsP is a text editor that understands Avisynth a lot better than I do. And it can show me, frame by frame, what it's doing - it has its own built-in mini-Moviola, if you like. And like Avisynth, it's free.
If you've tried to remove ads from TV movies in the past, you'll probably have used the straight cut. I started with a proprietary package called VideoReDo, which makes an excellent job of this. But you quickly discover that while straight cuts can get rid of the ads, they usually fail to disguise the fact that something's been removed. Often you'll get a jump in the sound, a glitch on the video, or just an awkward sharp transition. The good news is that - for our present purposes at least - you can nearly always fix this by substituting a long, short or medium dissolve. VideoReDo can't do dissolves. Final Cut, of course, can, although it seems to go out of its way to make this very awkward. Avisynth takes dissolves in its stride.
Assembling the Tools
Perhaps the most challenging part of the Avisynth process is setting up the software in the first place. Windows XP 32-bit is the environment of choice - although all this can be made to work with Vista and Windows 7 - and I recommend creating a directory under Program Files called Video Tools.
Install the following there, each in its own individual sub-directory:
| Software | Current Version | Source Location |
| Avisynth | 2.5.8 | http://sourceforge.net/project/showfiles.php?group_id=57023 |
| DGMPGDec | 1.5.5 | http://neuron2.net/dgmpgdec/dgmpgdec.html |
| NicAudio | 2.0.2 | http://nicaudio.codeplex.com/ |
| AvsP | 2.0.2 | http://avisynth.org/qwerpoi/ |
| MPC-HC | 1.2.908.0 | http://sourceforge.net/project/showfiles.php?group_id=170561 |
| WinFF | Installer 1.0.4 | http://winff.org/html/downloads.html |
| XViD | 1.2.2 | http://www.koepi.info/xvid.html |
| VirtualDub | 1.8.8 | http://virtualdub.sourceforge.net/ |
The last two rows are optional, although well worth installing. XViD is a system-wide codec, but you won't need it if you're using WinFF to encode and Media Player Classic-Home Cinema (MPC-HC) to play back; these come with their own encoders/decoders. VirtualDub will become indispensible if you want to venture into the art of logo removal, but you can get through the basics without it.
Preparing the Source for Avisynth
OK, we're ready to go. I'll assume your starting point is some kind of MPEG 2 file recorded from Freeview using a TV tuner. If it's another format, Avisynth can almost certainly cope, but you might need help from the relevant forums. For the purpose of demonstration, I've created one from a public domain clip downloaded from The Internet Archive. There are two types of MPEG 2 file: transport stream (.ts), the raw data as streamed over the airwaves, and program stream (.ps) a cleaned-up version that's better for playing on computers and associated hardware. Our method can cope with either type, but if your TV tuner software gives you a choice, opt to record in .ps format.
Either MPEG 2 variant needs some help before Avisynth can do its stuff. This is where the DGMPGDec suite comes in. It includes a utility called DGIndex - once you've installed the suite this should offer itself in the "Open With..." menu when you right click on an MPEG 2 file. But before you open DGIndex, create a plain text file with the following content...
video = MPEG2Source("__vid__", cpu=0)
audio = NicMPG123Source("__aud__")
AudioDub(video, audio).DelayAudio(__del__)
...and save it inside the DGMPGDec directory with the name template.avs. You'll see in a moment what this amazing time-saver does for us. Hint: the values bracketed with underlines in the template are variables.
DGIndex opens the MPEG2 file into a viewer that allows you to choose the in and out points of the video you're going to edit. You can use this to trim off most of the fat at either end, but don't cut too fine at this stage, because you can only cut to the GOP, not frame-accurately (see GOPs and Frames).

Make sure the audio output options are set correctly - but if your recorder saves audio as AC3 you may want to use the AC3-to-WAV option instead.
Saving the project creates three new files: the index into the original MPEG 2 file, the extracted audio track, and - this is the point of template.avs - a barebones Avisynth script.
GOPs and Frames
Compressed video is stored in a series of 'groups of pictures' (GOPs). The first frame of each GOP, the 'key frame', contains enough compressed data for the decoder to recreate the whole frame. But the data for subsequent frames - and there may be as many as 300 of them in a single GOP - contains only delta information, a description of the extent to which these following frames differ from the key frame or - and there's very fancy maths at work here - from their immediate neighbour frames.
Simple editing software can cut compressed video only on the key frame. Any attempt to cut inside the GOP will destroy subsequent frames and also probably ruin the sound sync. More sophisticated video editing software, like VideoReDo, will re-encode that particular GOP, allowing you to cut on any frame. This is called 'frame-accurate' editing.
Avisynth is a 'frameserver', decoding every GOP on demand as the editing software calls it up. Effectively, our editing is being carried out on a stream of fully detailed frames, so we don't have to worry about GOPs. As it's also a scriptable frameserver we're not confined to straight cuts - we've seen from the example above that Avisynth can equally easily do dissolves (or virtually anything else) around the cut point.
Making the Edits
Now we open the skeleton script with AvsP:

You'll see that the variables in the template have been filled in with actual values derived by DGIndex from the input file. A time-saver, as promised. But wait! We're not ready to run this script yet.
Those functions in the first two lines aren't native to Avisynth. They're external functions, and Avisynth won't have a clue what to do with them. The AvsP Help menu brings up a manual of all Avisynth's commands and functions.
Fixing this is very simple. From the DGMPGDec sub-directory inside Video Tools, drag out the file called DGDecode.dll and dump it inside the Avisynth plugins sub-directory. That takes care of the MPEG2Source. Do the same thing with NicAudio.dll from the NicAudio directory. Any external plugin that's moved into the Avisynth plugins directory will be automatically loaded every time Avisynth is restarted.
Once that's done, re-open the script file in AvsP. Now we can press the 'Show Frames' button: that discreet, up-pointing triangle down in the left hand corner. It swivels to point downwards, and we get....

At this point we can use the Left and Right cursor keys to step forward or back frame by frame, or use the double-arrows next to the 'Show Frames' triangle to do the same thing. The Up and Down cursor keys move us with in steps of one second, and the PageUp, PageDown keys navigate in one-minute steps. We can use this to find the first ad break, which is where AvsP starts to do its magic.
Converting Cuts to Dissolves
The author of AvsP, the mysterious Qwerpoi <qwerpoi.avsp@gmail.com> - alas he seems to be uncontactable these days - once wrote me a macro to speed up the conversion of cuts to dissolves:
entry = avsp.GetTextEntry('Select and copy the trim commands here:')
splitentry = entry.split('++')
if len(splitentry) == 2:
newString = 'Dissolve(%s, %s, 25)' % (splitentry[0], splitentry[1])
avsp.InsertText(newString, pos=None)
Stop at the frame just before the ad-break, and hit the End key. This brings up AvsP's Trim Editor:

"End" here means 'end of the section we want to keep', so make sure the Trim Editor's selection option is set to 'Keep selected region'. Now use the arrow and/or Page keys to wind forward to the end of the ad break. Select the first frame you want to keep and hit the Home key:

The two blue sections are what we're keeping. Now click on the Apply button to complete the Trim and discard the unwanted white section. Our source hasn't been changed in any way by this, but you'll notice that AvsP has written a new line into the script:

That double plus operator is what Avisynth calls an "aligned splice" which joins the two clips in a way that ensures the sound stays in sync. To check the splice, we want to run a section of the resulting clip to see how it plays, starting perhaps 200 frames before the splice and ending 200 frames after the splice. So we write a temporary fifth line, like this:

I said "we write", but let's get AvsP to do it. We can create a macro, a plain text file that looks like this:
# this python macro sets an inspection trim
# centered on the current frame and extending
# margin number of frames forward and backward
current = avsp.GetFrameNumber()
margin = 200
start = current - margin
end = current + margin
avsp.InsertText('Trim(%i,%i) #Inspection Trim' % (start, end), pos=-1 )
Call it something like Inspection Trim.py (the suffix is important) and save it into the AvsP's macros sub-directory. AvsP's 'Configure Shortcuts' menu under 'Options' will let you assign this macro to a key combo (I use Alt-i).
We can run this 400-frame snippet in real-time by saving it and feeding it to the MPC-HC video player. But AvsP offers a quick way to do this. Mouse-hovering over the right-pointing little triangle gives us the clue. Click the arrow, and AvsP will ask for the location on your external player. Once it knows that, clicking this arrow (or hitting the F6 key) will always play the script in its current state.

But what if this turns out to be one of those glitchy cuts? Then let's cover it with a dissolve. Simply rewrite the penultimate line, keeping the same frame number values:

This is a one-second dissolve across 25 frames - we're working in PAL - as you'll see from the the value before the closing bracket. If we like we can tinker with this until the dissolve works smoothly. Now finish going though the whole source, creating cuts and dissolves to taste - remembering to remove the temporary Inspection Trims after each inspection - and then save the script. You can now run this just like a regular media file in MPC-HC, or feed it into WinFF to re-encode it for a variety of standalone players or phones.
This has been a quick skate-through, but I hope it's given you a taste for the opportunities Avisynth opens up. Check through the Avisynth manual - from AvsP's Help menu - and you'll quickly realise that this is just a toe in the ocean of internal and external functions Avisynth offers. ®
Here are some references worth checking out:
The Avisynth Wiki (http://avisynth.org/mediawiki/Main_Page)
AvsP Overview (http://avisynth.org/qwerpoi/Overview.html)
VirtualDub and Avisynth FAQs (http://home.comcast.net/%7Eplutarch/VirtualDub.html)
The Doom9 Forum (http://www.doom9.org/)
Removing Logos with DeLogo (http://www.videohelp.com/forum/archive/removing-logos-using-delogo-vdub-filter-t280003.html)
