Introduction

This is an article for everyone who does not want to spend hours messing around with the AVIFile functions, if he only wants to read or change a simple AVI video. I have wrapped the most important AVIFile functions into three easy to use C# classes that can handle the following tasks:

Read images from the video stream.

Decompress a compressed video stream.

Compress an uncompressed video stream.

Change the compression of a video stream.

Export the video stream into a separate .avi file.

Export the audio stream into a .wav file.

Copy a couple of seconds from audio and video stream into a new .avi file.

Add sound from a .wav file to the video.

Create a new video stream from a list of bitmaps.

Add frames to an existing video stream, compressed or not.

Insert frames into a stream.

Copy or delete frames from a stream.

These features cover the common use cases like creating a video from a couple of images and a wave sound, extracting the sound track from a video, cutting out short clips, or grabbing a single picture from a movie.

This article has got two sections:

First, I'll explain the demo application so that you can use it to explore the library on your own.

Then, I'll explain how the library works step by step.

How to use the library - A walk through the demo application

The Explore tab

At the top of the form, you can choose the AVI file you want to explore. text.avi from the test data folder is pre-selected. On the left side, you can display header information about the video and the wave sound stream (if available). Also, you can see image frames from the video in a PictureBox:

The images are read by a VideoStream object. GetFrameOpen prepares the stream for decompressing frames, GetFrameClose releases the resources used to decompress the frame, and GetBitmap decompresses a frame and converts it to a System.Drawing.Bitmap.

Decompress removes the compression from a video stream. It creates a new file and video stream, decompresses each frame from the old stream, and writes it into the new stream. The result is a large new .avi file with the same video but no compression.

Compress changes the compression of the video, or applies compression to an uncompressed video. It does the same as Uncompress, but compresses the new stream. These two functions use the same method CopyFile:

Add Sound lets you choose a .wav file, and adds it to the video. You can use this feature to add a sound track to a silent video, for example, re-add the sound to a video extracted with Extract Video. Adding sound is a simple task of three lines:

The last set of functions is about creating new video streams. Enter a list of image files in the box and animate them:

Create uncompressed builds a new video from the images, and saves it without any compression. Create and Compress does the same, except that it displays the compression settings dialog and compresses the images. Both methods create a new file, and pass a sample bitmap to AddVideoStream. The sample bitmap is used to set the format of the new stream. Then, all the images from the list are added to the video.

Add Frames appends the images to the existing video stream. To an uncompressed video stream, we could append frames by simply opening the stream and adding frames as usual. But a compressed stream cannot be re-compressed. AVIStreamWrite - used by AddFrame - would not return any error; but anyway, it would add the new frames uncompressed and produce nothing but strangely colored pixel storms. To add frames to a compressed stream, the existing frames must be decompressed and added to a new compressed stream. Then the additional frames can be added to that stream:

Now that you know how to use the AVIFile wrapper classes, let's have a look at the background.

The Edit tab

The Edit tab demonstrates tasks for editable AVI streams, like pasting frames at any position in the stream, or changing the frame rate:

When you have chosen a file to edit, an editable stream is created from the video stream, and the editor buttons become enabled. A normal video stream is locked; for inserting and deleting frames, you need an editable stream:

The last box is not for editing, it is only a preview player. You should preview your editable stream before saving it to an AVI file.

A preview player is easy to implement, you only need a PictureBox and the video stream you want to play. A label displaying the current frame index can be helpful, too. A start button, a stop button, and there you are:

How it works

AviManger manages the streams in an AVI file. The constructor takes the name of the file and opens it. Close closes all opened streams and the file itself. You can add new streams with AddVideoStream and AddAudioStream. New video streams are empty, Wave streams can only be created from Wave files. After you have created an empty video stream, use the methods of VideoStream to fill it. But what actually happens when you add a stream?

Create a video stream

There are two methods for creating a new video stream: create from a sample bitmap, or create from explicit format information. Both methods do the same, they pass their parameter on to VideoStream and add the new stream to the internal list of opened streams, to close them before closing the file:

