FlacReader + WavWriter

As a follow-up to my previous article on FLAC and encoding uncompressed audio, I have further developed the Wav2Flac library and added FLAC decoding to the WAVE container. Some key points of this aspect of the WavFlacTest library are:

  • Support for 16- and 24-bit audio streams
  • Support for virtually all FLAC channel mappings: mono, stereo, 5.1, 7.1, etc.
  • The resulting file is a bit-for-bit copy of the original audio stream

All source code and the compiled 32-bit FLAC library can be downloaded from here.

Known limitations

  • Due to the wave format used being 32-bit, uncompressed files greater than 2GB in size might not play in full in some players.
  • Even though FlacReader can receive metadata callbacks, the data is not interpreted. This can be further developed using the FLAC API documentation.

Inline Tweet Translator

Translated tweet from @katyperryOne thing that popped in my mind yesterday after having a conversation over twitter (admittedly, a service I had rarely used until recently), is that the more followers you have, the higher the odds you would have to use other languages in addition to a lingua franca. This ‘leaves out’ other friends who could have limited knowledge of foreign languages.

This is how the idea for the Tweet Balloon Translator was born. It’s a Greasemonkey script for Firefox, which uses the balloon/hover feature recently introduced in twitter plus the Google Translate service to translate tweets quickly and inline.

You can install the script from userscripts.org or the local copy here.

Development notes

The key phases I outlined for the script were as follows:

  1. Establish a working translation block of code using the Google Translate JSON API
  2. Research the possibilities of inserting a Translate link in such aspects of twitter as the profile page, direct messages, retweets. The Guest/logged out user scenario also had to be taken into account as twitter serves the pages in a different manner.
  3. Figure out a way to use the twitter internal API for the HoverCard balloon feature. This was probably the hardest of all three because of the way these are created and populated.
  4. Integrate 1 through 3 in a single script.

Needless to say, the script employs asynchronous requests to Google via the HTTPXMLRequest model so as to not break the UI thread, as well as exception handling.

Please feel free to try out, review, or contribute to the script at userscripts.org. I feel both international and English-speaking users could benefit from this by being able to communicate with more people on twitter, and understand international tweets.

Resizing a form while keeping aspect ratio is useful in many cases, like video playback or vector graphics. This way, the window can be resized while retaining the original ratio and avoiding the use of letterboxing or pillarboxing.

What’s needed is for the window function to be overriden (WndProc) and pre-process the target window rectangle used by the WM_SIZING message.

The new destination rectangle is calculated by taking into account the resizing handle and the window chrome size (title height, border width, etc.).

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_SIZING)
    {
        RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));

        int w = rc.Right - rc.Left - chromeWidth;
        int h = rc.Bottom - rc.Top - chromeHeight;

        switch (m.WParam.ToInt32()) // Resize handle
        {

           // …

        }

        Marshal.StructureToPtr(rc, m.LParam, true);
    }

    base.WndProc(ref m);
}

You can find the full C# source code here, including a test program. The aspect ratio and initial client size is set to 16:9.

Why lossless?

Lossless audio is used on various media, including studio masters, CD, DVD-Audio (via MLP) and Blu-ray (via Dolby TrueHD, which is technically a rebrand of and an extension to MLP, and DTS-HD Master Audio). All of these, when decoded, will result in a pulse-code modulated signal identical to the source, unlike the popular MP3 format. MP3 performs a quality-file size trade-off by discarding or reducing frequencies less audible to human hearing.

PCM by design uses a constant bitrate, which is proportional to the sample rate, bit depth and number of audio channels, which results in very large file sizes with the increasing of each parameter, and/or duration of the audio track.

Solutions such as FLAC, TrueHD and DTS-HD MA are used to losslessly compress the source audio so that the rest of the medium (for example, a Blu-ray disc) can be used for more audio tracks, higher-bandwidth video or extras.

Out of the aforementioned, only FLAC is free to use—both TrueHD and DTS-HD MA encoders and decoders have to be licensed.

The first part of the series will explore the processing of uncompressed audio data with the FLAC API in C#. In case you prefer to use Visual Basic .NET, you can use this online converter.

