Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C#
Article

Steganography IV - Reading and Writing AVI files

Rate me:
Please Sign up or sign in to vote.
4.90/5 (57 votes)
19 May 2004CPOL4 min read 512.1K   12.4K   116   139
An article about hiding bytes in the bitmap frames of uncompressed AVI files.

Introduction

The video stream in an AVI file is nothing more than a sequence of bitmaps. This article is about extracting these bitmaps and re-building the stream, in order to hide a message in the video.

Background

Before reading this article, you should have read at least part one, Steganography - Hiding messages in the Noise of a Picture. This one uses the application described in parts 1-3, but you don’t need the extended features to understand it.

Reading the Video Stream

The Windows AVI library is a set of functions in avifil32.dll. Before it is ready to use, it has to be initialized with AVIFileInit. AVIFileOpen opens the file, AVIFileGetStream finds the video stream. Each of these functions allocates memory which has to be released.

C#
//Initialize the AVI library
[DllImport("avifil32.dll")]
public static extern void AVIFileInit();

//Open an AVI file
[DllImport("avifil32.dll", PreserveSig=true)]
public static extern int AVIFileOpen(
    ref int ppfile,
    String szFile,
    int uMode,
    int pclsidHandler);

//Get a stream from an open AVI file
[DllImport("avifil32.dll")]
public static extern int AVIFileGetStream(
    int pfile,
    out IntPtr ppavi,  
    int fccType,       
    int lParam);

//Release an open AVI stream
[DllImport("avifil32.dll")]
public static extern int AVIStreamRelease(IntPtr aviStream);

//Release an ope AVI file
[DllImport("avifil32.dll")]
public static extern int AVIFileRelease(int pfile);

//Close the AVI library
[DllImport("avifil32.dll")]
public static extern void AVIFileExit();

Now we are able to open an AVI file and get the video stream. AVI files can contain many streams of four different types (Video, Audio, Midi and Text). Usually there is only one stream of each type, and we are only interested in the video stream.

C#
private int aviFile = 0;
private IntPtr aviStream;

public void Open(string fileName) {
    AVIFileInit(); //Intitialize AVI library
    
    //Open the file
    int result = AVIFileOpen(
        ref aviFile,
        fileName,
        OF_SHARE_DENY_WRITE, 0);
    
    //Get the video stream
    result = AVIFileGetStream(
        aviFile,
        out aviStream,
        streamtypeVIDEO, 0);
}

Before we start reading the frames, we must know what exactly we want to read:

  • Where does the first frame begin?
  • How many frames are available?
  • What is the height/width of the images?

The AVI library contains a function for every question.

C#
//Get the start position of a stream
[DllImport("avifil32.dll", PreserveSig=true)]
public static extern int AVIStreamStart(int pavi);

//Get the length of a stream in frames
[DllImport("avifil32.dll", PreserveSig=true)]
public static extern int AVIStreamLength(int pavi);

//Get header information about an open stream
[DllImport("avifil32.dll")]
public static extern int AVIStreamInfo(
    int pAVIStream,
    ref AVISTREAMINFO psi,
    int lSize);

With these functions we can fill a BITMAPINFOHEADER structure. To extract the images, we need three more functions.

C#
//Get a pointer to a GETFRAME object (returns 0 on error)
[DllImport("avifil32.dll")]
public static extern int AVIStreamGetFrameOpen(
    IntPtr pAVIStream,
    ref BITMAPINFOHEADER bih);

//Get a pointer to a packed DIB (returns 0 on error)
[DllImport("avifil32.dll")]
public static extern int AVIStreamGetFrame(
    int pGetFrameObj,
    int lPos);

//Release the GETFRAME object
[DllImport("avifil32.dll")]
public static extern int AVIStreamGetFrameClose(int pGetFrameObj);

Finally we are ready to decompress the frames...

C#
//get start position and count of frames
int firstFrame = AVIStreamStart(aviStream.ToInt32());
int countFrames = AVIStreamLength(aviStream.ToInt32());

//get header information            
AVISTREAMINFO streamInfo = new AVISTREAMINFO();
result = AVIStreamInfo(aviStream.ToInt32(), ref streamInfo,
    Marshal.SizeOf(streamInfo));

