Click here to Skip to main content
15,880,956 members
Articles / Programming Languages / Visual Basic
Article

How to create a simple SWF decompiler with the SwfDotNet library

Rate me:
Please Sign up or sign in to vote.
4.60/5 (16 votes)
20 Dec 20062 min read 206.3K   9.9K   86   41
How to create a simple SWF decompiler with the SwfDotNet library

Swf Decompiler sample with C#

Goal of this article

This article's main goal is to show how to manage SWF encoded files with .NET, C#, or VB.NET. SWF is a binary format which represents compiled Flash animations.

Using the SwfDotNet library

The SwfDotNet library is a C# open source framework available at:

This library offers some good stuff to read and write SWF format files from version 1 to 7 for now. SwfDotNet.IO.dll is compatible with the .NET framework 1.1, 2.0 and +. This library respects MacromediaTM SWF format specifications. You can read and download the Macromedia official specifications here.

For our decompiler application, we used this framework like in these examples:

Include the SwfDotnNet library in your class:

C#
using SwfDotNet.IO;

Create a SwfReader object to get a Swf object:

C#
// Create a swf stream reader
SwfReader swfReader = new SwfReader("myfile.swf");
// Read the completed swf file
Swf swf = swfReader.ReadSwf();
// Read only headers of file to optimize read speed
//Swf swf = swfReader.ReadSwfHeader();
// Write swf file version
Console.WriteLine("Version: " + swf.Version);
// Write swf animation dimensions
Console.WriteLine("Size: " + swf.Header.Width + 
                  "x" + swf.Header.Height);
// Write swf fps
Console.WriteLine("Fps: " + swf.Header.Fps);
// Write swf file size
Console.WriteLine("File size: " + swf.Header.FileSize);
// Write swf file frames count
Console.WriteLine("Frames count: " + swf.Header.Frames);
// Write swf file signature (compressed or not)
Console.WriteLine("Signature: " + swf.Header.Signature);
// Closing stream reader
swfReader.Close();

Write in a Swf object and save as an SWF file or stream:

C#
// Create a new swf animation
Swf swf = new Swf();
// Define background as blue
swf.Tags.Add(new SetBackgroundColorTag(255, 0, 0));
// Define a new frame
swf.Tags.Add(new ShowFrameTag());

// Define a swf writer
SwfWriter writer = new SwfWriter("myfile.swf");
// Write animation
writer.Write(swf);
// Close the stream
writer.Close();

List of available tag objects in the framework:

C#
// Include tags namespace
using SwfDotNet.IO.Tags;

...
// Tags are organized as followed:
// 1. To control the frames flow
// Create a new frame 
ShowFrameTag resTag = new ShowFrameTag();
// End of frames sequence 
EndTag resTag = new EndTag();
// Define a frame name 
FrameLabelTag resTag = new FrameLabelTag();
// Place an object to the screen 
PlaceObjectTag resTag = new PlaceObjectTag();
// Place an object to the screen 
PlaceObject2Tag resTag = new PlaceObject2Tag();
// Remove an object of the screen 
RemoveObjectTag resTag = new RemoveObjectTag();
// Remove an object of the screen 
RemoveObject2Tag resTag = new RemoveObject2Tag();
// Define background color 
SetBackgroundColorTag resTag = new SetBackgroundColorTag();
// Protect the animation 
ProtectTag resTag = new ProtectTag();
// Define tag index of object 
SetTabIndexTag resTag = new SetTabIndexTag();

// 2. To embed a picture in an animation
//Add bitmap or gif 
DefineBitsTag resTag = new DefineBitsTag();
//Define bitmap  
DefineBitsLossLessTag resTag = new DefineBitsLossLessTag();
//Define bitmap with transparency 
DefineBitsLossLess2Tag resTag = new DefineBitsLossLess2Tag();
//Define a jpeg compression table 
JpegTableTag resTag = new JpegTableTag();
// To include jpeg files
DefineBitsJpeg2Tag resTag = new DefineBitsJpeg2Tag();
//To include transparent jpeg files
DefineBitsJpeg3Tag resTag = new DefineBitsJpeg3Tag();

// 3. To define new button
// To create a simple button
DefineButtonTag resTag = new DefineButtonTag();
// To create a simple button
DefineButton2Tag resTag = new DefineButton2Tag();
// To create a simple button
DefineButtonCxFormTag resTag = new DefineButtonCxFormTag();
// To create a button with sound
DefineButtonSoundTag resTag = new DefineButtonSoundTag();