Continue reading ‘Encoding uncompressed audio with FLAC in C#’

ConsoleProgressBar

Command-line interface tools. We usually prefer to write these when we need a lightweight application to get work done.

Some operations can be lengthy, or we simply want to present the a visual indicator of progress to the user. For this purpose I usually update Console.Title for simplicity’s sake.

However, if the tool is intended for a more wide audience (IT professionals or advanced users) you would want a CLI progress bar.

ConsoleProgress is a static class. Usage is pretty much straight-forward:

  1. Call Reset to reset the progress bar’s state. This is optional if you wish to use the progress bar only once in your program.
  2. Call Update. You can pass a float  to indicate progress using a fraction (0.25 = 25%), or the current and maximum values (e.g. 17 of 100 items processed).
  • If the operation can be canceled, either because of an internal exception or by the user, you can set the Canceled  property to true  to update the console output.

The sample code also contains several test cases, which demonstrate successful and canceled operations. I have also used relevant colors depending on each result.

ConsoleProgressBar

2010

2010

I’d like to wish everyone a very happy and successful new year!

This month I will be posting useful code snippets and a series on high-definition audio.

I would like to focus on the now-popular Blu-ray disc format and decoding DTS-HD Master Audio streams to PCM and compressing with the open-source FLAC codec in C#. The next part will go native and explore the writing of a DirectShow filter with Managed C++, which will utilize the DtsHD library.

Време е за първия блог пост на български. Каква по-добра тема от Windows 7? Днес Microsoft направи Windows 7 RC – Release Candidate, достъпен за всички. Можете да научите повече и свалите своето копие от тук. RC означава, че тази версия е много близо до крайната, която се очаква наесен.

Инсталацията е бърза и отнема не повече от 20 минути, а единствената информация, която е неоходима да въведете е езика, който да се инсталира, на кой дял и евентуално сериен ключ за активация (но не е задължителен).

Нека разгледаме какво е ново и променено в Windows.

Работният плот

Лентата на задачите е първата промяна, която ще забележите. В Windows 7 Quick Launch и обичайният Taskbar са обединени.

Работният плот Internet Explorer с preview Jump List

Бутоните в тази лента се комбинират, а липсата на имената на всички програми пести пространство (можете и да намалите размера на иконите или да включите опцията за показване на имената). Например ако имате отворени 7 таба или прозорци на Internet Explorer ще има само една икона в лентата. За сметка на това смяната на прозорци става като преминете през бутоните и изберете желания прозорец. Също така има и приятна плаваща анимация за тези, които използват Aero.

Лентата на задачите в три възможни режима

Ако щракнете с десния бутон върху някоя от програмите в таскбара, ще изкочи един нов вид списък – Jump List. Там повечето от програмите представят списък с последно отворени папки, картини в Paint, документи на Word или Еxcel, или страници посетени в интернет.

Една малка, но полезна промяна – ако премествате, копирате или сваляте файлове от интернет, бутона на програмата показва прогреса на операцията. Така можете да продължите работата си и само с един поглед ще разберете кога е готова.

ТемиТемите в Windows “преобличат” работния плот и могат да сменят фона периодично. Sidebar от Windows Vista вече го няма, а притурките (gadgets) могат да се закрепят към всеки край на екрана.
Continue reading ‘Windows 7 – Какво ново?’

Microsoft Most Valuable ProfessionalJust a couple of days ago Microsoft MVP lead Alessandro Teglia announced the newly awarded and renewed Most Valuable Professionals for 2009 — I would like to congratulate all of them on their achievements. Rock on!

I am also very happy and proud to be given the award for Visual C# this year. It is my programming language of choice and in my opinion the .NET Framework will continue to be adopted by developers in 2009. I hope the MVP program will offer a lot of new doors and opportunities.

So what’s to come on my blog? I plan on writing mosly technical posts about the .NET Framework as a whole, and coding patterns in .NET languages. Visual Studio 2010 is coming near release and it is going to introduce some very interesting additions, which I will go through in the coming days.