//construct the expected bitmap header
BITMAPINFOHEADER bih = new BITMAPINFOHEADER();
bih.biBitCount = 24;
bih.biCompression = 0; //BI_RGB;
bih.biHeight = (Int32)streamInfo.rcFrame.bottom;
bih.biWidth = (Int32)streamInfo.rcFrame.right;
bih.biPlanes = 1;
bih.biSize = (UInt32)Marshal.SizeOf(bih);

//prepare to decompress DIBs (device independend bitmaps)
int getFrameObject = AVIStreamGetFrameOpen(aviStream, ref bih);

...

//Export the frame at the specified position
public void ExportBitmap(int position, String dstFileName){
    //Decompress the frame and return a pointer to the DIB
    int pDib = Avi.AVIStreamGetFrame(getFrameObject, firstFrame + position);

    //Copy the bitmap header into a managed struct
    BITMAPINFOHEADER bih = new BITMAPINFOHEADER();
    bih = (BITMAPINFOHEADER)Marshal.PtrToStructure(new IntPtr(pDib),
        bih.GetType());
    
    //Copy the image
    byte[] bitmapData = new byte[bih.biSizeImage];
    int address = pDib + Marshal.SizeOf(bih);
    for(int offset=0; offset<bitmapData.Length; offset++){
        bitmapData[offset] = Marshal.ReadByte(new IntPtr(address));
        address++;
    }

    //Copy bitmap info
    byte[] bitmapInfo = new byte[Marshal.SizeOf(bih)];
    IntPtr ptr;
    ptr = Marshal.AllocHGlobal(bitmapInfo.Length);
    Marshal.StructureToPtr(bih, ptr, false);
    address = ptr.ToInt32();
    for(int offset=0; offset<bitmapInfo.Length; offset++){
        bitmapInfo[offset] = Marshal.ReadByte(new IntPtr(address));
        address++;
    }

...and store them in bitmap files.

C#
    //Create file header
    Avi.BITMAPFILEHEADER bfh = new Avi.BITMAPFILEHEADER();
    bfh.bfType = Avi.BMP_MAGIC_COOKIE;
    //size of file as written to disk

    bfh.bfSize = (Int32)(55 + bih.biSizeImage);
    bfh.bfOffBits = Marshal.SizeOf(bih) + Marshal.SizeOf(bfh);

    //Create or overwrite the destination file
    FileStream fs = new FileStream(dstFileName, System.IO.FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);

    //Write header
    bw.Write(bfh.bfType);
    bw.Write(bfh.bfSize);
    bw.Write(bfh.bfReserved1);
    bw.Write(bfh.bfReserved2);
    bw.Write(bfh.bfOffBits);
    //Write bitmap info
    bw.Write(bitmapInfo);
    //Write bitmap data
    bw.Write(bitmapData);
    bw.Close();
    fs.Close();
} //end of ExportBitmap

The application can use the extracted bitmaps just like any other image file. If one carrier file is an AVI video, it extracts the first frame to a temporary file, opens it and hides a part of the message. Then it writes the resulting bitmap to a new video stream, and continues with the next frame. After the last frame the application closes both video files, deletes the temporary bitmap file, and continues with the next carrier file.

Writing to a Video Stream

When the application opens an AVI carrier file, it creates another AVI file for the resulting bitmaps. The new video stream must have the same size and frame rate as the original stream, so we cannot create it in the Open() method. When the first bitmap arrives, we know the frame size and are able to create a video stream. The functions to create streams and write frames are AVIFileCreateStream, AVIStreamSetFormat and AVIStreamWrite:

C#
//Create a new stream in an open AVI file
[DllImport("avifil32.dll")]
public static extern int AVIFileCreateStream(
    int pfile,
    out IntPtr ppavi, 
    ref AVISTREAMINFO ptr_streaminfo);

//Set the format for a new stream
[DllImport("avifil32.dll")]
public static extern int AVIStreamSetFormat(
    IntPtr aviStream, Int32 lPos, 
    ref BITMAPINFOHEADER lpFormat, Int32 cbFormat);

//Write a sample to a stream
[DllImport("avifil32.dll")]
public static extern int AVIStreamWrite(
    IntPtr aviStream, Int32 lStart, Int32 lSamples, 
    IntPtr lpBuffer, Int32 cbBuffer, Int32 dwFlags, 
    Int32 dummy1, Int32 dummy2);

