Latest Tweet:
  • Loading...

This is a post I've been looking forward to write for quite some time, but I've just been to busy with work, CodeCampOz and REMIX to get around to do it… At the MVP Summit in Seattle some weeks back I had dinner with a group of friends, including fellow RD and co-worker Sondre Bjellås, and long time IRC-friend Wilco Bauwer (now working at Microsoft). Like when ever a group of programmers get together the talk soon was about Silverlight, C# and programming an general. We started discussing Silverlight and what features we would love to se in future versions. One of the things Sondre felt was missing is support for microphone and webcam. I don't know why Sondre think this is a big deal (but he DO read Love and Sex with robots… btw, Sondre, you should write a book review!). Wilco have worked on the HTML-bridge in Silverlight, so we started talking if it might be possible to "cheat" basic webcam support by bridging Silverlight and Flash. Without knowing the details we all agreed that it was probably possible to do.

When I got back from Seattle I started doing some initial research, like learning how to program against the webcam in Flash, what kind of HTML-bridging  capabilities you got and so on. A video tutorial titled "Webcams, PNG and AIR", combined with a blog post titled "Use JavaScript to Take a Screenshot of a Flash movie", gave me all the pieces to build webcam support for Silverlight (using Flash). So I asked my self: "What would MacGyver do", and decided to glue everything together into a proof-of-concept of webcam support in Silverlight 2.

The video tutorial covers the basics of how to create a camera object, attach it to a video and grab a video frame as a BitmapData object. It also covers how to use the as3core library, a set of open source extensions to ActionScript3, which includes a PNG-encoder class. The PNGEncoder encodes a BitmapData object into a ByteArray. Once I had the ByteArray I needed a way to pass it back to the browser. Since the set of types you can marshal between ActionScript and the browser (at least to my knowledge) is limited, I figured a Base64 encoded string would be the way to go. The blog post about taking screenshots used this technique to pass an image from Flash to JavaScript. It also covered how to expose ActionScript functions to JavaScript using the ExternalInterface APIs.

Once I had the Base64 encoded PNG image in JavaScript I could simply return it back to Silverlight, which then would use the Convert.FromBase64String method to create a byte array. With the image stored in a byte array I could simply load it into a MemoryStream, and then set the MemoryStream as the source of a BitmapImage object.  I'll let MacGyver show you how it all comes together:

MacGyverUML

It literally didn't take more than 20 lines of ActionScript, 5 lines of JavaScript and 5 lines of C# to get a single frame from my webcam onto a Silverlight image control.  This first piece of code is the ActionScript needed to start the webcam, capture a frame, set the mode and expose two functions to the browser:

WebcamActionscript

The next part is the JavaScript needed to grab the object/elem tag containing the Flash player, and calling the ActionScript functions to grab a snapshot from the webcam. The Base64 string is just returned from the function, as this function is being called from C#:

WebcamJavascript

The final part is the C# code using the HTML bridge to invoke the JavaScript function, grab the Base64 string, decode it, and then load the PNG image:

WebcamCSharp

Using the basic webcam integration I created two sample applications. The first one is a "performance test" to see how many frames per second I'm able to transmit to Silverlight. Since I'm not able to pas the raw stream from the camera, and have to PNG encode each frame, it's all CPU bound. The application uses a timer, which will grab a frame and measure the time it takes. Once it got the frame it will adjust the interval of the timer to the amount of time spent on the previous frame + 50 milliseconds (to give the UI thread some room to handle input events etc). I was able to get roughly 12fps 180x140, but on higher resolutions it starts to get sluggish. Also note that when using all the CPU power to capture frames you don't have CPU left to do Silverlight animations etc, so doing "live" video is really something you don't want to do. Click the image to check out the sample:

WebcamLiveVideo

The second sample is a Silverlight "Photo Booth" application, with out any of the cool features of the real Apple Photo Booth app. The interesting part about this sample is how I overlay the Flash container on top of Silverlight. This way my Silverlight application don't need to use CPU power to pre-view the video, and I only grab photos when the user clicks the button. Each image is also added to the thumbnail control, which I re-used from my YouCard demo. Click the image to check out the sample:

WebcamPhotobooth

I've made the code available for everyone to play with, including the Flash webcam wrapper. In order to build the Flash app you need Adobe Flash CS3. If you don't have Adobe Flash CS3 you can still build the app in Visual Studio and use the prebuilt WebcamWrapper.swf file. The code is not optimized in any way, and probably contains some bugs. But, this initial post is meant as a proof-of-concept, and I'll probably revisit this topic later.

And to summarize: THIS is how MacGyver would have built webcam support for Silverlight 2!

Tuesday, May 27, 2008 4:55:52 PM (W. Europe Daylight Time, UTC+02:00)
Quite cool indeed. This must be the digital equivalent of swivel chair integration.
Wednesday, May 28, 2008 1:41:36 AM (W. Europe Daylight Time, UTC+02:00)
Nice workaround mate! Finally we can have a webcam support on SilverLight through Flash... Well done. =)
Wednesday, May 28, 2008 3:53:00 AM (W. Europe Daylight Time, UTC+02:00)
Haha! That's just spot on Anders - This is Silverlight doing Ctrl+C Ctrl+V using JavaScript ;)

