Avisynth Basics - Resizing and Sharpening for Gifs
Prerequisites
Avisynth (Wikipedia)
How to Use Avisynth For Gif Making by MichieTuts
Installing Avisynth by brandinator
Tumblr Dashboard Image Display Sizes by Unwrapping Tumblr
This post details my process for using Avisynth to resize a video file. The video file can then be edited and converted to a gif.
I learned how to use Avisynth through the posts linked above. I highly recommend reading through them; they're very detailed and easy to follow. By comparison, this is a basic guide as it only offers one method for using Avisynth.
In this post, I cover the following:
Why use Avisynth?
Using Avisynth to resize a video clip
This post assumes that you've already installed Avisynth.
💡 Why use Avisynth?
Avisynth is a frameserver that takes a video file as input and resizes it for editing. The width of a Tumblr post is 540 pixels (px); with Avisynth, we can resize video files so that they fit that criteria. (For context, a 1080p (HD) YouTube video is 1920 x 1080 px.)
While Photoshop is able to resize images (Image > Image Size), it's not as accurate as Avisynth is.
Here are two gifs that have been resized through different software:
The difference is subtle, but the left gif (Avisynth) appears more detailed to me!
However, please note that I didn't run any Photoshop sharpening on the right gif. When learning how to resize and sharpen gifs in Photoshop, I followed rubyredwisp's Gif Sharpening Tutorial.
🎥 Using Avisynth to resize a video clip
The following steps detail how I use Avisynth to resize videos. The final product, an .avi file, can be imported into your editor (eg. Photoshop) and edited there.
① Choose a video file that you'd like to gif.
For the purpose of this tutorial, I work with a screenrecording that I took of Dragon Age 2.
② Navigate to your Avisynth folder and locate the normalwebmrange script.
This may differ depending on how you installed Avisynth, but my Avisynth folder is located at \This PC\Windows (:C)\video.
normalwebmrange is a Windows batch file (.bat). I use this particular script because it allows you to clip out a few seconds of the video by specifying the start and end timestamps. These timestamps specify the video clip that will become your gif(s).
I recommend working with video clips that are 4-8 seconds long.
ⓘ This means that you may need to load your video file back into normalwebmrange to make a gif in a new timestamp range. While inconvenient, I recommend working with smaller video clips so that you're asking Avisynth to process multiple small videos rather than one large video. A larger video is more likely to crash the software.
③ Load the video file into normalwebmrange.
To do so, select and drag your video file into normalwebmrange.
④ Enter the timestamps of the portion of the video you want to clip out.
A pop-up window will appear that asks you for the "starting time in hh:mm:ss format."
For this example, I want my gif to start at about 3 minutes and 13 seconds into my video file. My start timestamp is therefore 00:03:13.
Enter this information, then hit the Enter key.
Next, enter the "ending time in hh:mm:ss format." (For this example, my end timestamp is 00:03:21.) Hit the Enter key.
normalwebmrange will then generate a bunch of log lines. After, it will automatically open two things:
A tab in your computer's default web browser.
An Avisynth window.
⑤ Specify the resizing details for your gif.
Navigate to the browser tab that normalwebmrange opened. There are several fields for you to fill out here.
GIF Size - This is the width and height of your gif. For more details on Tumblr post sizes, see Tumblr Dashboard Image Display Sizes. After filling this out, you may have to adjust your video clip in the preview box (below the white textbox).
Opacity - Leave this value at 100.
Preprocessor - I always use qtgmc 30 slow for the framerate and debilinear sharpening. "30" refers to how many frames per second (fps) you want your gif to display; I find that the alternative, 60 fps, is overkill for Tumblr gifs. "Slow" means that Avisynth will take longer to process your video, but this results in better quality.
Extra Sharpening - I don't use this field, but feel free to experiment!
After filling out all of the fields, copy all of the text in the white textbox.
⑥ Enter the resizing information in Avisynth.
Navigate to the Avisynth window that normalwebmrange opened.
Paste the text you just copied on line 17:
Your Avisynth window should now look something like this:
Select File > Save Script.
Close the Avisynth window.
This automatically launches another Avisynth window called VirtualDub. Here, you can watch Avisynth resize and sharpen your video clip in real time!
Once the VirtualDub window automatically closes, you'll know that your video clip has been fully processed and is now ready for editing.
? Where did my video clip save to? If you go back to your Avisynth folder (\This PC\Windows (:C)\video), open the \temp folder. The .avi file named "video" is your resized and sharpened video clip!
Ok, as promised, I present to the 5 of you still making gifs on Tumblr an updated and (sort of) improved process for (somewhat) easily leveraging AviSynth to make (mostly, but not “only”) Tumblr gifs.
I’ll consider this the “final form” for this awful slapped together bat file setup and focus my attention on something much more convenient and interesting for you guys to use--but I will update this as necessary as functional problems arise. I haven’t really had a chance to do a ton of testing, so I hope you guys can help me with that and let me know what kind of experiences you’re having trying this stuff out, good or bad. If you’re running into issues please let me know about them! It would go a long way towards making something better in the future.
Additionally, if anybody has some grievances/wishes/problems/concerns with their current process--whether that’s this set of batch files or your process with the old files/vapoursynth/etc., whatever--please do let me know. I have some pretty cool ideas, but I’d be interested to know what you guys hate about the tools available to you atm, or what you would like to see improved.
** I repeat, I have not done a ton of testing. Problems may be likely. Keep backups of your plugins folder and current C:/video setup for your own sake **
Anyway, on to the stuff, here’s what needs to be done:
Uninstall AviSynth 2.5. Tell them “I love you” and thank them for everything. We need to move on...it’s not them, it’s us...
JK, it’s them. We’re replacing 2.5 with AviSynth 2.6. Download and install. Don’t worry about where your install ends up, though it is most likely C:/Program Files (x86)/AviSynth/
Download this new batch (heh) of files: batinator-2.1.2.zip
The packaged zip includes a plugins folder. Move the contents of the included plugins folder into your AviSynth plugins directory. Refer to step 2, this will most likely be C:/Program Files (x86)/AviSynth/plugins/. Nothing you guys haven’t done a dozen times by now.
From here it should be business as usual. Within the batinator folder is an auto.bat. Drag your videos into this and the process will start. If you’ve ever used “avisynth” for this before it should be very familiar.
For reference, here are some things the new setup does better
Automatically find the avisynth plugins folder, no matter where it is. 32-bit, 64-bit, wrong folder name, doesn't matter. If avisynth is installed, it'll find the corresponding plugins folder.
Work from anywhere, not just c:/video. Put it in your desktop if you want. Put it in your music folder, I don't care.
Take a range OR cut 10 seconds automatically. 17s was too long tbh, you really need 17 seconds for one scene? STOP.
Better time seeking. Have you ever put in a timestamp and had this thing spit out the wrong scene by like a second? Awful. No more of that. Using the power of Math™, no frames are left behind.
Attempts to automatically decide the best process to load the video based on the format. There should be no more need for a lossless.bat to try a different method manually
Be less sloppy in general. What the hell is even happening in that black window? Nobody knows.
Save every output video to the output folder without overwriting, in case people want to make multiple cuts before working in photoshop. Because realizing you have to go back and re-do that gif that got overwritten is the saddest thing ever...
Resizer slightly less ugly (still working on that but I'm lazy)
Less shitty resamplehq errors, calculates better sizes in the resizer so that avspmod stops bitching for once in its stupid life
New remake.bat uses the same video and clip and skips to the steps of resizer + avspmod so you can try again, for when you were too lazy to preview it and SWORE those sharpen settings would look good, and they totally don't.
[NEWER] Leverage AviSynth 2.6 and L-SMASH for previously unsupported/badly supported video formats.
Some known issues/things planned
There are some problems with characters in certain languages that I have yet to fully look into. If you’re running into strange problems, checking if you have any non gringo friendly characters in any of the file paths would be a good first start
Files that load with LWLibavVideoSource may not load 100% perfectly. I’ve had issues with the first 20 or so frames being either janky or frozen, sometimes in the preview, sometimes only in the final output. I THINK I fixed this, but if you do run into it, please let me know. As a temporary solution, I would suggest overcompensating on the start time of your cut and making it start a few seconds earlier, just to ensure the first few frames you need are actually clean.
As usual, AviSynth is a Windows tool. I have cross-platform plans for the macfriends, but this will likely leverage VapourSynth, not AviSynth, and will be a re-write that is essentially the focus of what I intend to move on to now that this is (mostly) out of the way.
TL;DR
Uninstall AviSynth 2.5
Install AviSynth 2.6
Download new files (includes plugins folder): batinator-2.1.2.zip
Move plugins to AviSynth 2.6 plugins directory (located wherever AviSynth was installed)
Drag files into auto.bat and it’s business as usual
Please let me know how it works for you and any errors/issues/you encounter, even if they are known issues. More detail and insight are always welcome
hi michie! okay so i have a problem. i downloaded my ts file and tried to run it through normalwebmrange but it never opened my resizer. i tried to run it through different bats but none of them worked. the resizer never opened what do I do?
Oh yikes I’m not sure how I missed this ask. I’m so sorry for the long wait. Not sure if you even need help anymore, but this might happen because you haven’t set a default browser to upen html files. To fix this, find the resizer.html file in the temp folder and open it. Make sure you set a default browser to open the file. Now when you run one of the bat files it should work fine. I hope this helps!
Hello everyone! This post is going to describe the way in which I export and encode my video work to send it over the Internet and archive it. I’ll be talking about everything I’ve discovered over the past 10 years of research on the topic, and I’ll be mentioning some of the pitfalls to avoid falling into.
There’s a tremendous amount of misguided information out there, and while I’m not going to claim I know everything there is to know on this subject, I would like to think that I’ve spent long enough researching various issues to speak about my own little setup that I’ve got going on... it’s kind of elaborate and complex, but it works great for me.
(UPDATE 2020/12/09: added, corrected, & elaborated on a few things.)
First rule, the most golden of them all!
There should only ever be one compression step: the one YouTube does. In practice, there will be at least two, because you can’t send a mathematically-lossless file to YouTube... but you can send one that’s extremely close, and perceptually pristine.
The gist of it: none of your working files should be compressed if you can help it, and if they need to be, they should be as little as possible. (Because let’s face it, it’s pretty tricky to keep hours of game footage around in lossless form, let alone recording them as such in the first place.)
This means that any AVC files should be full (0-255) range, 4:4:4 YUV, if possible. If you use footage that’s recorded with, like, OBS, it’s theoretically possible to punch in a lossless mode for x264, and even a RGB mode, but last I checked, neither were compatible with Vegas Pro. You may have better luck with other video editors.
Make sure that the brightness levels and that the colors match what you should be seeing. This is something you should be doing at every single step of the way throughout your entire process. Always keep this in mind. Lagom.nl’s LCD calibration section has quite a few useful things you can use to make sure.
If you’re able to, set a GOP length / max keyframe range of 1 second in the encoder of your footage. Modern video codecs suck in video editors because they use all sorts of compression tricks which are great for video playback, but not so efficient with the ways video editors access and request video frames. (These formats are meant to be played forwards, and requesting frames in any other order, as NLEs do, has far-reaching implications that hurt performance.)
Setting the max keyframe range to 1 second will mildly hurt compressability of that working footage but it will greatly limit the performance impact you’ll be putting your video editor’s decoder through.
A working file is a lossless file!
I’ve been using utvideo as my lossless codec of choice. (Remember, codec means encoder/decoder.) It compresses much like FLAC or ZIP files do: losslessly. And not just perceptual losslessness, but a mathematical one: what comes in will be exactly what comes out, bit for bit.
Download it here: https://github.com/umezawatakeshi/utvideo/releases
It’s an AVI VFW codec. In this instance, VFW means Video for Windows, and it’s just the... sort of universal API that any Windows program can call for. And AVI is the container, just like how MP4 and MKV are containers. MP4 as a file is not a video format, it’s a container. MPEG-4 AVC (aka H.264) is the video format specification you’re thinking of when you say “MP4″.
Here’s a typical AVI VFW window, you might have seen one in the wild already.
In apps that expose this setting, you can hit “configure” and set the prediction mode of utvideo to “median” to get some more efficient compression at the cost of slower decoding, but in practice this isn’t a problem.
Things to watch out for:
Any and all apps involved must support OpenDML AVIs. The original AVI spec is 2GB max only. This fixes that limitation. That’s normal, but make sure your apps support that. The OpenDML spec is from the mid-90s, so usually it’s not a problem. But for example, the SFM doesn’t support it.
The files WILL be very large. But they won’t be as large as they’d be if you had a truly uncompressed AVI.
SSDs are recommended within the bounds of reasonability, especially NVMe ones. 1080p30 should be within reach of traditional HDDs though.
utvideo will naturally perform better on CGI content rather than real-life footage and I would not recommend it at all for real-life footage, especially since you’re gonna get that in already-compressed form anyway. Do not convert your camera’s AVC/HEVC files to utvideo, it’s pointless. (Unless you were to do it as a proxy but still, kinda weird)
If you’re feeling adventurous, try out the YUV modes! They work great for matte passes, since those are often just luma-masks, so you don’t care about chroma subsampling.
If you don’t care about utvideo or don’t want to do AVIs for whatever reason, you could go the way of image sequences, but you’ll then be getting the OS-level overhead that comes with having dozens of thousands of files being accessed, etc.
They’re a valid option though. (Just not an efficient one in most cases.)
Some of my working files aren’t lossless...
Unfortunately we don’t all have 10 TB of storage in our computers. If you’re using compressed files as a source, make sure they get decoded properly by your video editing software. Make sure the colors, contrast, etc. match what you see in your “ground truth” player of choice. Make sure your “ground truth” player of choice really does represent the ground truth. Check with other devices if you can. You want to cross-reference to make sure.
One common thing that a lot of software screws up is BT.601 & BT.709 mixups. (It’s reds becoming a bit more orange.)
Ultimately you want your compressed footage to appear cohesive with your RGB footage. It should not have different ranges, different colors, etc.
For reasons that I don’t fully understand myself, 99% of AVC/H.264 video is “limited range”. That means that internally it’s actually squeezed into 16-235 as opposed to the original starting 0-255 (which is full range). And a limited range video gets decoded back to 0-255 anyway.
Sony/Magix Vegas Pro will decode limited range video properly but it will NOT expand it back to full 0-255 range, so it will appear with grayish blacks and dimmer whites. You can go into the “Levels” Effects tab to apply a preset that fixes this.
Exporting your video.
A lot of video editors out there are going to “render” your video (that is to say, calculate and render what the frames of your video look like) and encode it at the same time with whatever’s bundled in the software.
Do not ever do this with Vegas Pro. Do not ever rely on the integrated AVC encoders of Vegas Pro. They expect full range input, and encode AVC video as if it were full range (yeah), so if you want normal looking video, you have to apply a Levels preset to squeeze it into 16-235 levels, but it’s... god, honestly, just save yourself the headache and don’t use them.
Instead, export a LOSSLESS AVI out of Vegas. (using utvideo!)
But you may be able to skip this step altogether if you use Adobe Media Encoder, or software that can interface directly with it.
Okay, what do I do with this lossless AVI?
Option 1: Adobe Media Encoder.
Premiere and AE integrate directly with Adobe Media Encoder. It’s good; it doesn’t mix up BT.601/709, for example. In this case, you won’t have to export an AVI, you should be able to export “straight from the software”.
However, the integrated AVC/HEVC encoders that Adobe has licensed (from MainConcept, I believe) aren’t at the top of their game. Even cranking up the bitrate super high won’t reach the level of pristine that you’d expect (it keeps on not really allocating bits to flatter parts of the image to make them fully clean), and they don’t expose a CRF mode (more on that later), so, technically, you could still go with something better.
But what I’m getting at is, it’s not wrong to go with AME. Just crank up the bitrate though. (Try to reach 0.3 bits per pixel.) Here’s my quick rough quick guideline of Adobe Media Encoder settings:
H.264/AVC (faster encode but far from the most efficient compression one can have)
Switch from Hardware to Software encoding (unless you’re really in a hurry... but if you’re gonna be using Hardware encoding you might as well switch to H.265/HEVC, see below.)
Set the profile to High (you may not be able to do this without the above)
Bitrate to... VBR 1-pass, 30mbps for 1080p, 90mbps for 4K. Set the maximum to x2. +50% to both target and max if fps = 60.
“Maximum Render Quality” doesn’t need to be ticked, this only affects scaling. Only tick it if you are changing the final resolution of the video during this encoder step (e.g. 1080p source to be encoded as 720p)
If using H.265/HEVC (smaller file size, better for using same file as archive)
Probably stick with hardware encoding due to how slow software encoding is.
Stick to Main profile & Main tier.
If hardware: quality: Highest (slowest)
If software: quality: Higher.
4K: set Level to 5.2, 60mbps
1440p: set Level to 5.1, 40mbps
1080p: keep Level to 5.0, 25mbps
If 60fps instead of 24/30: +50% to bitrate. In which case you might have to go up to Level 6.2, but this might cause local playback issues; more on "Levels” way further down the post.
Keep in mind however that hardware encoders are far less efficient in terms of compression, but boy howdy are they super fast. This is why they become kind of worth it when it comes to H.265/HEVC. Still won’t produce the kind of super pristine result I’d want, but acceptable for the vast majority of YouTube cases.
Option 2: other encoding GUIs...
Find software of your choice that integrates the x264 encoder, which is state-of-the-art. (Again, x264 is one encoder for the H.264/AVC codec specification. Just making sure there’s no confusion here.)
Handbrake is one common choice, but honestly, I haven’t used it enough to vouch for it. I don’t know if the settings it exposes are giving you proper control over the whole BT601/709 mess. It has some UI/UX choices which I find really questionable too.
If you’re feeling like a command-line masochist, you could try using ffmpeg, but be ready to pour over the documentation. (I haven’t managed to find out how to do the BT.709 conversion well in there yet.)
Personally, I use MeGUI, because it runs through Avisynth (a frameserver), which allows me to do some cool preprocessing and override some of the default behaviour that other encoder interfaces would do. It empowers you to get into the nitty gritty of things, with lots of plugins and scripts you can install, like this one:
Once you’re in MeGUI, and it has finished updating its modules, you gotta hit CTRL+R to open the automated script creator. Select your input, hit “File Indexer” (not “One Click Encoder”), then just hit “Queue” so that Avisynth’s internal thingamajigs start indexing your AVI file. Once that’s done, you’ll be greeted with a video player and a template script.
In the script, all you need to add is this at the bottom:
This will perform the proper colorspace conversion, AND it does so with dithering! It’s the only software I know of which can do it with dithering!! I kid you not! Mode 7 means it’s doing it using a noise distribution that scales better and doesn’t create weird patterns when resizing the video (I would know, I’ve tried them all).
Your script should look like this, just 3 lines
LoadPlugin("D:\(path to megui, etc)\LSMASHSource.dll")
The colors WILL look messed up in the preview window but that’s normal. It’s one more example of how you should always be wary when you see an issue. Sometimes you don’t know what is misbehaving, and at which stage. Always try to troubleshoot at every step along the way, otherwise you will be chasing red herrings. Anyway...
Now, back in the main MeGUI window, we’ve got our first line complete (AviSynth script), the “Video Output” path should be autofilled, now we’re gonna touch the third line: “Encoder settings”. Make sure x264 is selected and hit “config” on the right.
Tick “show advanced settings.”
Set the encoding mode to “Const. Quality” (that’s CRF, constant rate factor). Instead of being encoded with a fixed bitrate, and then achieving variable quality with that amount of bits available, CRF instead encodes for a fixed quality, with a variable bitrate (whatever needs to be done to achieve that quality).
CRF 20 is the default, and it’s alright, but you probably want to go up to 15 if you really want to be pristine. I’m going up to 10 because I am unreasonable. (Lower is better, higher numbers means quality is worse.)
Because we’re operating under a Constant Quality metric, CRF 15 at encoder presets “fast” vs. “slow” will produce the same perceptual quality, but at different file sizes. Slow being smaller, of course.
You probably want to be at “slow” at least, there isn’t that much point in going to “slower” or “veryslow”, but you can always do it if you have the CPU horsepower to spare.
Make sure AVC Profile is set to High. The default would be Main, but High unlocks a few more features of the spec that increase compressability, especially at higher resolutions. (8x8 transforms & intra prediction, quantization scaling matrices, cb/cr controls, etc.)
Make sure to also select a Level. This doesn’t mean ANYTHING by itself, but thankfully the x264 config window here is smart enough to actually apply settings which are meaningful with regards to the level.
A short explanation is that different devices have different decoding capabilities. A decade ago, a mobile phone might have only supported level 3 in hardware, meaning that it could only do main profile at 30mbps max, and if you went over that, it would either not decode the video or do it using the CPU instead of its hardware acceleration, resulting in massive battery usage. The GPU in your computer also supports a maximum level. 5.0 is a safe bet though.
If you don’t restrict the level accordingly to what your video card supports, you might see funny things happen during playback:
It’s nothing that would actually affect YouTube (AFAIK), but still, it’s best to constrain.
Finally, head over to the “misc” tab of the x264 config panel and tick these.
If the command line preview looks like mine does (see the screenshot from a few paragraphs ago) then everything should be fine.
x264 is configured, now let’s take care of the audio.
Likewise, “Audio Input” and “Audio Output” should be prefilled if MeGUI detected an audio track in your AVI file. Just switch the audio encoder over to FLAC, hit config, crank the slider to “smallest file, slow encode” and you’re good to go. FLAC = mathematically lossless audio. Again, we want to not compress anything, or as little as possible until YouTube does its own compression job, so you might as well go with FLAC, which will equal roughly 700 to 1000kbps of audio, instead of going with 320kbps of MP3/AAC, which might be perceptually lossless, but is still compressed (bad). The added size is nothing next to the high-quality video track you’re about to pump out.
FLAC is not an audio format supported by the MP4 container, so MeGUI should have automagically changed the output to be using the MKV (Matroska) container. If it hasn’t, do it yourself.
Now, hit the “Autoencode” button in the lower right of the main window. And STOP, do not be hasty: in the new window, make sure “no target size” is selected before you do anything else. If you were to keep “file size” selected, then you would be effectively switched over to 2-pass encoding, which is another form of (bit)rate control. We don’t want that. We want CRF.
Hit queue and once it’s done processing, you should have a brand new pristine MKV file that constains lossless audio and extra clean video! Make sure to double-check that everything matches—take screenshots of the same frames in the AVI and MKV files and compare them.
Now all you’ve got to do is send it to YouTube!
For archival... well, you could just go and crank up the preset to Placebo and reduce CRF a little bit—OR you could use the 2-pass “File Size” mode which will ensure that your video stream will be the exact size (give or take a couple %) you want it to be. You could also use x265 for your archival file buuuut I haven’t used it enough (on account of how slow it is) to make sure that it has no problems anywhere with the whole BT.601/708 thing. It doesn’t expose those metadata settings so who knows how other software’s going to treat those files in the future... (god forbid they get read as BT.2020)
You can use Mediainfo (or any player that integrates it, like my favorite, MPC-HC) to check the metadata of the file.
Good luck out there!
And remember to always double-check the behaviour of decoders at every step of the way with your setup. 99% of the time I see people talk about YouTube messing with the contrast of their video, it’s because they weren’t aware of how quirky Vegas can be with H.264/AVC input & its integrated encoder.
wanted to see if there was any visible difference between the different qtgmc modes for gif making with avisynth.
my steps:
60fps H264 .ts file clipped into smaller .ts files (no file conversion or re-encoding, thus no quality loss... hopefully. I’m not an expert)
avisynth’s video folder > x264losslesswebm.bat (command prompt showed a bunch of errors but put the file thru anyway so I’m not exploring these errors. normalwebm.bat should work too)
deblinear, no extra sharpening
lighting/coloring psd and 0.03 frame delay applied to all gifs
conclusions:
to the naked eye these gifs look the damn same lmao
fast/slow doesn’t affect the flow of the gif
between 30 fast and 60 fast, there is no visible difference in the pixels of the frames. no difference in the frames of 30 slow compared to 60 slow either
HOWEVER... the pixels of fast are slightly less defined than the pixels of slow (see yonghee’s mole; 1000% zoom)
60 slow took So Fucking Long so i’m probably sticking to 30 slow
note: qtgmc 60 fast/slow duplicated every frame despite this being a 60fps video, so I limited to every 2nd frame when converting video frames to layers in photoshop