Now we can create a stream...

//Create a new video stream
private void CreateStream() {
    //describe the stream to create
    AVISTREAMINFO strhdr = new AVISTREAMINFO();
    strhdr.fccType = this.fccType; //mmioStringToFOURCC("vids", 0)
    strhdr.fccHandler = this.fccHandler; //"Microsoft Video 1"
    strhdr.dwScale = 1;
    strhdr.dwRate = frameRate;
    strhdr.dwSuggestedBufferSize = (UInt32)(height * stride);
    //use highest quality! Compression destroys the hidden message.
    strhdr.dwQuality = 10000;
    strhdr.rcFrame.bottom = (UInt32)height;
    strhdr.rcFrame.right = (UInt32)width;
    strhdr.szName = new UInt16[64];
    
    //create the stream
    int result = AVIFileCreateStream(aviFile, out aviStream, ref strhdr);

    //define the image format
    BITMAPINFOHEADER bi = new BITMAPINFOHEADER();
    bi.biSize      = (UInt32)Marshal.SizeOf(bi);
    bi.biWidth     = (Int32)width;
    bi.biHeight    = (Int32)height;
    bi.biPlanes    = 1;
    bi.biBitCount  = 24;
    bi.biSizeImage = (UInt32)(this.stride * this.height);

    //format the stream
    result = Avi.AVIStreamSetFormat(aviStream, 0, ref bi, Marshal.SizeOf(bi));
}

...and write video frames.

C#
//Create an empty AVI file
public void Open(string fileName, UInt32 frameRate) {
    this.frameRate = frameRate;

    Avi.AVIFileInit();
    
    int hr = Avi.AVIFileOpen(
        ref aviFile, fileName, 
        OF_WRITE | OF_CREATE, 0);
}

//Add a sample to the stream - for first sample: create the stream 
public void AddFrame(Bitmap bmp) {
    BitmapData bmpDat = bmp.LockBits(
        new Rectangle(0, 0, bmp.Width, bmp.Height),
        ImageLockMode.ReadOnly,PixelFormat.Format24bppRgb);

    //this is the first frame - get size and create a new stream
    if (this.countFrames == 0) {
        this.stride = (UInt32)bmpDat.Stride;
        this.width = bmp.Width;
        this.height = bmp.Height;
        CreateStream(); //a method to create a new video stream
    }

    //add the bitmap to the stream
    int result = AVIStreamWrite(aviStream,
        countFrames, 1, 
        bmpDat.Scan0, //pointer to the beginning of the image data
        (Int32) (stride  * height), 
        0, 0, 0); 

    bmp.UnlockBits(bmpDat);
    this.countFrames ++;
}

That's all we need to read and write video streams. Non-video streams and compression are not interesting at the moment, because compression destroys the hidden message by changing colours, and sound would make the files even larger - uncompressed AVI files are big enough! ;-)

Changes in CryptUtility

The HideOrExtract() method used to load all carrier images at once. This was no good from the beginning, and now it became impossible. From now on HideOrExtract() loads only one bitmap, and disposes it before loading the next one. The currently used carrier image - simple bitmap or extracted AVI frame - is stored in a BitmapInfo structure, which is passed around by ref.
C#
public struct BitmapInfo{
    //uncompressed image
    public Bitmap bitmap;
    
    //position of the frame in the AVI stream, -1 for non-avi bitmaps
    public int aviPosition;
    //count of frames in the AVI stream, or 0 for non-avi bitmaps
    public int aviCountFrames;
    
    //path and name of the bitmap file
    //this file will be deleted later, if aviPosition is 0 or greater
    public String sourceFileName;
    //how many bytes will be hidden in this image
    public long messageBytesToHide;

    public void LoadBitmap(String fileName){
        bitmap = new Bitmap(fileName);
        sourceFileName = fileName;
    }
}

Whenever MovePixelPosition moves the position into the next carrier bitmap, it checks the field aviPosition. If aviPosition is < 0, it saves and disposes the bitmap. If aviPosition is 0 or greater, it is a frame in an AVI stream. It is not saved to a file, but added to the open AVI stream. If the bitmap was a simple image or the last frame of an AVI stream, the method opens the next carrier file. If there are more frames in the AVI stream, is exports and loads the next bitmap.