Diamz: Congrats on winning Imagine Cup AU, I checked out your blog, and those screens looks awesome. I'll drop you a comment on your post when I've read the entire thing. Great work!
Thursday, May 29, 2008 10:16:05 AM (W. Europe Daylight Time, UTC+02:00)
Haha, a workaround MacGyver would be proud of for sure :)
Thursday, May 29, 2008 12:31:56 PM (W. Europe Daylight Time, UTC+02:00)
Just plain cool mate! Now I'm thinking of ways to top your sample ... hmmm !
Jose Fajardo
Thursday, May 29, 2008 2:52:17 PM (W. Europe Daylight Time, UTC+02:00)
Fredrik: Glad you liked it ;)

Jose: Thanks mate! Looking forward to se what kind of cool Silverlight stuff you could come up with using the webcam. Have a new sample comming soon (a simple puzzle game) - Nothing "fancy", at least a little bit more usefull... But yeah, plenty of oppertunity.

Joe stegman has a PNG Encoder - One idea would be to create a PNG Decoder and load the image back into an EditableImage (that's the name of the class you use to generate bitmaps in his PNG/Dynamic Bitmap sample), and then to some effects etc.

Joes post on dynamic image generation in Silverlight can be found at: http://blogs.msdn.com/jstegman/archive/2008/04/21/dynamic-image-generation-in-silverlight.aspx

Saturday, May 31, 2008 9:30:15 AM (W. Europe Daylight Time, UTC+02:00)
Haha, du e MacGyver og pappa e Indiana Jones? :D Kan ikke si jeg orka å lese artikkelen, men artig greie... :)
Hilde Follesø
Sunday, June 29, 2008 5:04:53 PM (W. Europe Daylight Time, UTC+02:00)
Great. So I must search for flash samples to integrate a live streaming webcam on my website...
Monday, June 30, 2008 1:13:10 AM (W. Europe Daylight Time, UTC+02:00)
victorantos: Yes, if you want to build a rich internet application accessing the local web cam you would have to look up Flash examples. If you want to show a video stream on your page you can do that as long as the stream is encoded in a format Silverlight can show. Expression Media Encoder supports real time web cam encoding, and if you have a streaming server you can use that server to stream the video to your users using Silverlight.

If you want to capture a few stills for some kind of local processing, then you could use this technique.

Cheers,
Jonas
Tuesday, July 01, 2008 4:03:04 PM (W. Europe Daylight Time, UTC+02:00)
Congratulations, but ..... silverlight is considered as the future substitute of Flash technology and it has not support for webcam and microphone....:|
I hope ms 'll do something about this missing thing.
Why do you use png format ? I think it should be better jpg or jpg2000 :) ...
Bye
evs
Wednesday, July 02, 2008 4:56:21 AM (W. Europe Daylight Time, UTC+02:00)
Hi evs,

I consider Silverlight as an alternative to Flash, not a substitute. There are tons of Flash developers and designers out there, the install base is amazing (99.9% of internet connected computers in the US), and Adobe is continuing to innovate on the platform.

That being said Silverlight is a great alternative and competitor that will pick up the fight with Flash for the rich internet application space. After working with it for some time I absolutely sure Silverlight is going to be big in the years to come. The fact that you can run .NET in the browser, and write in both static (C#) and dynamic languages (Python/Ruby) is huge.

But back to your question: No, there is no client side access to webcam and microphone in Silverlight 2.0. It's the second revision of the framework, and the key improvements where on .NET, languages, core features and a UI component framework. Features like webcam and microphone will come in the future if the users request it.

As for the image format I could probably picked JPG. I'll give it a go and see if it affect performance in any way (I'm quite sure the AC3CoreLib supports it).

Chers,
Jonas
Monday, July 14, 2008 2:16:17 PM (W. Europe Daylight Time, UTC+02:00)
Could you please update your samples to Silverlight 2 Beta2?
It's very interesting!
Tuesday, July 15, 2008 12:34:19 AM (W. Europe Daylight Time, UTC+02:00)
Mikhali: Sure will. Have allready ported the code, as well as added an additional sample. Will try to post it as soon as possible. Glad you find the post interesting!
Monday, August 11, 2008 3:37:01 PM (W. Europe Daylight Time, UTC+02:00)
Any news about the updated code for Silverlight beta 2? :)
Adriano
Saturday, August 16, 2008 12:23:23 PM (W. Europe Daylight Time, UTC+02:00)
I have now updated the code and added a new sample application. Check out http://jonas.follesoe.no/WebcamInSilverlight2NdashSlidingPuzzleGame.aspx.

Cheers,
Jonas
Friday, November 14, 2008 3:45:30 PM (W. Europe Standard Time, UTC+01:00)
Thanks a lot! You save me a lot of time, nice job.
Cheers
Vlad
Vlad
Friday, November 21, 2008 5:08:17 AM (W. Europe Standard Time, UTC+01:00)
HI Jonas,