// 4. To create a new movie clip (container of tags sequence)
DefineSpriteTag resTag = new DefineSpriteTag();

// 5. To add text
// To create an edit text area
DefineEditTextTag resTag = new DefineEditTextTag();
// To use a font
DefineFontTag resTag = new DefineFontTag();
DefineFont2Tag resTag = new DefineFont2Tag();
DefineFontInfoTag resTag = new DefineFontInfoTag();
DefineFontInfo2Tag resTag = new DefineFontInfo2Tag();
// To add static text
DefineTextTag resTag = new DefineTextTag();
// To add static text
DefineText2Tag resTag = new DefineText2Tag();

// 6. Define shapes or morph shapes to draw
// To create morph shapes
DefineMorphShapeTag resTag = new DefineMorphShapeTag();
// To create glyph shapes
DefineShapeTag resTag = new DefineShapeTag();
// To create glyph shapes
DefineShape2Tag resTag = new DefineShape2Tag();
// To create glyph shapes
DefineShape3Tag resTag = new DefineShape3Tag();

// 7. Audio and video embedding
DefineSoundTag resTag = new DefineSoundTag();    
SoundStreamBlockTag resTag = new SoundStreamBlockTag();
SoundStreamHeadTag resTag = new SoundStreamHeadTag();
SoundStreamHead2Tag resTag = new SoundStreamHead2Tag();
StartSoundTag resTag = new StartSoundTag();
DefineVideoStreamTag resTag = new DefineVideoStreamTag();    
VideoFrameTag resTag = new VideoFrameTag();

// 8. Add action script and debugg
// Add action script code
DoActionTag resTag = new DoActionTag();
// Enable debugger
EnableDebuggerTag resTag = new EnableDebuggerTag();
// Enable debugger
EnableDebugger2Tag resTag = new EnableDebugger2Tag();
// Export assets
ExportAssetsTag resTag = new ExportAssetsTag();
// Import assets
ImportAssetsTag resTag = new ImportAssetsTag();
// Init action
InitActionTag resTag = new InitActionTag();
ScriptLimitTag resTag = new ScriptLimitTag();

Use the byte code decompiler to get the action script code of an Action tag:

C#
//include bytecode management namespace 
using SwfDotNet.IO.ByteCode;

...
//Browse swf tags list
IEnumerator tagsEnu = swf.Tags.GetEnumerator();
while (tagsEnu.MoveNext())
{
  BaseTag tag = (BaseTag)tagsEnu.Current;
  if (tag.ActionRecCount != 0)
  // The tag contains action script ?
  {
    IEnumerator byteCodeEnu = tag.GetEnumerator();
    while (enum2.MoveNext())
    {
      //Init the action script decompiler
      Decompiler dc = new Decompiler(swf.Version);
      //Decompile the current actionscript action from a tag 
      ArrayList actions = dc.Decompile((byte[])tagsEnu.Current);
      foreach (BaseAction obj in actions)
      {
        //Write action script byte code to the console
        Console.WriteLine(obj.ToString());
      }
    }
  }
}

We can directly extract media files from tags:

C#
//Browse swf tags list
IEnumerator tagsEnu = swf.Tags.GetEnumerator();
while (tagsEnu.MoveNext())
{
  BaseTag tag = (BaseTag)tagsEnu.Current;
  if (tag is DefineBitsJpeg2Tag) //Extract a jpeg:
  {
    //Extract to a file:
    ((DefineBitsJpeg2Tag)tag).DecompileToFile("extract_image.jpeg");
    //Or in a stream:
    Image img = ((DefineBitsJpeg2Tag)tag).DecompileToImage();
  }
  else if (tag is DefineSoundTag) //Extract a sound file:
  {
    DefineSoundTag soundTag = (DefineSoundTag)tag;
    //Extract to a file
    if (soundTag.SoundFormat == SoundCodec.MP3)
      soundTag.DecompileToFile("extract_sound.mp3");
    else
      soundTag.DecompileToFile("extract_sound.wav");
  }
}

Creating the SWF decompiler sample

The goal of this sample is to create a very simple SWF decompiler. From a compiled FlashTM animation (SWF file), we want to load it, and extract in separate files, all the pictures and all the embedded MP3 files.

Attention: This sample decompiler is not a full SWF decompiler! This sample only decompiles embedded JPEG files without the JPEG table, and only non-streamed MP3 and WAV sounds. Only the action script byte code is extracted too.

You can see a file called SwfDecompiler.exe.log.xml in the project, this file is the log4net framework configuration file. For more information about log4net, you can read this article or go to the official web site.

