Monday, December 7, 2009

WriteableBitmapEx - WriteableBitmap extensions now on CodePlex

I finally kept my promise and put the WriteableBitmap extensions up on CodePlex. This step was long overdue, but when the Silverlight 4 beta was released I couldn't resist and had to play with the new webcam API first (though I'm not finished yet).

The WriteableBitmapEx library project description:
The WriteableBitmapEx library is a collection of extension methods for Silverlight's WriteableBitmap. The WriteableBitmap class that was added in Silverlight 3, allows the direct manipulation of a bitmap and could be used to generate fast procedural images by drawing directly to a bitmap. The WriteableBitmap API is very minimalistic and there's only the raw Pixels array for such operations. The WriteableBitmapEx library tries to compensate that with extensions methods that are easy to use like built in methods. The library extends the WriteableBitmap class with elementary and fast (2D drawing) functionality, supporting common shapes like point, line, ellipse, polyline, quad, rectangle, triangle. Conversion methods and functions to combine WriteableBitmaps (Blitting) are part of it too.
Roots
The WriteableBitmapEx library has its origin in several blog posts:
Additional work
I recreated the whole Visual Studio 2008 solutions, changed the namespaces, headers, added comments and cleaned up the code base and samples. I also grouped the extension methods into different CS files with a partial class. It is now possible to include just a few methods by using the specific source CS files directly or all extension methods through the built library assembly.

License
The WriteableBitmapEx library is released as open source under the Microsoft Public License (Ms-PL) license. The Ms-PL license allows the use of the library without affecting the license of the user, thus making it also easily usable for commercial projects. On the other hand the weak copyleft characteristic ensures that changes on the source have to be committed back and that the library or parts of it always be free and never become closed source.

Touch it, Buy it, Use it, Break it, Fix it, Trash it, Change it, (Mail) - Upgrade it, ...
The WriteableBitmapEx CodePlex project site lives here. You might also want to see the Issue Tracker for a list of features that will be added in the future or to add your own. If you have any comments, questions, suggestions or want to see your name in the Credits list, don't hesitate and write a comment, use the Issue Tracker on the CodePlex site or contact me via any other media.
Have fun and let me know it if you do some cool stuff with it.

Thursday, December 3, 2009

Silverlight 4 Augmented Reality Proof Of Concept

Please goto: World# - Real Time 3D Augmented Reality with Silverlight. Such demos are now easily possible with the open source SLARToolkit.

In this short blog post I want to present a demo I've actually made last week. Unfortunately I had no time to work on it since then. This demo is a proof of concept for doing Augmented Reality with Silverlight 4 and the built-in webcam API.
I use the open source Augmented Reality library NyARToolkitCS and implemented the necessary interfaces to make it work with Silverlight. The NyARToolkitCS library is a completely managed version of the well known ARToolkit.

Video
I've recorded a short video with my iPhone 3GS. The video was recorded at night and it's no secret that the iPhone camera is not the best, but I think it's good enough to see how the marker is tracked and the Silverlight logo moves with it.


Background music is "You have something in your scowl" by Henrik José / Bliss.


To be continued
The first results are quite good and the demo runs smoothly at 60-70 fps on a dual core machine utilizing both cores. I will continue my work on this project and provide more details, samples and of course source code.
Stay tuned...

Monday, November 30, 2009

Convert, Encode And Decode Silverlight WriteableBitmap Data

In the comments of my Silverlight 4 EdgeCam Shots blog post "marcb" asked me how to convert the WriteableBitmap to a byte array to save the snapshot in a database.
I thought the answer might be also useful for others. Furthermore I will provide ready to use code for JPEG encoding and decoding of the WriteableBitmap.





Byte array conversion

Copy WriteableBitmap to ARGB byte array
public static byte[] ToByteArray(this WriteableBitmap bmp)
{
   int[] p = bmp.Pixels;
   int len = p.Length * 4;
   byte[] result = new byte[len]; // ARGB
   Buffer.BlockCopy(p, 0, result, 0, len);
   return result;
}