AVICOMPRESSOPTIONS_CLASS is the AVICOMPRESSOPTIONS structure as a class. Using classes instead of structures is the easiest way to deal with pointers to pointers. If you don't know what I'm talking about, you probably have never used AVISaveOptions or AVISaveV in .NET. Take a look at the original declaration:

LPAVICOMPRESSOPTIONS is a pointer to a pointer to an AVICOMPRESSOPTIONS structure. In C#, structures are passed by value. If you pass a structure by ref, a pointer to the structure is passed. Instances of classes are always passed to methods as pointers. So a class-parameter by ref means a pointer to a pointer to the object. The C# declarations of AVISaveOptions and AVICOMPRESSOPTIONS are:

DecompressToNewFile creates a writeable copy of the stream in a new file. You can add frames to this new stream, close the new AviManager to save it, and then add the sound stream from the old file to complete the copy. Adding frames to a video is not easy, but this way it works.

Separate a stream

Sometimes, you might have a video file with sound, but you only need the silent video, or only the sound. It is not necessary to copy each frame, you can open the stream as usual and export it with AVISaveV. This works with all kinds of streams, only the compression options are different:

Import sound from a Wave file

Now, we are able to build a video from bitmaps, and extract sound from it. And how does the sound get into the file? We could use AVISaveV again, to combine the video and audio streams in a new file - but we don't have to. The easiest way to add a new audio stream is to open the Wave file as an AVI file with only one stream, and then copy that stream:

Copy a clip from video and sound

I have added this method, because many people asked me how this could be done. To copy a part of the video stream from second X to second Y, the indices of the first and last frames have to be calculated from the frame rate and second. For the Wave stream, we must calculate the byte offsets from samples per second, bits per sample, and the requested seconds. The rest is only copy and paste:

at first: Thanks! I started writing nearly the same wrapper until I found out you already did it.
I am using this wrapper to extract frames which I convert to OpenGL textures and I synchronize
repaint events using the number of milliseconds per frame... I've added this to my wrapper before
I found yours and find it really useful. You might want to add it as well.

I have a question regarding 8bpp bitmap (gray-scale images) files. When I try extract set of 8bpp into AVI file then AVI file is very poor quality ( pink, green, etc. colors...) It's not similar to separates bitmaps

Madam ,
I'm using ur code for my research purpose and the problem is its not opening other avi files except the one u gave (test.avi). How can we analyse another avi video. This avi is being played by the windows media player and all other players.
Venu

This is a fantastic library and demo program. Thank you. Just what I was looking for to do some home cooked video editing. However -
When I try to copy a movie from my digital camera with a frame rate of 29.724518456389 the result has a different rate. The problem is with the GetRateAndScale routine in VideoStream.cs which tries to make an integer for the Rate. There are many ways to fix it. I just capped the scale at 1000000. Bob

It's important to note that codecs play an important part of this code working. The operating system that the code is working against needs the appropriate codecs your AVI is using (if you plan on opening/reading from existing AVIs).

But i have a question about the videoStream framerate,i found it`s not accurately.Because just use Thread.Sleep(millisecondsPerFrame),ignore the cost of the code in the for circle before Thread.Sleep().I make a test, implement the code cost 30-50ms, therefore, i use Thread.Sleep(millisecondsPerFrame-time cost by the code),but when i set framerate larger then 25,it still not accurately.So, i want to konw how to make it accurately.Thanks.

Great job on the lib, not only it wll be able to save me alot of time to write something similar, but it also helped me understand bettr how the avi format works.

every AVI file I've downloaded from the internet seems to kill the app in the AVIStreamGetFrameOpen step.
is it beacuse they ae prbably AVI 2.0?
if so, do you have a recommendation as to what to do with it?
I need to open AVI files so I will be able to use the data inside them (I'm trying to implement the video snapcut algorithm) and meanwhile your video stream calss seems to be the best way to do so.