Using the code

There are three new classes in the project:

  • AviReader opens existing AVI files and copies frames to bitmap files.
  • AviWriter creates new AVI files and combines bitmaps to a video stream.
  • Avi contains the function declarations and structure definitions.

Thanks

Thanks to Shrinkwrap Visual Basic, for the "Visual Basic AVIFile Tutorial". The examples could not be easily converted to VB.NET or C#, but they gave me important hints on how to copy DIBs.

Thanks to Rene N., who posted an AviWriter class in microsoft.public.dotnet.languages.csharp.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
Corinna lives in Hanover/Germany and works as a C# developer.

Comments and Discussions

 
Generalsize of output files Pin
DavidMT4-Jan-05 2:07
DavidMT4-Jan-05 2:07 
GeneralConvert AVI to BMP or JPG using VB6 Pin
Wahaj Khan23-Dec-04 5:16
Wahaj Khan23-Dec-04 5:16 
GeneralRe: Convert AVI to BMP or JPG using VB6 Pin
Corinna John23-Dec-04 6:00
Corinna John23-Dec-04 6:00 
GeneralI'm big lamer :))) Pin
Anonymous1-Nov-04 6:46
Anonymous1-Nov-04 6:46 
GeneralBig trouble!!!!!! Pin
ixyildirim22-Oct-04 2:09
ixyildirim22-Oct-04 2:09 
Generali wanna know avifil32 functions Pin
ixyildirim22-Oct-04 2:04
ixyildirim22-Oct-04 2:04 
GeneralRe: i wanna know avifil32 functions Pin
Corinna John22-Oct-04 3:30
Corinna John22-Oct-04 3:30 
GeneralRe: i wanna know avifil32 functions Pin
atherqurashi10-May-06 0:34
atherqurashi10-May-06 0:34 
QuestionHow to Edit a video file and after how to stored into another file in .net Pin
Member 113378529-Sep-04 22:01
Member 113378529-Sep-04 22:01 
Generalsize of files in C# Pin
Member 125868528-Sep-04 0:47
Member 125868528-Sep-04 0:47 
GeneralRe: size of files in C# Pin
Corinna John28-Sep-04 1:09
Corinna John28-Sep-04 1:09 
GeneralRe: size of files in C# Pin
kuntal4110127-Apr-12 12:18
kuntal4110127-Apr-12 12:18 
QuestionHow to do we convert AVI Files to WMI Files using C# Pin
pubududilena31-Aug-04 1:13
pubududilena31-Aug-04 1:13 
QuestionVC6++ HELP HOW??? Pin
cnncnn18-Aug-04 20:19
cnncnn18-Aug-04 20:19 
GeneralWriting different size bitmaps to AVI Pin
kevinmrkr24-Jun-04 10:41
kevinmrkr24-Jun-04 10:41 
GeneralRe: Writing different size bitmaps to AVI Pin
Corinna John26-Jun-04 13:22
Corinna John26-Jun-04 13:22 
GeneralRe: Writing different size bitmaps to AVI Pin
Anonymous27-Jun-04 11:16
Anonymous27-Jun-04 11:16 
GeneralProblem with AVIStreamGetFrameOpen Pin
rolaustral8-Jun-04 15:23
rolaustral8-Jun-04 15:23 
GeneralRe: Problem with AVIStreamGetFrameOpen Pin
Corinna John9-Jun-04 5:06
Corinna John9-Jun-04 5:06 
Generaldo I miss something Pin
=aKe=28-May-04 7:44
=aKe=28-May-04 7:44 
GeneralProblem reading compressed streams Pin
sherrinmultimedia24-Apr-04 14:38
sherrinmultimedia24-Apr-04 14:38 
GeneralRe: Problem reading compressed streams Pin
sherrinmultimedia28-Apr-04 5:23
sherrinmultimedia28-Apr-04 5:23 
GeneralGreat! Pin
Daniel Turini23-Apr-04 6:45
Daniel Turini23-Apr-04 6:45 
GeneralRe: Great! Pin
Corinna John23-Apr-04 7:50
Corinna John23-Apr-04 7:50 
GeneralAudio Stream Pin
KeitaroSan17-Apr-04 18:37
KeitaroSan17-Apr-04 18:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.