I am frequent on the official Microsoft newsgroups (mostly .NET-related) and will be attending Microsoft Days ‘09 later this month. You can expect an essential coverage as well.

Last, but definitely not least, a big “Thanks” to Microsoft and a very good friend of mine, Christoffer Andersson, for all the support!

P.S. I am contemplating mirroring some or all of the articles in Bulgarian, my native language. Are there any Bulgarian readers out here?

GlassLib is a wrapper library for the Desktop Window Manager API and is to be used by developers which would like their applications to take advantage of .NET Framework and Windows Presentation Foundation in particular.

It can be used to control the Desktop Composition due to application requirements, create and reference Live Thumbnails of arbitrary windows, manipulate the Glass client area of windows and receive events which occur for them (Figure). Developers who target their applications for Far East users can also use the wrapper library to control the flow direction of controls and caption bar.

While the library wraps a big portion of the API exposed by DWM, the timing and performance counter part is to follow up shortly.

Documentation and a test application are provided. The usage of the wrapper library is pretty much straight-forward. Following is a list of several key facts:

  • Add a reference to the DwmWrapper.dll library to your project (from the Solution Explorer, select your project’s node, right click it and select Add Reference. From the new dialog box, browse the library file). Please note that the library is compiled against the .NET Framework 2.0 therefore it can only be used in projects compiled against it, or a newer version.
  • Include the GlassLib namespace so that the Dwm-related classes can be accessed more easily.
  • When used in a System.Windows.Window, override the OnSourceInitialized method and then set up the event handlers.
  • Per-window options can be set using the Dwm.Glass, Blur, Events, NonClientArea and Flip3D. This is available by using the indexer (default property) of these properties. The value passed to the indexer can be an IntPtr - handle to a window or a System.Windows.Media.Visual whose window handle will be manipulated. E.g:
    • In VB .NET: Dwm.Glass(Me).Enabled = False
    • In C# .NET: Dwm.Glass[this].Enabled = false;
      • Note: this and Me refer to the calling instance, which is a System.Windows.Window in the example.
  • The Dwm* structures have implicit operators. This allows for casting Windows Presentation Foundation Rect and Thickness implicitely to DwmRect and DwmMargins, respectively. For instance, the following expression will be valid:
    • Thickness foo = new Thickness(5, 30, 5, 20);
      // Assign foo to a Visual’s margin.
      Dwm.Glass[this].Margins = foo; // foo is implicitely casted to DwmMargins.

GlassLib Test Application GlassLib Test Application - Right-To-Left Layout

If you have any questions, suggestions or would like to report an issue, please feel free to use the Contact form.

Written in C# .NET. Binaries and the sources of a test application are available here; only binaries.

 

Following the first part of the Tweak DWM from your programs series, we are going to explore the actual usage of the Desktop Window Manager API in a Windows Forms-based program. The test application–included in the source package–also makes use of glassbarGlassBar, an extension to the existing control set.

Using GlassLib in your program

projectGlassLib is going to be main focus of this part of the series. It supersedes projectDwmWrapper by implementing a framework around glassbarGlassBar which can be used as a complement to your visually-rich forms. In order to use this library in your project, you have to do the following:

  1. Include a) a reference to the DLL in your project from Visual Studio: Project menu => Add reference, or b) the actual code files to your C# project (adding them as links (shortcuts) as opposed to copying them is more suitable if you wish include the files in multiple projects and/or wish to make changes to the code yourself).
  2. Remember that all of the functionality lies in the namespace_GlassLib namespace. You can use the using or Imports clause in the beginning of your C# or VB.NET code file, respectively, or the global imports if you code exclusively in VB.NET.

Exploring the GlassLib Test app

Let’s begin exploring the framework by opening the project file for projectGlassLibTest. Included in the GlassLib solution, it depends on the projectGlassLib project reference, which on its part has all the projectDwmWrapper code. Open the formfrmMain.cs file which is the form which is to be executed right at start up. As described in the first part, the first thing the class constructor public frmMain() should do is to set Dwm.ThrowExceptionTypes to DwmExceptionTypes.None in order to avoid any exceptions from being raised when DWM is not enabled or available on the OS, or if any function failed. The next thing the program does is to enable dragging from the Glass-extended area.