The SwfDotNet library uses log4net for all the trace operations. When you read an SWF file, you can trace all the SWF tags read by the SwfReader object, and you can trace the different shapes contained by a DefineShape tag for example.

To do it, just change these lines in the SwfDecompiler.exe.log.xml file:
XML
<!-- To trace tags readed -->
<logger name="SwfDotNet.IO">
  <level value="ALL" />  <!-- Turn it to ALL -->
</logger>

<!-- To trace shapes readed -->
<logger name="SwfDotNet.IO.Tags.Types">
  <level value="ALL" />  <!-- Turn it to ALL -->
</logger>

If you change these values and execute the decompiler one more time, a file named "Log.txt" will appear in the same directory of the application, with some lines like this::

[DEBUG] - **************** Start to decompile file ..\input\sample.swf
[INFO ] - SetBackgroundColor....OK (5)
[INFO ] - SoundStreamHead2....OK (6)
[INFO ] - DefineBitsJpeg2....OK (43816)      <== A DefineBitsJpeg2 
                                                tag has been readed 
                                                which contains 
                                                43816 octects of data
[INFO ] - Shape: StyleChangeRecord                
[INFO ] - Shape: StraightedEdgeRecord
[INFO ] - Shape: StraightedEdgeRecord        <== A straighted edge 
                                                 shape has been readed
[INFO ] - Shape: StraightedEdgeRecord
[INFO ] - Shape: StraightedEdgeRecord
[INFO ] - Shape: EndShapeRecord    
[INFO ] - DefineShape....OK (61)
[INFO ] - PlaceObject2....OK (8)
[INFO ] - DefineSound....OK (8439)
[INFO ] - StartSound....OK (9)
[INFO ] - DefineSound....OK (293373)
[INFO ] - StartSound....OK (9)
[INFO ] - ShowFrame....OK (2)
[INFO ] - ShowFrame....OK (2)
.....

Conclusion

As you can see, thanks to the SwfDotNet library, you can easily analyse, manage, create, read, or write SWF binary files. This sample is a really "light" SWF decompiler but shows the way to do it, shows how to do a real one, and doesn't require to be a binary reading process expert.

Moreover, the SwfDotNet library is 100% free (GPL license) and not platform dependent: you can use it in a web project or in a WinForms application, and, for sure, with Mono.

History

  • 19/12/2006: First article version.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
Olivier Carpentier is a french C#.Net Architect, Microsoft Certified Professional.

Software Expert at SQLi, french consulting company
http://www.sqli.com

Comments and Discussions

 
GeneralGreat work - but no button actions! Pin
wizofaus11-Feb-07 14:38
wizofaus11-Feb-07 14:38 
GeneralRe: Great work - but no button actions! Pin
Olivier Carpentier11-Feb-07 21:18
Olivier Carpentier11-Feb-07 21:18 
GeneralRe: Great work - but no button actions! Pin
wizofaus12-Feb-07 9:04
wizofaus12-Feb-07 9:04 
GeneralRe: Great work - but no button actions! Pin
SpaceWalker21-Apr-08 11:17
SpaceWalker21-Apr-08 11:17 
GeneralRe: Great work - but no button actions! Pin
wizofaus21-Apr-08 12:52
wizofaus21-Apr-08 12:52 
GeneralRe: Great work - but no button actions! Pin
SpaceWalker27-Apr-08 12:25
SpaceWalker27-Apr-08 12:25 
GeneralRe: Great work - but no button actions! Pin
wizofaus27-Apr-08 13:06
wizofaus27-Apr-08 13:06 
GeneralRe: Great work - but no button actions!(SwfDotNet increase version) Pin
Member 366988918-Feb-09 21:52
Member 366988918-Feb-09 21:52 
Hi,
How to increase flash version support of SwfDotNet.
Now when I try upload flash file version 8 then it gives error.
It support till 7.0.
Anyone can share the code?

Thanks in advance

Kumar Harsh
GeneralRe: Great work - but no button actions! Pin
streamingmedia15-Jul-09 16:11
streamingmedia15-Jul-09 16:11 
GeneralThanks Pin
Elias Bachaalany2-Jan-07 4:08
Elias Bachaalany2-Jan-07 4:08 
GeneralRe: Thanks Pin
Olivier Carpentier4-Jan-07 2:50
Olivier Carpentier4-Jan-07 2:50 
GeneralLooks promising! Pin
jalbitz26-Dec-06 5:16
jalbitz26-Dec-06 5:16 

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.