Copy ARGB byte array into WriteableBitmap
public static void FromByteArray(this WriteableBitmap bmp, byte[] buffer)
{
   Buffer.BlockCopy(buffer, 0, bmp.Pixels, 0, buffer.Length);
}

Usage
// Render UIElement into WriteableBitmap
WriteableBitmap bmp = new WriteableBitmap(UIElement, null);

// Copy WriteableBitmap.Pixels into byte array (format ARGB)
byte[] buffer = bmp.ToByteArray();


// Create a new WriteableBitmap with the size of the original image
WriteableBitmap bmp = new WriteableBitmap(width, height);

// Fill WriteableBitmap from byte array (format ARGB)
bmp.FromByteArray(buffer);

I will include the two methods in my WriteableBitmap extensions that I'm going to put up on Codeplex soon.


JPEG encoding and decoding
If you want to store many images or transport them over a network the needed storage size could quickly become a big problem. For example an image with the size 512 x 512 needs 1 Megabyte storage space and a 1024 x 768 image even 3 MB. A solution could be image compression using JPEG encoding and decoding. To accomplish this I've used the open source FJCore JPEG library which is distributed under the MIT License and works nicely with Silverlight.

Encode WriteableBitmap as JPEG stream
public static void EncodeJpeg(WriteableBitmap bmp, Stream destinationStream)
{
   // Init buffer in FluxJpeg format
   int w = bmp.PixelWidth;
   int h = bmp.PixelHeight;
   int[] p = bmp.Pixels;
   byte[][,] pixelsForJpeg = new byte[3][,]; // RGB colors
   pixelsForJpeg[0] = new byte[w, h];
   pixelsForJpeg[1] = new byte[w, h];
   pixelsForJpeg[2] = new byte[w, h];

   // Copy WriteableBitmap data into buffer for FluxJpeg
   int i = 0;
   for (int y = 0; y < h; y++)
   {
      for (int x = 0; x < w; x++)
      {
         int color = p[i++];
         pixelsForJpeg[0][x, y] = (byte)(color >> 16); // R
         pixelsForJpeg[1][x, y] = (byte)(color >> 8);  // G
         pixelsForJpeg[2][x, y] = (byte)(color);       // B
      }
   }

   // Encode Image as JPEG using the FluxJpeg library
   // and write to destination stream
   ColorModel cm = new ColorModel { colorspace = ColorSpace.RGB };
   FluxJpeg.Core.Image jpegImage = new FluxJpeg.Core.Image(cm, pixelsForJpeg);
   JpegEncoder encoder = new JpegEncoder(jpegImage, 95, destinationStream);
   encoder.Encode();
}

Decode WriteableBitmap from JPEG stream
public static WriteableBitmap DecodeJpeg(Stream sourceStream)
{
   // Decode JPEG from stream
   var decoder = new FluxJpeg.Core.Decoder.JpegDecoder(sourceStream);
   var jpegDecoded = decoder.Decode();
   var img = jpegDecoded.Image;
   img.ChangeColorSpace(ColorSpace.RGB);

   // Init Buffer
   int w = img.Width;
   int h = img.Height;
   var result = new WriteableBitmap(w, h);
   int[] p = result.Pixels;
   byte[][,] pixelsFromJpeg = img.Raster;

   // Copy FluxJpeg buffer into WriteableBitmap
   int i = 0;
   for (int y = 0; y < h; y++)
   {
      for (int x = 0; x < w; x++)
      {
         p[i++] = (0xFF << 24)                    // A
                | (pixelsFromJpeg[0][x, y] << 16) // R
                | (pixelsFromJpeg[1][x, y] << 8)  // G
                |  pixelsFromJpeg[2][x, y];       // B
      }
   }

   return result;
}

Usage
// Save rendered UIElement as JPEG file
private void BtnSaveFile_Click(object sender, RoutedEventArgs e)
{   
   if (saveFileDlg.ShowDialog().Value)
   {
      using (Stream dstStream = saveFileDlg.OpenFile())
      {
         // Render to WriteableBitmap
         WriteableBitmap bmp = new WriteableBitmap(UIElement, null);
         
         // Encode JPEG and write to FileStream
         EncodeJpeg(bmp, dstStream);
      }
   }
}