Dwm.Glass[this].DragExtendedArea = true; is useful if you want the extended area to act as the caption bar does, like in Windows Media Player. This is what the glassbarGlassBar toolbar does as well (more on this later in this part). toolbox Switch to Designer mode (View => Designer) and you can see the layout of the form: the usual Windows Forms buttons, combo and text boxes et cetera, but also glassbarGlassBar. To add the latter to your own forms, open the Toolbox (View => Toolbox) and drag it to your form (see figure on right). The toolbar will automatically dock to the bottom of it and extend Glass from this side of the form. You are free to dock it to the whole form (or container for that matter) or one of the other sides. Because DWM only supports Glass on top-level windows, in designer mode glassbarGlassBar falls back to UXTheme API in order to get the theme-specific background image or brush which is suitable for all non-Aero Glass themes such as Aero Basic, Luna (on Windows XP) or Windows Classic on any supported Windows version. On top of this, you can choose to write your own classGlassBarRenderer.

This feature provides two key benefits to your application’s design:

  • For Windows Vista systems and future OS with support for Glass: rich, seamless Glass UI
  • For Windows Vista systems where DWM is disabled or unavailable, and all previous Windows releases: seamless UI deriving from the appropriate Windows theme, including custom themes created with software such as WindowBlinds.

GlassBar

Managing the GlassBar items

Adding your items to GlassBar is quite easy. While in Design Mode, make sure that the Properties pane is visible (View menu => Properties Window to invoke it), select Items and expand the Collection Editor. You can add, remove and rearrange the items. For each one of them you can customize their:

property_thumb1Name Used in code only (does not appear in UI)
property_thumb1Enabled Enables/disables the item from the UI
property_thumb1Icon Preferably translucent PNG image 25×25 pixels in size
property_thumb1IsSeparator Denotes whether the item is a separator (its Icon will be disregarded)
property_thumb1Overlay Image, useful for ‘hover’ effects
property_thumb1Text Alternative text shown when the item is hovered
property_thumb1Visible Shows/hides the item

You can of course manage items programmatically using the property_thumb1Items property, for example adding one: Image img = Image.FromFile(“someFile.png”); GlassBarItem gbi = new GlassBarItem(“Sample Text” + i, img); glassBar.Items.Add(gbi); When the logic of your program requires an item be disabled or hidden, e.g. an unavailable feature, you can use property_thumb1Enabled or property_thumb1Visible to prevent users from clicking it.

Custom renderers

Internally GlassBar defines a standard renderer which on Windows Vista with Aero Glass enables draws on a translucent surface and otherwise falls back to the system-defined theme. If you wish to code a custom renderer for your needs, what you have to do is:

  1. Create a class deriving from (inheriting) from one of the following classes:
    • classGlassLib.Rendering.DefaultGlassBarRenderer if you wish to customize only specific parts of the default renderer (images, background etc)
    • classGlassLib.Rendering.GlassBarRenderer if you wish to build one from the ground up. This requires you to implement all of the methods and properties and is unlikely to be your choice.
  2. Decide which functions or images you would like to change. You can assign any image to property_thumb1MainPiece, RightSecondaryStates, AnimationStrip etc.
  3. The method_thumb1DrawBarBackground function is called every time the UI changes and needs to be redrawn. It is here where you can change most of the behavior of the default renderer and implement your own features.
  4. Assign an instance of your custom renderer to glassbarGlassBar
    • glassBar.Renderer = new CustomRenderer(); or to revert to default:
    • glassBar.Renderer = new GlassLib.Rendering.DefaultGlassBarRenderer();

The test app

There is a test program added to the package, project_thumb1GlassLibTest, whose code and compiled binary you can explore and experiment with GlassBar and DWM. If you have any comments, questions, wishes or just an opinion, I would be happy to hear it.




About

Stanimir Stoyanov is a programmer, Microsoft MVP, and Windows enthusiast. Read More...

Currently, he is administering AeroXperience and coding using Visual Studio 2008 on Windows 7.