Is it possible to record this stream flash into movie format
PAE
Sunday, November 23, 2008 3:38:41 PM (W. Europe Standard Time, UTC+01:00)
thanx so much. It is excellent sample. But i have a problem i can not open the project WebCamPOC. I have visual studio 2008 professional version but it says project type is not supported by this installation. Please help me about the requirements for this project
Monday, November 24, 2008 12:06:00 AM (W. Europe Standard Time, UTC+01:00)
@PAE - I'm not sure what you mean? You would not be able to use this technique to save the web cam stream to a movie format. To do that you would need some kind of encoder.

@Fatih - Have you installed the Silverlight Tools for Visual Studio 2008? Since this is a Silverlight project you need to install some additional add-ins to Visual Studio to build and run the project. You can find the details on how to get started with Silverlight at http://silverlight.net/GetStarted/. If you already have the Silverlight Tools for Visual Studio 2008 installed it could be that the sample app hasn't been updated to the released version of Silverlight (could still be targeting the beta). Let me know if you have the tools installed, but still is experiencing this problem.
Friday, November 28, 2008 6:01:30 AM (W. Europe Standard Time, UTC+01:00)
Hi Jonas

What i m going to do is , i try to capture webcam in to movie format
Is it possible to do it?

Thanxxxx
PAE
Friday, November 28, 2008 7:07:53 AM (W. Europe Standard Time, UTC+01:00)
PAE: You can record videos from the Flash web cam, but not using this technique. This one is all about showing Flash<->Silverlight interop.

Try googeling for Flash Media Server and Flash Web Cam Capture for more information.

- Jonas
Sunday, January 25, 2009 4:00:36 AM (W. Europe Standard Time, UTC+01:00)
Great idea... just blogged about a similar line of thinking in the Silverlight/Flash hybrid microphone solution we're considering for the Tutor.com Classroom (http://russellgreenspan.blogspot.com/2009/01/microphone-access-in-silverlight-via.html). You'll need to use Flash Media Server if you want the audio conferencing aspect, but at least the bulk of your application can be in Silverlight with just the voice piece in Flash.

Thanks,
Russell Greenspan

http://www.russellgreenspan.com
http://russellgreenspan.blogspot.com/
Thursday, February 19, 2009 9:42:23 PM (W. Europe Standard Time, UTC+01:00)
Thanks for sharing the link and blog post Russell!

Combining Flash, Silverlight and other technologies enables us to write some really interesting RIAs. But I really hope Microsoft implement Mic/Webcam support in some future version of Silverlight. But for now we have to use hacks like this ;)
Thursday, April 02, 2009 5:12:22 AM (W. Europe Daylight Time, UTC+02:00)
Here is good list of motion detection resources for c# and flash developers - http://www.ugolog.com/pages/webcam-motion-detection-for-flash-flex-and-csharp
Wednesday, April 08, 2009 1:36:59 AM (W. Europe Daylight Time, UTC+02:00)
PAE: it should be possible to take the collection of bitmaps - send them over a web service / WCF link and encode a video file using full blown .NET libraries.

Try this: http://www.standardmpeg.com/documentation/tutorials/csharp
Mike
Thursday, June 25, 2009 4:09:49 PM (W. Europe Daylight Time, UTC+02:00)
This was a great solution to a key issue.

Apparently, there is no webcam/microphone support in SL3 either, which truly confuses me and creates a big problem for myself as I am currently developing a SL application that will faciliate recording (to a Silverlight format) the user by means of a webcam.

You had replied to PAE last year that your solution cannot be used/adapted to do so.

Do you know of anything else 'out there' that would provide this functionality.

Thanks Jonas

Phillip
Phillip
Monday, August 10, 2009 9:28:56 AM (W. Europe Daylight Time, UTC+02:00)
hello,
how to edit you fla file,

i have open it with macromedia flash 8 and fmx 2004, it show
"unkown file format"

thanks

email : pub123@126.com
Grant Liu
Thursday, September 24, 2009 1:38:01 PM (W. Europe Daylight Time, UTC+02:00)
We should stick with flash then until silvelight supports live webcam/microphone !
coucou
Sunday, November 08, 2009 4:06:23 PM (W. Europe Standard Time, UTC+01:00)
Your code has memory leak when i take call takesnapshot function.

i think it's in encodeByteArray function.
you allocate but never desallocate "outputBuffer".

I try recompilate it.


I use your wrapper for send webcamimage stream. it's cool without memory leak ;)
Thetyne
Sunday, November 08, 2009 7:13:32 PM (W. Europe Standard Time, UTC+01:00)
Hi,
after inverstigate, the leak is only when javascript get bitmapstring by calling takeSnapShot.

I think a leak of string copy between flash and javascript.

I have test on IE and firefox, same thing and i have desactivate my code.

so, i search...
Thetyne
Wednesday, November 11, 2009 10:44:35 AM (W. Europe Standard Time, UTC+01:00)
Thanks for commenting Thetyne,

I'm sure there are quite a few bugs in the implementation. This was done more as a fun proof-of-concept of some of the things you can do using the JavaScript bridge, rather than a real alternative to Flash for webcam apps.

But thanks for sharing :)
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910