// Open JPEG file and read into a WriteableBitmap
private void BtnLoadFile_Click(object sender, RoutedEventArgs e)
{   
   if (openFileDialog.ShowDialog().Value)
   {
      using (System.IO.Stream srcStream = openFileDialog.File.OpenRead())
      {         
         // Read JPEG file and decode it
         WriteableBitmap bmp = DecodeJpeg(srcStream);
      }
   }
}

Keep in mind that the standard JPEG format doesn't support alpha values (transparency) and that the compression is lossy. So don't encode and decode images subsequently with JPEG.
It is also possible to use the built-in Silverlight class BitmapSource and its SetSource method to decode an JPEG stream.
public static WriteableBitmap DecodeJpegWithBitmapSource(Stream sourceStream)
{
   // Decode JPEG from stream
   var bitmapSource = new BitmapSource();
   bitmapSource.SetSource(sourceStream);
   return new WriteableBitmap(bitmapSource);
}

Source code
Check out my Codeplex project WriteableBitmapEx for an up to date version of the byte array conversion methods.

Monday, November 23, 2009

EdgeCam Shots - Saving Silverlight 4 Webcam Snapshots to JPEG

In my last blog post I have covered the new Silverlight 4 Webcam API and provided a demo that used my edge detection pixel shader to create a nice real time webcam effect. In this post I make an extended version available which can save webcam snapshots as JPEG files and I also discuss some limitations of the webcam API's built-in CaptureSource.AsyncCaptureImage snapshot method. Furthermore I will give some ideas on how to build a Silverlight 4 video chat / conference application on top of the provided JPEG capturing and encoding code.


Live
To view the application you need to install the Silverlight 4 runtime. It's available for Windows and Mac.



The Webcam capturing could be started and stopped with the "Start Capture" Button. If you press it for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the new "Webcam / Mic" tab to set them.
Press the "Save Snapshot" Button to take a snapshot and save it to a JPEG file on your harddisk.
The threshold of the edge detection can be changed using the Slider and the "Bypass" Checkbox allows you to disable the shader.

How it works
The base Silverlight 4 webcam usage code was covered in my last blog post.

The new eventhandler for the "Save Snapshot" button:
private void BtnSnapshot_Click(object sender, RoutedEventArgs e)
{
   if (saveFileDlg.ShowDialog().Value)
   {
      using (Stream dstStream = saveFileDlg.OpenFile())
      {
         SaveSnapshot(dstStream);
      }
   }
}
The code is pretty obvious: A SaveFileDialog is shown and if the user enters a file name and hits OK, a stream to the file will be opened and passed to the SaveSnapshot method. There's only one think to keep in mind when using the SaveFileDialog.ShowDialog() method, it can only be called from user-initiated code like an event handler, otherwise a SecurityException is thrown.

The SaveSnapshot method including comments:
// Render Rectangle manually into WriteableBitmap
WriteableBitmap bmp = new WriteableBitmap(ViewportHost, null);

// Init buffer in FluxJpeg format
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int[] p = bmp.Pixels;
byte[][,] pixelsForJpeg = new byte[3][,]; // RGB colors
pixelsForJpeg[0] = new byte[w, h];
pixelsForJpeg[1] = new byte[w, h];
pixelsForJpeg[2] = new byte[w, h];

// Copy WriteableBitmap data into buffer for FluxJpeg
int i = 0;
for (int y = 0; y < h; y++)
{
   for (int x = 0; x < w; x++)
   {
      int color = p[i++];
      pixelsForJpeg[0][x, y] = (byte)(color >> 16); // R
      pixelsForJpeg[1][x, y] = (byte)(color >> 8);  // G
      pixelsForJpeg[2][x, y] = (byte)(color);       // B
   }
}

