Click here to Skip to main content
Click here to Skip to main content

Media files conversion using C#

By , 28 Jul 2005
 

Introduction

The GraphEdit utility, from the DirectShow SDK, is a popular tool to simulate the processing of media files on the Windows platform. Recently, DirectShowLib, an open-source .NET wrapper for DirectShow has been released. Version 1.0 of DirectShowLib wraps the most important interfaces and, already provides much more functionality than the interop assembly generated from the Quartz.dll. In this article, we'll present an application that builds filter graphs for the conversion of media files using C#. Hence, we'll show how to create applications in C# that provide some functionality that GraphEdit does.

Background

There are plenty of file formats for multimedia applications. The most popular ones are those in the MPEG family (MPEG-1/2, MPEG 4 (part 2 or 10)...), the Microsoft family (AVI, ASF, WMV,...), QuickTime family (QT, MOV,...) and RealMedia (RM, RAM,...). Each has its advantages and disadvantages. Moreover, some are covered by those silly little things called "software patents" (probably invented by fat, lazy middle managers in large corporations, who find it easier to dump work on their law department than actually developing products that their customers want ;-).

So for this application, I have decided to write a conversion utility that will convert many media files to the Windows Media Video (.wmv) format. Moreover, since Microsoft holds patents on the ASF format (from which .wmv is derived), I have code to convert to the open format initiative known as Matroska.

Using the code

This web site has many resources for using DirectShow from .NET. The ancestor of DirectShowLib was a project by .netmaster on this site. I have studied their code and you can look at them for things that I haven't explained in this article.