//Encode Image as JPEG
var colModel = new ColorModel { colorspace = ColorSpace.RGB };
var jpegImage = new FluxJpeg.Core.Image(colModel, pixelsForJpeg);
var encoder = new JpegEncoder(jpegImage, 95, dstStream);
encoder.Encode();
The Rectangle's surrounding Grid "ViewportHost" is rendered into a WriteableBitmap and the WriteableBitmap's Pixels are copied into another buffer with a different format. The rendered image is then written as a JPEG encoded stream using the open source FJCore library which is distributed under the MIT License. I've found some code at Stackoverflow on how to use the library in combination with the WriteableBitmap, but I modified / shortened it.
See my post on how to Convert, Encode And Decode Silverlight WriteableBitmap Data if you are interested in more WriteableBitmap conversion and JPEG encoding code.

Why not CaptureSource.AsyncCaptureImage?
You might be wondering why I haven't used the Silverlight 4 webcam API's built-in AsyncCaptureImage snapshot method of the CaptureSource class.
  1. The AsyncCaptureImage method grabs a frame directly from the device and therefore any effects like the edge detection pixel shader won't be visible in the rendered image.
  2. It only works if the CaptureSource was started, so the user can't save the visible image when the capturing was stopped. See the MSDN for details.
Please keep in mind that the first beta version of Silverlight 4 was used for this blog post and that some things will be changed in subsequent releases.

Where to go from here
The code in the SaveSnapshot method could be optimized and also multithreaded. The rendering should run in it's own thread. The encoding in a separate thread too and the network transport also. This approach would utilize modern quad core CPUs. After that it might be a good starting point for a video chat / conferencing application that continuously renders JPEGs and transports them between Silverlight clients. This technique is similar to the M-JPEG video format that also uses separately compressed JPEGs.
To make this idea usable for a Silverlight video chat, only the rendering, the JPEG encoder and the transfer method  need to be fast enough for real time streaming.
Please leave a comment what you think about it.

Source code
Download the Visual Studio 2010 solution here.

Update 03-20-2010
Updated to the Silverlight 4 release candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.

Friday, November 20, 2009

EdgeCam - Silverlight 4 Webcam & Edge Detection Shader

Only 4 months after Silverlight 3 RTM came out Microsoft released the first beta version of Silverlight 4 on 11-18-2009 at the PDC. The new features are just awesome and many of them were requested by the community. Tim Heuer's great blog post covers all the new goodies in detail and provides videos and source code for most of them.
One of my favorite new features is the webcam and microphone support and I've coded a small demo that uses the new Silverlight 4 CaptureSource class and applied my edge detection pixel shader to it to create a cool real time webcam effect.

Live
To view the application you need to install the Silverlight 4 runtime. It's available for Windows and Mac. You can also watch a video below.



The Webcam capturing could be started and stopped with the Button in the middle. If you press it for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the new "Webcam / Mic" tab to set them.
The threshold of the edge detection can be changed using the Slider and the "Bypass" Checkbox allows you to disable the shader.

Video
I've recorded a short video with my iPhone 3GS that shows the demo running on my Samsung NC 10 Atom Netbook. The built-in webcam is not very good and the video was recorded at night, but I think it's good enough to see how the effect looks.


How it works
The new Silverlight 4 webcam and microphone API is pretty easy to use:
// Init capture devices
captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

// Create video brush that preserves the aspect ratio and fill a Rectangle with it
VideoBrush videoBrush = new VideoBrush();
videoBrush.Stretch = Stretch.Uniform;
videoBrush.SetSource(captureSource);
Viewport.Fill = videoBrush;

// Ask user for permission
if (CaptureDeviceConfiguration.AllowedDeviceAccess
|| CaptureDeviceConfiguration.RequestDeviceAccess())
{
   captureSource.Start();
}
The edge detection pixel shader is applied to the "Viewport" Rectangle in the XAML. For a more intuitive behavior I've also attached a negative ScaleTransform to flip the x axis of the Rectangle. Otherwise the webcam output would be mirror-reversed by default.

Source code
The Visual Studio 2010 solution including the edge detection shader is available for download.

Update 11-23-2009
Make sure to read the follow up blog post EdgeCam Shots - Saving Silverlight 4 Webcam Snapshots to JPEG

Update 03-20-2010
Updated to the Silverlight 4 release candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.