First, the command line to compile the application (provided in build.cmd and assuming that the C# compiler is accessible from the current path) refers to the DirectShowLib assembly. In the code, we start with:

using DirectShowLib;

Then, we use the following variables to build the filter graph:

// The main com object
FilterGraph fg = null;
// The graphbuilder interface ref
IGraphBuilder gb = null;
// The mediacontrol interface ref
IMediaControl mc = null;
// The mediaevent interface ref
IMediaEventEx me = null;

After some initial steps (common to all DirectShow applications in C#), we convert a media file to a .wmv file using the following code:

// here we use the asf writer to create wmv files
WMAsfWriter asf_filter = new WMAsfWriter();
IFileSinkFilter fs = (IFileSinkFilter)asf_filter;
        
hr = fs.SetFileName( fileName + ".wmv", null );
DsError.ThrowExceptionForHR( hr );

hr = gb.AddFilter( (IBaseFilter)asf_filter, "WM Asf Writer" );
DsError.ThrowExceptionForHR( hr );
        
hr = gb.RenderFile( fileName + fExt, null );
DsError.ThrowExceptionForHR( hr );

hr = mc.Run();          
DsError.ThrowExceptionForHR( hr );

This code creates a WMAsfWriter object, and accesses its IFileSinkFilter interface to set its file name. Then it adds the filter to the graph using the GraphBuilder interface method AddFilter. After this, we use "Intelligent Connect" (done through the call to RenderFile) to let the DirectShow runtime build the rest of the graph. Then, when we call the method Run on the MediaControl interface, we are actually writing the file because the renderer filter in this graph is a file writer.

Points of Interest

From my earlier comments, you probably guessed that I am not a big fan of software patents. After having written the code for the conversion to .wmv files, I learned that Microsoft has patents on the file format on which it is based. So I looked for alternatives, and I realized that this field is replete with those "silly little things". So I decided to add support for conversion to the Matroska file format which is "patent-free", as far as I know.

Matroska support

The code to build a filter graph that will write .mkv files is similar to the code for writing .wmv files. Except that we don't create a WMAsfWriter but we create a FileWriter object (and, again, access its IFileSinkFilter interface to set its name). Then we use the following to add the Matroska Mux filter:

// create an instance of the matroska multiplex filter and add it
// Matroska Mux Clsid = {1E1299A2-9D42-4F12-8791-D79E376F4143}
Guid guid = new Guid( "1E1299A2-9D42-4F12-8791-D79E376F4143" );
Type comtype = Type.GetTypeFromCLSID( guid );
IBaseFilter matroska_mux = (IBaseFilter)Activator.CreateInstance( comtype );

If you have installed support for Matroska to your system (download the codec pack from www.matroska.org if you don't consider codec packs "evil"), the CLSID for the Matroska Muxer will be included in your registry. Then you can create a type object and call Activator.CreateInstance to have an IBaseFilter object that can be added to the filter graph.

Using GraphBuilder.RenderFile will again try to build the rest of the graph from a source media file. This process doesn't always work as expected and you should consider the Matroska support as experimental and mainly used for illustrative purposes.

Limitations and known issues

I originally developed this application because I had some Real Media files that I wanted to convert to .wmv. I manually built the filter graph in the GraphEdit tool and rebuild it for every file. So I decided a little application that would do the same would be handy. Real Media files can be converted to Windows Media files without any problem if you have the Real Media Splitter installed on your system (with a Real Player or Real Alternative).

The Window Media file to Matroska file conversion seems to be working fairly well. But MPEG files don't convert to Matroska files with this application (and I didn't look into the problem). But you can convert MPEGs to WMVs and then convert it once more to a Matroska file. (This second conversion seems to hang on some files but the files are not corrupted and can be played in your favorite player. GraphEdit had the some difficulty on these files.) As mentioned, the Matroska support is experimental and mainly for illustrative purposes. So I don't promise that I'll support this functionality of the application.

Installing the codec pack for Matroska with its shell extension facility created problems on my system (and it seems to be a problem on other machines). But the default installation script doesn't include this functionality. Nevertheless, searching Google reveals that other people had problems after installing the Matroska codec pack on XP.

The timing on some Matroska files looks odd and I'll intent to look at this issue.

If the file is large, the conversion can take some time. I use the Task Manager application and check the CPU usage to find out when the conversion is over.

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

About the Author

daniel049
United States United States
Member
You can read my blog entries at:
http://wwww.informikon.com/blog/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionexceptionmembersileen_Mohammad13 Apr '12 - 4:50 
how to fix the error exception in this code ?
Questiondidn't work wellmemberMember 832343616 Oct '11 - 18:06 
I get two asf files on my windows xp computer. One can be played and the converted wmv file can be played ,too. But for the other asf file, neighter its self nor the wmv file can be played. The asf size is 1377KB, and the converted wmv file size is 92KB.
Generalhimembernid4may25 Jun '10 - 20:35 
this is very usefull
i want to convert avi or wmv video format to mpeg format.
please reply if u have any solution
thanks
GeneralVery usefulmemberCinni3 Dec '09 - 0:45 
Denial,
i must say, "great job", than you for sharing knowledge.
I was unaware of "DirectShowLib", and your article has helped me a lot.
 
Lead a few, Follow one....Love all, Hate none....

GeneralC# CODE FOR VEDIO CUTTER FEATURES........memberBabita Shivade2 Apr '09 - 3:15 
Hi friends,,,,,,,,,
 

I am working on c# .NET DESKTOP APPLICATION ...........
I want c# source code for vedio cutter working with best features such are ,play, start clip,stop clip, pause, save .........
plz reply
GeneralMatroska (mkv) is not a codec!memberQwertie29 Jan '09 - 9:08 
Your concern about patented video codecs is not alleviated by using mkv, since mkv is just a container format, not a codec!
 
Your code doesn't select any codec to use for the mkv conversion. My guess would be that DirectShow will most likely do a direct stream copy, i.e. it will use the same video codec in the mkv file that was used in the source file. I haven't tested that theory though. Your code also doesn't configure the wmv codec at all. I hate to be rude, but... do you have any idea what you're doing?
GeneralProprietary Codecmemberkicknit222 Dec '08 - 11:18 
I am trying to convert avi files with the GEOV codec to WMV. The GEOV codec is installed and I can play the video in WMP but when I use this program I get a COMException "Unspecified error" at mc.Run().
 
Can anyone help or is there a better way to do this?
GeneralError in Executionmemberapons17 Jul '08 - 3:01 
When I download the demo and try to convert an avi file to a wmv file I receive an error, the errors are:
 
Error converting to wma : Unspecified error for one avi and then
Error converting to wma: Exception from HRESULTS: 0xC00D0BB8
 
I am not sure why it does not work and what I am trying to do is exactly what is in the project convert avi to wmv.
 
Please I have been try to get this to work for a few days and have no clue what to do.
GeneralRe: Error in ExecutionmemberDisha43917 Jul '09 - 8:59 
Hi,
 
I too have the same issue while exuting the application. Could any one pls let me know, how to resolve this issue?
GeneralConvert wmv to wavmemberWebrat24 Feb '08 - 16:02 
How to convert wmv to wav?
I tried to build a graph, but it didn't get it to work.
 
That was my idea: WMAsfReader -> WMAudio Decoder DMO -> WAV Dest -> FileWriter
 
Here is a screenshot of the graph in graphedit i made: Screenshot[^]
 
I'm not able to create the WMAudio Decoder DMO and add it to the graph.
 
Please help me creating and adding the WMAudio Decoder DMO
 
Greetings
Webrat
QuestionRe: Convert wmv to wavmemberWebrat25 Feb '08 - 1:41 
oh... i forgot to say:
The problem is the C#-code, not the visual graph (with graphedit) Wink | ;)
 
Greetings
Webrat
GeneralRe: Convert wmv to wavmemberdaniel04925 Feb '08 - 7:06 
You might be able to use the wmv/wma parser from http://www.gdcl.co.uk/downloads.htm[]">.
 
I checked your graph and using the above filter seems to work for me.
 
-daniel
GeneralRealVideo 10mvpJohn Simmons / outlaw programmer10 Jan '08 - 11:10 
The RenderFile call throws the following exception when trying to convert RealVideo 10 files.
 
"Cannot playback file. The Format is not supported."
 
I've installed RealPlayer 11 Gold and I'm using the latest version of DirectShowLib. How can I resolve this issue?
 

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

GeneralRe: RealVideo 10memberdaniel04911 Jan '08 - 3:58 
Since you can't play RealMedia files with WMP, it is unlikely that you can use this code to treat these files.
 
Unfortunately, I am not aware of other tools, except those provide by Real, that can handle the recent formats from this company. Google is your friend...
GeneralWMV Profilesmemberizmoto1 Jan '08 - 23:06 
I am converting AVI to WMV and would like to use the WMProfile_V80_700PALVideo profile on the converted WMVs. I am using the sample application provided here. Please give direction.
 
void izmoto(char* szKwazi);

GeneralRe: WMV Profilesmemberdaniel0492 Jan '08 - 7:38 
Hi,
 
I've done something similar in the past with the following code:
 
Add this to the conversion method
IConfigAsfWriter icw = (IConfigAsfWriter)asf_filter;
icw.ConfigureFilterUsingProfileGuid( ref profileGuid );
 
where your profile guid is the following (i've googled it)
EC298949-639B-45e2-96FD-4AB32D5919C2
 
I've used the following idl to generate the typelib
for the IConfigAsfWriter method:
import "dshowasf.idl";
[
uuid(857FF9C7-4397-42d9-8216-FB89940119C5),
helpstring("Asf type library")
]
library ToWavTypeLib
{
importlib("STDOLE2.TLB");
 
interface IConfigAsfWriter;
};
 
I believe it was working well.
GeneralProblems with demo codememberAnil KumarThanga2 Oct '07 - 21:57 
Dear Sir,
 
I am new to this videos world. I am working for web application in c#.net.We have a fecility to upload videos. My requiremnet is to convert all the videos to .WMV format So that I can play them through Windows Media Player. I am trying to achieve this through DirectShowLib.
 
I have got source code and demo that you have posted in code project, When I tried to run the demo I am getting exceptions like "UNSPECIFIED ERROR" for .RAM formats and "CAN NOT PLAY BACK THE FILE. THE FORMAT IS NOT SUPPORTED." for 3gp formats. In both the cases I tried to convert to WMV format.

Do I need any codecs to be installed on my machine to make the demo application working? Or what are the softwares(requirements) that I should have to make the demo application working?( I am not aware of codecs.. if at all I have to download something, Please provide the link).
 

Please help me out...
thanks in advance.
 
Anil
GeneralRe: Problems with demo codememberdaniel0496 Oct '07 - 11:05 
If you can play the file in WMP, then there is a good chance that you'll be able to translate it using this app.
If not, then it's unlikely this app will be useful.
 
Real Media files can't be played in WMP therefore you won't be able to use this app for these files.
 
I'm not aware of utilities (or codecs) that can handle the most recent versions of Real Media (except for what is provided by that company).
GeneralRe: Problems with demo codemvpJohn Simmons / outlaw programmer9 Jan '08 - 5:41 
Is RealMedia the same this as RealVideo?
 

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

QuestionVOB to GBM+GBS [modified]membera stupid person27 Jul '07 - 15:22 
How do I convert VOB to GBM+GBS? The official converter does not work.
 
[edit] I can get it to convert in GraphEdit, but the video is too fast. I tested using the converter software's GBM player feature, not the GBA player. GBM+GBS = GameBoy Movie+GameBoy Sound. It is used by SuperCard, GBAMP, and others?
 

 
-- modified at 0:47 Friday 3rd August, 2007
GeneralTranscoding to Ogg Theora on Windowsmemberdaniel04920 Mar '07 - 8:06 
Hello everyone,
 
I have modified this application in order to transcode video files to the patent-free Ogg Theora format.
 
You can download this application from:
http://www.a2ii.com/tech/directx/TransTheora.zip[^]
 
-daniel
QuestionRe: Transcoding to Ogg Theora on WindowsmemberBasel Nimer20 Jun '07 - 4:53 
am sorry, i am new to this, i am getting an error about that the guid doesn't exist, should i install something before running this sample?
 
Thanks

 
(2B)||(!2B)

AnswerRe: Transcoding to Ogg Theora on Windowsmemberdaniel04920 Jun '07 - 6:51 
Did you download the DS Ogg filters?
 
From the "readme.txt" file:
You need to install the DirectShow filters
for Ogg from:
http://www.illiminable.com/ogg/downloads.html
in order to use this application.
 
-daniel
GeneralRe: Transcoding to Ogg Theora on Windows - Updated LinkmemberDavid Ward, MIT30 Oct '09 - 18:27 
In case anyone else wanted to download this, the previous link is dead. Daniel's application has been moved here.
QuestionHow to convert avi file to .movmemberdaydream321119 Jan '07 - 18:15 
Dear sir,
I wrote this question in hope of you can show me how to convert avi file to mov file (Step by step).
I hope that I will receive your answer as soon as possible.
Thank you in advance!
 
Missing You

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 29 Jul 2005
Article Copyright 2005 by daniel049
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid