<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tamir Khason - Just code &#187; DirectX</title>
	<atom:link href="http://khason.net/tag/directx/feed/" rel="self" type="application/rss+xml" />
	<link>http://khason.net</link>
	<description>Take care of the sense, and the sounds will take care of themselves.</description>
	<lastBuildDate>Mon, 02 Apr 2012 08:58:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Quick how to: Reduce number of colors programmatically</title>
		<link>http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/</link>
		<comments>http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 18:46:50 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[WPF crossbow]]></category>

		<guid isPermaLink="false">http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/</guid>
		<description><![CDATA[My colleague just asked me about how to reduce a number of colors in image programmatically. This is very simple task and contains of 43 steps: First of all, you have to read a source image using (var img = Image.FromFile(name)) { var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(e =&#62; e.FormatID == ImageFormat.Bmp.Guid); Then create your own encoder [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>My colleague just asked me about how to reduce a number of colors in image programmatically. This is very simple task and contains of 43 <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  steps:</p>
<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="Simple color matrix" src="http://khason.net/images/2009/02/image2.png" border="0" alt="Simple color matrix" width="383" height="366" /></p>
<p>First of all, you have to read a source image</p>
<blockquote><p>using (var img = Image.FromFile(name)) {<br />
var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(e =&gt; e.FormatID == ImageFormat.Bmp.Guid);</p></blockquote>
<p>Then create your own encoder with certain color depth (32 bits in this case)</p>
<blockquote><p>var myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;<br />
var myEncoderParameter = new EncoderParameter(myEncoder, 32L);<br />
var myEncoderParameters = new EncoderParameters(1) { Param = new EncoderParameter[] { myEncoderParameter } };</p></blockquote>
<p>Then save it</p>
<blockquote><p>img.Save(name.Replace(&#8220;.png&#8221;, &#8220;.bmp&#8221;), bmpEncoder, myEncoderParameters);</p></blockquote>
<p>It it enough? Not really, because if you’re going to loose colors (by reducing color depth), it makes sense to avoid letting default WIX decoder to do this, thus you have to find nearest base colors manually. How to do this? By using simple math</p>
<blockquote><p>Color GetNearestBaseColor(Color exactColor) {<br />
Color nearestColor = Colors.Black;<br />
int cnt = baseColors.Count;<br />
for (int i = 0; i &lt; cnt; i++) {<br />
int rRed = baseColors[i].R &#8211; exactColor.R;<br />
int rGreen = baseColors[i].G &#8211; exactColor.G;<br />
int rBlue = baseColors[i].B &#8211; exactColor.B;</p>
<p>int rDistance =<br />
(rRed * rRed) +<br />
(rGreen * rGreen) +<br />
(rBlue * rBlue);<br />
if (rDistance == 0.0) {<br />
return baseColors[i];<br />
} else if (rDistance &lt; maxDistance) {<br />
maxDistance = rDistance;<br />
nearestColor = baseColors[i];<br />
}<br />
}<br />
return nearestColor;<br />
}</p></blockquote>
<p>Now, you can either change colors on base image directly</p>
<blockquote><p>unsafe {<br />
uint* pBuffer = (uint*)hMap;<br />
for (int iy = 0; iy &lt; (int)ColorMapSource.PixelHeight; ++iy)<br />
{<br />
for (int ix = 0; ix &lt; nWidth; ++ix)<br />
{<br />
Color nc = GetNearestBaseColor(pBuffer[0].FromOle());</p>
<p>pBuffer[0] &amp;= (uint)((uint)nc.A &lt;&lt; 24) | //A<br />
(uint)(nc.R &lt;&lt; 16 ) | //R<br />
(uint)(nc.G &lt;&lt; 8 ) | //G<br />
(uint)(nc.B ); //B<br />
++pBuffer;<br />
}<br />
pBuffer += nOffset;<br />
}<br />
}</p></blockquote>
<p>Or, if you’re in WPF and .NET 3.5 <a title="HLSL (Pixel shader) effects tutorial" href="http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/" target="_blank">create simple pixel shader effect</a> to do it for you in hardware. Now, my colleague can do it himself in about 5 minutes <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  . Have a nice day and be good people.</p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>USB FM radio library was published on CodePlex</title>
		<link>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/</link>
		<comments>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 20:48:30 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[My tools]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[promo]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>

		<guid isPermaLink="false">http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/</guid>
		<description><![CDATA[I just published a part of my latest project – dynamic library to work with FM receivers on CodePlex under MS-PL. So, feel free do download, test and use it. Note, that this release is preliminary and has a lot of bugs. Also, RDS is not fully implements as well as recording capabilities with Direct [...]<p/>]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://www.codeplex.com/FM">I just published</a> a part of my latest project – dynamic library to work with <a target="_blank" href="http://www.codeplex.com/FM">FM receivers on CodePlex</a> under MS-PL. So, feel free do download, test and use it. </p>
<p>Note, that this release is preliminary and has a lot of bugs. Also, RDS is not fully implements as well as recording capabilities with Direct Sound. </p>
<p>I’m keep working to provide WPF UI for this library to “productize” it.</p>
<p>So, what are you waiting for? <a target="_blank" href="http://www.codeplex.com/FM/Release/ProjectReleases.aspx">Download</a> and Spear the word with this news! This is the first and only fully managed library (as far as I know) to work with RDS, TMC and FM data. Also, there are not a lot of information about HID usage as FM receiver in managed code.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://khason.net/images/2009/01/image.png" width="405" height="405" /> </p>
<p><a target="_blank" href="http://www.codeplex.com/FM/Release/ProjectReleases.aspx"><strong>Download latest release of USBFM.DLL &gt;&gt;</strong></a></p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Capturing and streaming sound by using DirectSound with C#</title>
		<link>http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/</link>
		<comments>http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/#comments</comments>
		<pubDate>Thu, 25 Dec 2008 10:48:20 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[DEV]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/</guid>
		<description><![CDATA[I already wrote a little about managed way to use DirectX DirectSound. Today we’ll speak about how to get sound from your microphone or any other DirectSound capturing device (such as FM receiver) and stream it out to your PC speakers and any other DirectSound Output device. So, let’s start creating our first echo service [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I already wrote a little about <a href="http://khason.net/blog/sound-tone-and-dtmf-generation-by-using-managed-directsound-and-c-and-sine-tone-detection-with-pure-managed-goertzel-algorithm-implementation/">managed way to use DirectX DirectSound</a>. Today we’ll speak about how to get sound from your microphone or any other DirectSound capturing device (such as <a href="http://khason.net/blog/reading-and-decoding-rds-radio-data-system-in-c/">FM receiver</a>) and stream it out to your PC speakers and any other DirectSound Output device. So, let’s start creating our first echo service by using managed DirectX.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-13541f81.png" width="225" height="229" /> </p>
<p>First of all we should decide what Wave format we want to use for capturing and recording. So, let’s choose anything reasonable <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>var format = new WaveFormat {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; SamplesPerSecond = 96000,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BitsPerSample = 16,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Channels = 2,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; FormatTag = WaveFormatTag.Pcm      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; };</p>
</blockquote>
<p>Now, we should calculate block align and average byte per second value for this format. I’m wondering why it cannot be done automatically…</p>
<blockquote><p>format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));     <br />format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlign;</p>
</blockquote>
<p>Next step is to set the size of two buffers – one for input and other for output. Generally those buffers are circular, and capturing one should be twice bigger, then output. Why? Because we choose two channels to use. Also, we should decide about chunk size of the buffer, we want to signal when filled.</p>
<blockquote><p>_dwNotifySize = Math.Max(4096, format.AverageBytesPerSecond / 8);     <br />_dwNotifySize -= _dwNotifySize % format.BlockAlign;      <br />_dwCaptureBufferSize = NUM_BUFFERS * _dwNotifySize;      <br />_dwOutputBufferSize = NUM_BUFFERS * _dwNotifySize / 2;</p>
</blockquote>
<p>Next step is to create CaptureBufferDescriptor and actual capturing buffer. We’ll enumerate all devices and choose one, satisfies given string (captureDescriptor) – for example “Mic” <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>var cap = default(Capture);     <br />var cdc = new CaptureDevicesCollection();      <br />for (int i = 0; i &lt; cdc.Count; i++) {      <br />&#160;&#160; if (cdc[i].Description.ToLower().Contains(captureDescriptor.ToLower())) {      <br />&#160;&#160;&#160;&#160;&#160; cap = new Capture(cdc[i].DriverGuid);      <br />&#160;&#160;&#160;&#160;&#160; break;      <br />&#160;&#160; }      <br />}      <br />var capDesc = new CaptureBufferDescription {      <br />&#160;&#160; Format = format,      <br />&#160;&#160; BufferBytes = _dwCaptureBufferSize      <br />};      <br />_dwCapBuffer = new CaptureBuffer(capDesc, cap);</p>
</blockquote>
<p>Then we’ll create output device and buffer. To simplify program, we will use default speakers to output, however, you can choose output device the same way we did for capturing. Also, because DirectSound uses any window as it’s message pump, we have to use SetCooperativeLevel method. In my case (windowless application), I’ll use desktop window as message broker. This why you will have to add Windows.Forms as reference for your project, even if it console application. Also, do not forget to set GlobalFocus value to True, if you want to play echo, even if desktop window is not focused.</p>
<blockquote><p>var dev = new Device();     <br />dev.SetCooperativeLevel(Native.GetDesktopWindow(), CooperativeLevel.Priority); </p>
<p>var devDesc = new BufferDescription {     <br />&#160;&#160; BufferBytes = _dwOutputBufferSize,      <br />&#160;&#160; Format = format,      <br />&#160;&#160; DeferLocation = true,      <br />&#160;&#160; GlobalFocus = true      <br />};      <br />_dwDevBuffer = new SecondaryBuffer(devDesc, dev);</p>
</blockquote>
<p>Now, we will subscribe to buffer notifications and set autoResetEvent to be fired when it filled up.</p>
<blockquote><p>var _resetEvent = new AutoResetEvent(false);     <br />var _notify = new Notify(_dwCapBuffer);      <br />//half&amp;half      <br />var bpn1 = new BufferPositionNotify();      <br />bpn1.Offset = _dwCapBuffer.Caps.BufferBytes / 2 &#8211; 1;      <br />bpn1.EventNotifyHandle = _resetEvent.SafeWaitHandle.DangerousGetHandle();      <br />var bpn2 = new BufferPositionNotify();      <br />bpn2.Offset = _dwCapBuffer.Caps.BufferBytes &#8211; 1;      <br />bpn2.EventNotifyHandle = _resetEvent.SafeWaitHandle.DangerousGetHandle(); </p>
<p>_notify.SetNotificationPositions(new BufferPositionNotify[] { bpn1, bpn2 });</p>
</blockquote>
<p>Almost done, the only thing we should do is to fire worker thread to take care on messages</p>
<blockquote><p>int offset = 0;     <br />_dwCaptureThread = new Thread((ThreadStart)delegate {      <br />&#160;&#160; _dwCapBuffer.Start(true); </p>
<p>&#160;&#160; while (IsReady) {     <br />&#160;&#160;&#160;&#160;&#160; _resetEvent.WaitOne();      <br />&#160;&#160;&#160;&#160;&#160; var read = _dwCapBuffer.Read(offset, typeof(byte), LockFlag.None, _dwOutputBufferSize);      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.Write(0, read, LockFlag.EntireBuffer);      <br />&#160;&#160;&#160;&#160;&#160; offset = (offset + _dwOutputBufferSize) % _dwCaptureBufferSize;      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.SetCurrentPosition(0);      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.Play(0, BufferPlayFlags.Default);      <br />&#160;&#160; }      <br />&#160;&#160; _dwCapBuffer.Stop();      <br />});      <br />_dwCaptureThread.Start();</p>
</blockquote>
<p>That’s it. Compile and run. Now if you’ll speak, you can hear your echo from PC speakers. </p>
<p>Merry Christmas for whom concerns and be good people – do not scare your co-workers with strange sounds – be polite and make the volume lower <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/feed/</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>Programming for Windows 7</title>
		<link>http://khason.net/blog/programming-for-windows-7/</link>
		<comments>http://khason.net/blog/programming-for-windows-7/#comments</comments>
		<pubDate>Sun, 09 Nov 2008 12:12:38 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[blogging general]]></category>
		<category><![CDATA[demos]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[promo]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TECH]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Vista]]></category>
		<category><![CDATA[Vista Battery Saver]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Windows 7]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XPS]]></category>

		<guid isPermaLink="false">http://khason.net/blog/programming-for-windows-7/</guid>
		<description><![CDATA[Well, Windows 7 is going to be released by the end of next year. This is great news, because it seemed, that Microsoft finally understand how to get the best of Windows Vista and make it to work not only on monster machines. It even works on new brandy my wife&#8217;s pinky machine. And if [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Well, Windows 7 is going to be released by the end of next year. This is great news, because it seemed, that Microsoft finally understand how to get the best of Windows Vista and make it to work not only on <a href="http://www.top500.org/">monster machines</a>. </p>
<p><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" src="http://khason.net/images/2008/12/image-3.png" width="600" height="397"/> </p>
<p>It even works on new brandy my wife&#8217;s pinky machine. And if it works there and my wife is happy with it, this OS going to be very impressive.</p>
<p><img border="0" alt="image" src="http://khason.net/images/2008/12/image-58bf6973-bdc1-44d9-8649-f24e6255e65f.png" width="529" height="397"/> </p>
<p>But from the other hand, we, as developers should be ready today to developer Windows 7 ready application (by the way, <a target="_blank" href="http://blogs.microsoft.co.il/blogs/tamir/archive/tags/Vista+Battery+Saver/default.aspx">Vista Battery Saver</a> works for Windows 7 as well as for Windows Vista, in spite of the fact, that power management in Windows 7 was improved dramatically). So let&#8217;s start!</p>
<p>First thing we need is to read big <a target="_blank" href="http://code.msdn.microsoft.com/Win7DeveloperGuide/Release/ProjectReleases.aspx">Windows 7 Developer Guide</a>. This document will explain most of new features for developers to build applications right. What is includes?</p>
<h3>Windows Driver Kit (WDK) 3.0</h3>
<p>Basically, Windows 7 works with Vista drivers, however, hibernation, power management, networking, PREfast will work much better. You also will have new WMI access for reliability monitors and ACPI. </p>
<h3>Management and deployment</h3>
<p>By default Windows 7 uses PowerShell 2.0 and Windows Installer. For PowerShell it includes enhanced cmdlets to manage Active Directory, IIS, etc. For Windows Installer, you finally can build &#8220;chainers&#8221; by yourself (the same approach, used for latest deployment of Microsoft products such as <a target="_blank" href="http://blogs.microsoft.co.il/blogs/tamir/archive/tags/Silverlight/default.aspx">Silverlight</a>, <a target="_blank" href="http://blogs.microsoft.co.il/blogs/tamir/archive/tags/Visual+Studio/default.aspx">Visual Studio 2008 SP1</a> etc.) Also, you can get advantage by using Windows Filtering Platform (Firewall) and User Account Control (UAC) from inside your application by using new APIs. </p>
<h3>Performance</h3>
<p>The most significant change in Windows 7 for end-user point of view is improved performance. Windows 7 kernel is much smaller, that kernel of Windows Vista. Also it uses specific patterns to decrease background activities on low power, based on system triggers. New user-mode and kernel-mode APIs are used by Windows Drivers Foundation much more efficiently. Also system services are much smarter. For example, DCIA starts only when you connect new hardware. After drivers were installed the service shuts down. The same approach used by domain join, GP changes, new IP fetching etc. Windows 7 knows to run and stop services, based on system events, which decreases average work load and enhances whole system performance. </p>
<h3>Multi-touch gestures and Interia API and used interface in general</h3>
<p>Yes, you can use this API for your applications. Finally we can have more, then just mouse. And it is not only about multiple mouse devices. We can use single finder panning, raw touch input data, internal multitouch ink recognition, which is also supports math. Also it uses build-in MathML export feature. </p>
<p>There are a lot of other enhancements, such as smart bars, windows&#8217; stacking, gadget desktop (it does not eat battery as external process anymore), system ribbon menu integration. etc</p>
<h3>Graphics</h3>
<p>Direct 11, new Direct2D, DirectWrite (we can turn text anti-aliasing for small fonts, hurrah!), improved WIC, DX/GDI interoperability on system level with automatic fallback for weak hardware (yes, you should not be worry about it anymore). Also new video and audio format support with <u>human readable interfaces</u>. Yes, no more DirectDraw hacks. We can use new high level interfaces such as MFPlay to manage playbacks, Source Reader for decoding, Sink Writer for transcoders and re-coding compressions.</p>
<h3>Web and communication</h3>
<p>WCF is inside, as well as distributed routing table for peer-to-peer operations. BranchCache &#8211; new technology to reduce WAN traffic and latency. </p>
<p>Also Windows 7 is compatible with <a target="_blank" href="http://www.opensearch.org">OpenSearch</a> (I told, that Microsoft does not know to build search engines). Sharepoint integration and environment sensors platform, that can be used either for desktop and web applications. </p>
<p>There are much more features, that makes Windows 7 to pretend to be very good operation system. If you want to learn more about all those Windows 7 new features, I highly advice you to <a target="_blank" href="http://code.msdn.microsoft.com/Win7DeveloperGuide/Release/ProjectReleases.aspx">download and read this document</a>. It includes most of new features of new OS with explanations and screenshots to make your learn and understand what can your future application do with all those new features.</p>
<p>Have a nice day and be good people.</p>
<p>BTW, if you have PDC version of Windows 7 and want to unlock it for using of some cool features, <a target="_blank" href="http://channel9.msdn.com/pdc2008/KYN02/">introduced during keynotes</a>, it worth <a target="_blank" href="http://www.withinwindows.com/2008/11/02/flashy-windows-7-bits-protected-by-elaborate-scheme-workaround/">to visit here</a> and learn how to <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Download </strong><a href="http://code.msdn.microsoft.com/Win7DeveloperGuide"><strong>Windows 7 Developer Guide</strong></a><strong> and start programming.</strong></p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/programming-for-windows-7/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>HLSL (Pixel shader) effects tutorial</title>
		<link>http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/</link>
		<comments>http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 21:56:13 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/</guid>
		<description><![CDATA[Recently, I already wrote about PixelShader effects, introduced in .NET framework 3.5 SP1 (WPF). However it looks like for most people this syntax is still hard to understand. Today we’ll try to lean it more. In order to do this, I wrote small program, that helps you to write and debug pixel shader effects quickly. [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Recently, <a href="http://khason.net/blog/brightness-and-contrast-manipulation-in-wpf-35-sp1/">I already wrote about PixelShader effects</a>, introduced in .NET framework 3.5 SP1 (WPF). However it looks like for most people this syntax is still hard to understand. Today we’ll try to lean it more. In order to do this, I wrote small program, that helps you to write and debug pixel shader effects quickly. This how it looks like</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-70299c1b-722e-44c2-88e4-bf899d65018b.png" width="703" height="713" /> </p>
<p>Hit Open to load image, Write your code and hit Execute to compile and apply bitmap dx effect to the image. Let’s start from very beginning. Effect, that does nothing:</p>
<blockquote><p>sampler2D input : register(s0);     <br />float4 main(float2 uv : TEXCOORD) : COLOR      <br />{      <br />&#160;&#160;&#160; float4 Color;      <br />&#160;&#160;&#160; Color = tex2D( input , uv.xy);      <br />&#160;&#160;&#160; return Color;      <br />}</p>
</blockquote>
<p>This is the results:</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-82e5ad3b-72ea-46b3-82ad-5d7022d0c248.png" width="423" height="272" /> </p>
<p>What was done? We got pixel. Read it color and return it as it to the shader. Let’s do something more interesting.</p>
<p>Actually we can get float2 as coordinate, this means, that it can be spitted to uv.x and uv.y. Also color is float4 (argb), thus we can change color. Let’s multiply color by 3</p>
<blockquote><p>Color = tex2D( input , uv.xy)*3;</p>
</blockquote>
<p>And the result is bright image</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-8460e6d1-3244-4dd8-b613-c92d22ce2361.png" width="425" height="272" /> </p>
<p>We also can make operations with variables.</p>
<blockquote><p>Color = tex2D( input , uv.xy)*uv.x;</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-c44e6dbc-a594-425c-bf35-86a34c1ec914.png" width="432" height="255" /> </p>
<p>We not have to change whole color. We can also change only its part. Blue for example</p>
<blockquote><p>Color = tex2D( input , uv.xy);     <br />Color.b = Color.b*2;</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-f1c02841-1e4e-494e-85e8-0314785d07df.png" width="422" height="236" /> </p>
<p>Or execute math operations</p>
<blockquote><p>Color = tex2D( input , uv.xy);     <br />Color.r = Color.r*sin(uv.x*100)*2;      <br />Color.g = Color.g*cos(uv.x*150)*2;      <br />Color.b = Color.b*sin(uv.x*50)*2;</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-b362a6b3-f754-489f-8200-3f9448210dad.png" width="428" height="240" /> </p>
<p>Color is not only thing we can operate. Actually we’re sampling coordinates, so operations done with coordinates should work. Let’s try to stretch image</p>
<blockquote><p>uv.x = uv.x * 0.5;     <br />Color = tex2D( input , uv.xy);</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-0812b43c-99f2-498e-949c-d365f0f8e515.png" width="500" height="196" /> </p>
<p>Why 0.5? Should not it make it smaller? Actually not, you’re multiplying coordinates, so to make the image smaller, you should divide </p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
<blockquote><p>uv.x = uv.x / 0.5;     <br />Color = tex2D( input , uv.xy);</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-d530e052-d198-46ee-82e1-9f7901f9af3b.png" width="454" height="213" /> </p>
<p>Some math could be fun here also</p>
<blockquote><p>uv.y = uv.y&#160; + (sin(uv.y*100)*0.03);     <br />Color = tex2D( input , uv.xy);</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-cc11aa2a-e616-42a1-9ff9-d39ff125cf5e.png" width="434" height="205" /> </p>
<p>There are a ton of interesting effects you can do by using pixel shaders. Here for example color shift</p>
<blockquote><p>&#160;&#160; Color = tex2D( input , uv);     <br />Color.r -= tex2D( input , uv +(somevar/100)).r;      <br />Color.g += tex2D( input , uv+ (somevar/200)).g;      <br />Color.b -= tex2D( input , uv+ (somevar/300)).b;</p>
</blockquote>
<p>Result:</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-0eb1d179-1f56-4ab3-a39c-7650dc41094f.png" width="456" height="238" /> </p>
<p>Or, even cooler efects</p>
<blockquote><p>Color -= tex2D(input , uv.xy-0.003)*2.7f;     <br />Color += tex2D( input , uv.xy+0.003)*2.7f;      <br />Color.rgb = (Color.r+Color.g+Color.b)/3.0f;</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-d7793d59-ea16-4754-b233-03e635a53e0e.png" width="439" height="276" /> </p>
<p>You can also use cases and ifs for even cooler effects</p>
<blockquote><p>Color.rgb = (Color.r+Color.g+Color.b)/3.0f;     <br />if (Color.r&lt;0.2 || Color.r&gt;0.9) Color.r = 0; else Color.r = 1.0f;      <br />if (Color.g&lt;0.2 || Color.g&gt;0.9) Color.g = 0; else Color.g = 1.0f;      <br />if (Color.b&lt;0.2 || Color.b&gt;0.9) Color.b = 0; else Color.b = 1.0f;</p>
</blockquote>
<p>Result</p>
<p><img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-54cf74fd-fff8-48f4-a05d-b632fca70597.png" width="436" height="260" /> </p>
<p>Other words, the sky is the limit. </p>
<p>Please note, that Pixel Shaders done in GPU only, thus it is the most efficient method to manipulate your images. Actually, you can apply effect to any UIElement, thus the sky is really the limit.</p>
<p>Have a nice day and be good people. Download code for this article. Notice, that you’ll need DirectX SDK to compile pixel shader files and use this program</p>
<div style="padding-right: 0px; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px; display: inline" id="scid:4c033bbc-1f2f-4686-a55f-26926c847a06:4543afae-62a5-4c04-9c60-b17a446628e6" class="wlWriterSmartContent">
<p><a href="http://blogs.microsoft.co.il/blogs/tamir/WindowsLiveWriter/HLSLPixelshadereffectstutorial_1342F/HLSLTester_1.zip" title="HLSLTester.zip [47.3 Kb]">HLSLTester.zip [47.3 Kb]</a></p>
</div>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Brightness and contrast manipulation in WPF 3.5 SP1</title>
		<link>http://khason.net/blog/brightness-and-contrast-manipulation-in-wpf-35-sp1/</link>
		<comments>http://khason.net/blog/brightness-and-contrast-manipulation-in-wpf-35-sp1/#comments</comments>
		<pubDate>Fri, 23 May 2008 18:06:00 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/blog/brightness-and-contrast-manipulation-in-wpf-35-sp1/</guid>
		<description><![CDATA[While being in flight, I had to learn new features, introduced in .NET 3.5 SP1. So, let’s start from image manipulation. I want to perform contrast and brightness manipulation in GPU over displayed image. In order to begin, you should download and install .NET 3.5 SP1 and Visual Studio 2008 SP1. Meanwhile (it’s about 500 [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>While being in flight, I had to learn new features, introduced in .NET 3.5 SP1. So, let’s start from image manipulation. I want to perform contrast and brightness manipulation in GPU over displayed image. In order to begin, you should download and install <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=23516C63-2DB2-4E7F-AABA-32B12D6E025C&amp;displaylang=en" mce_href="http://www.microsoft.com/downloads/details.aspx?FamilyId=23516C63-2DB2-4E7F-AABA-32B12D6E025C&amp;displaylang=en" target="_blank">.NET 3.5 SP1</a> and <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=CF99C752-1391-4BC3-BABC-86BC0B9E8E5A&amp;displaylang=en" mce_href="http://www.microsoft.com/downloads/details.aspx?FamilyId=CF99C752-1391-4BC3-BABC-86BC0B9E8E5A&amp;displaylang=en" target="_blank">Visual Studio 2008 SP1</a>. Meanwhile (it’s about 500 MB of download) we’ll learn how to write custom shader effect.</p>
<p><img src="http://khason.net/images/2008/12/image-5e082569-5244-4eef-a94e-784adc53cdbb.png" title="image" alt="image" mce_src="http://khason.net/images/2008/12/image-5e082569-5244-4eef-a94e-784adc53cdbb.png" border="0" height="299" width="301"/> </p>
<p>In order to build custom Shader Effer, we have to use HLSL (High Level Shading Language). This is programming language, introduces in DirectX 9.0 and supports the shader construction with C-like syntax, types, expressions and functions. If you know C – it will be very easy for you to learn it. </p>
<p>What is shader? Shader is consists of vertex shader and pixel shader. Any 3D model flows from application to the vertex shader, then pixel shader frames buffer. So we’ll try from simple matrix transformation. First we should build the struct of the position. It is float4 type and has POSITION inheritance. Also we have to get matrix, which is regular float4x4 object. Then all we have to to is to translate inpos by matrix and return new position. That’s exactly what following code does.</p>
<blockquote><p>float4 main(float4 inpos : POSITION, uniform float4x4 ModelViewMatrix) : POSITION     <br />&nbsp; {      <br />&nbsp;&nbsp;&nbsp;&nbsp; return mul(inpos, ModelViewMatrix);       <br />&nbsp; }</p>
</blockquote>
<p>So by using HLSL we can play freely with vertexes, but what’s happen with pixel shader? This works exactly the same way. We have pixel, which is TEXCOORD in input and COLOR in output. So, here it comes</p>
<blockquote><p>float4 main(float2 uv : TEXCOORD, float brightness, float contrast) : COLOR     <br />{      <br />&nbsp;&nbsp;&nbsp; float4 color = tex2D(input, uv);&nbsp; <br />&nbsp;&nbsp;&nbsp; return (color + brightness) * (1.0+contrast)/1.0;      <br />}</p>
</blockquote>
<p>For more information about HLSL, please <a href="http://msdn.microsoft.com/en-us/library/bb509561%28VS.85%29.aspx" mce_href="http://msdn.microsoft.com/en-us/library/bb509561(VS.85).aspx" target="_blank">visit MSDN</a>. As for us, we already have our shader effect and how we have to compile it into executable filter. In order to do it, we’ll use directx shader effect compiler. Let’s say, that we have our source in effect.txt file and our output file will be effect.ps. Small tip insert following line into pre-build event, and have your shader effect script ready and up-to-day with each compilation.</p>
<blockquote><p>fxc /T ps_2_0 /E main /Fo&#8221;$(ProjectDir)effect.ps&#8221; &#8220;$(ProjectDir)effect.txt&#8221;</p>
</blockquote>
<p>Mode information about FX compiler command switches, can be found <a href="http://msdn.microsoft.com/en-us/library/bb205078%28VS.85%29.aspx" mce_href="http://msdn.microsoft.com/en-us/library/bb205078(VS.85).aspx" target="_blank">here</a>. How we should actually wrap our effect in manage code. But wait. We have to pass parameters into shader effect. How to register external parameters within FX file? Simple. Exactly as input params. Note, the tag inside register method will actually be used within our managed wrapper.</p>
<blockquote><p>sampler2D input : register(s0);     <br />float brightness : register(c0);      <br />float contrast : register(c1);</p>
<p>float4 main(float2 uv : TEXCOORD) : COLOR     <br />{      <br />&nbsp;&nbsp;&nbsp; float4 color = tex2D(input, uv);       <br />&nbsp;&nbsp;&nbsp; float4 result = color;      <br />&nbsp;&nbsp;&nbsp; result = color + brightness;      <br />&nbsp;&nbsp;&nbsp; result = result * (1.0+contrast)/1.0;      <br />&nbsp;&nbsp;&nbsp; return result;      <br />}</p>
</blockquote>
<p>Well done.&nbsp; Let’s build wrapper. Of cause you should inherit from ShaderEffect object and register your input param</p>
<blockquote><p>public class BrightContrastEffect : ShaderEffect     <br />&nbsp;&nbsp;&nbsp; {      <br />…      </p>
<p>public Brush Input     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get { return (Brush)GetValue(InputProperty); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; set { SetValue(InputProperty, value); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty(&#8220;Input&#8221;, typeof(BrightContrastEffect), 0);</p>
</blockquote>
<p>Then load pixel shader from application resources (you should compile ps file as “Resource”)</p>
<blockquote><p>private static PixelShader m_shader = new PixelShader() { UriSource = new Uri(@&#8221;pack://application:,,,/CustomPixelRender;component/bricon.ps&#8221;) };</p>
</blockquote>
<p>Then parameters (they are regular dependency objects) with additional special PixelShaderConstantCallback, that received the numeric id of registered properties from pixel shader effect.</p>
<blockquote><p>public float Brightness     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get { return (float)GetValue(BrightnessProperty); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; set { SetValue(BrightnessProperty, value); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static readonly DependencyProperty BrightnessProperty = DependencyProperty.Register(&#8220;Brightness&#8221;, typeof(double), typeof(BrightContrastEffect), new UIPropertyMetadata(0.0, PixelShaderConstantCallback(0))); </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public float Contrast     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get { return (float)GetValue(ContrastProperty); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; set { SetValue(ContrastProperty, value); }      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>A couple of updates and we done with code behind.</p>
<blockquote><p>public BrightContrastEffect()     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PixelShader = m_shader;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UpdateShaderValue(InputProperty);      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UpdateShaderValue(BrightnessProperty);      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UpdateShaderValue(ContrastProperty); </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>Next step is XAML. Each UI element in .NET 3.5 SP1 got new property, named Effect, that designed to hold your custom shader effects (exactly as it was with transformations in 3.0 and 3.5). I want to perform a transformation over image.</p>
<blockquote><p>&lt;Image Source=&#8221;img.jpg&#8221;&gt;     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;Image.Effect&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;l:BrightContrastEffect </p>
</blockquote>
<p>Now we should build two sliders to manage brightness and contrast level</p>
<blockquote><p>&lt;UniformGrid Grid.Row=&#8221;1&#8243;&gt;     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;TextBlock Text=&#8221;Brightness&#8221;/&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;Slider Maximum=&#8221;1&#8243; Minimum=&#8221;-1&#8243; Name=&#8221;bVal&#8221;/&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;TextBlock Text=&#8221;Contrast&#8221;/&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;Slider Maximum=&#8221;1&#8243; Minimum=&#8221;-1&#8243; Name=&#8221;cVal&#8221;/&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/UniformGrid&gt;</p>
</blockquote>
<p>And bind to its values from our pixel shader effect</p>
<blockquote><p>&lt;Image Source=&#8221;img.jpg&#8221;&gt;     <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;Image.Effect&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;l:BrightContrastEffect       <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Brightness=&#8221;{Binding ElementName=bVal, Path=Value}&#8221;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Contrast=&#8221;{Binding ElementName=cVal, Path=Value}&#8221;/&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/Image.Effect&gt;      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/Image&gt;</p>
</blockquote>
<p>That’s all, folks. Please note, that everything, done with shader effects, done in GPU. Also, the effect applies on rendered object (you can set the same effect not only to image, but to any UIElement in your system. Thus from performance point of view it’s the best method to work with your output. Let’s take for example very big image (3000&#215;3000 pixels), rendered with low quality to 300&#215;300 size. Perform per-pixel transformation (what we done here) will take 300X300Xdpi loops. While if you’ll perform the same operating over source image or memory section, used to create it, you’ll have to do 3000x3000xdpi loops, which is x10^2 more times. </p>
<p>Have a nice day and be good people. </p>
<p><a href="http://cid-4e39ecd492e4eec1.skydrive.live.com/self.aspx/Windows%20Share%20Folder/CustomPixelRender.zip" mce_href="http://cid-4e39ecd492e4eec1.skydrive.live.com/self.aspx/Windows%20Share%20Folder/CustomPixelRender.zip">Source code for this article</a>.</p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/brightness-and-contrast-manipulation-in-wpf-35-sp1/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Webcam control with WPF or how to create high framerate player with DirectShow by using InteropBitmap in WPF application</title>
		<link>http://khason.net/blog/webcam-control-with-wpf-or-how-to-create-high-framerate-player-with-directshow-by-using-interopbitmap-in-wpf-application/</link>
		<comments>http://khason.net/blog/webcam-control-with-wpf-or-how-to-create-high-framerate-player-with-directshow-by-using-interopbitmap-in-wpf-application/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 21:33:50 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/blog/webcam-control-with-wpf-or-how-to-create-high-framerate-player-with-directshow-by-using-interopbitmap-in-wpf-application/</guid>
		<description><![CDATA[Did you ever see, that MediaElement “eats” about 30% of CPU while playing movie in WPF? Did you thought, that you&#160; can display live camera capture in WPF with 60 fps full screen (I have really high resolution 1920&#215;1200) and 2% of&#160; CPU? You did not? Let’s see how it can be done. Today we’ll [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Did you ever see, that MediaElement “eats” about 30% of CPU while playing movie in WPF? Did you thought, that you&#160; can display live camera capture in WPF with 60 fps full screen (I have really high resolution 1920&#215;1200) and 2% of&#160; CPU? You did not? Let’s see how it can be done. Today we’ll create simple WebCam player control that can show you live video capturing with high frame rate. In order to do it, we’ll use DirectShow, WPF and make them work together. </p>
<p>&#160; <img title="image" border="0" alt="image" src="http://khason.net/images/2008/12/image-6bcb2dac-e598-4e0f-83f3-29f231cb703b.png" width="548" height="238" /> </p>
<p>You, probably do not believe me. Let’s start. In order to build this application, we need to make DirectDraw working in C# managed code. We can use <a href="http://directshownet.sourceforge.net/" target="_blank">DirectShow.NET</a>, but this time we’ll do it manually. Why? because I love to do things manually. So let’s understand what we need? Actually, not very much: one Sample Grabber (ISampleGrabber) and one Device input filter(IBaseFilter). Both we should connvert with Graph Builder (IGraphBuilder) and point to some grabber implementation (ISampleGrabberCB). Also, we do not want DirectShow to render video for use, thus we’ll send it’s default Video Window (IVideoWindow) to null with no AutoShow and then run the controller (IMediaControl). Do you tired enough to lost me? Let’s see the code. One Filter graph with one Device Filter and one Sample grabber.</p>
<blockquote><p>graph = Activator.CreateInstance(Type.GetTypeFromCLSID(FilterGraph)) as IGraphBuilder;     <br />sourceObject = FilterInfo.CreateFilter(deviceMoniker); </p>
<p>grabber = Activator.CreateInstance(Type.GetTypeFromCLSID(SampleGrabber)) as ISampleGrabber;     <br />grabberObject = grabber as IBaseFilter; </p>
<p>graph.AddFilter(sourceObject, &quot;source&quot;);     <br />graph.AddFilter(grabberObject, &quot;grabber&quot;);</p>
</blockquote>
<p>Set media type for our grabber</p>
<blockquote><p>using (AMMediaType mediaType = new AMMediaType())     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; mediaType.MajorType = MediaTypes.Video;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; mediaType.SubType = MediaSubTypes.RGB32;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; grabber.SetMediaType(mediaType);</p>
</blockquote>
<p>And then connect device filter to out pin and grabber to in pin. Then get capabilities of video received (thiss stuff come from your web camera manufacturer)</p>
<blockquote><p>if (graph.Connect(sourceObject.GetPin(PinDirection.Output, 0), grabberObject.GetPin(PinDirection.Input, 0)) &gt;= 0)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (grabber.GetConnectedMediaType(mediaType) == 0)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; VideoInfoHeader header = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.FormatPtr, typeof(VideoInfoHeader));      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; capGrabber.Width = header.BmiHeader.Width;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; capGrabber.Height = header.BmiHeader.Height;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Out pin to grabber without buffering and callback to grabber object (this one will get all images from our source).</p>
<blockquote><p>graph.Render(grabberObject.GetPin(PinDirection.Output, 0));     <br />grabber.SetBufferSamples(false);      <br />grabber.SetOneShot(false);      <br />grabber.SetCallback(capGrabber, 1);</p>
</blockquote>
<p>Dump output window</p>
<blockquote><p>IVideoWindow wnd = (IVideoWindow)graph;     <br />wnd.put_AutoShow(false);      <br />wnd = null;</p>
</blockquote>
<p>And run the controller</p>
<blockquote><p>control = (IMediaControl)graph;     <br />control.Run();</p>
</blockquote>
<p>We done. Now our video is captured and can be accessed from BufferCB method of ISampleGrabberCB. Next step is to do WPF related stuff</p>
<p>First of all, we’ll use InteropBitmap. This one <a href="http://khason.net/blog/how-to-high-performance-graphics-in-wpf/" target="_blank">will provide us with real performance bust</a>. So, one our DirectShow graph is ready and we know result image capabilities, we can create memory section and map it in order to provide ISampleGrabberCB with place to put images. This will be always the same pointer, so all we have to do is to .Invalidate interop image.</p>
<blockquote><p>if (capGrabber.Width != default(int) &amp;&amp; capGrabber.Height != default(int))     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; uint pcount = (uint)(capGrabber.Width * capGrabber.Height * PixelFormats.Bgr32.BitsPerPixel / 8);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0&#215;04, 0, pcount, null);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; map = MapViewOfFile(section, 0xF001F, 0, 0, pcount);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromMemorySection(section, capGrabber.Width, capGrabber.Height, PixelFormats.Bgr32,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; capGrabber.Width * PixelFormats.Bgr32.BitsPerPixel / 8, 0) as InteropBitmap;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; capGrabber.Map = map;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (OnNewBitmapReady != null)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; OnNewBitmapReady(this, null);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Now in capGrabber (ISampleGrabberCB) we’ll copy buffer, comes from our webcam to the mapped location for WPF usage</p>
<blockquote><p>public int BufferCB(double sampleTime, IntPtr buffer, int bufferLen)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (Map != IntPtr.Zero)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; CopyMemory(Map, buffer, bufferLen);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; OnNewFrameArrived();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return 0;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>All we have to do is to call InteropBitmap.Invalidate() each frame to reread the image bytes from the mapped section.</p>
<blockquote><p>if (BitmapSource != null)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BitmapSource.Invalidate();</p>
</blockquote>
<p>How do display all this stuff? Simple – subclass from Image and set it’s Source property with the interop bitmap.</p>
<blockquote><p>public class CapPlayer : Image,IDisposable     <br />&#160;&#160;&#160; {      <br />…      </p>
<p>void _device_OnNewBitmapReady(object sender, EventArgs e)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.Source = _device.BitmapSource;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Now, the usage from XAML is really simple</p>
<blockquote><p>&lt;l:CapPlayer x:Name=&quot;player&quot;/&gt;</p>
</blockquote>
<p>We done <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  As always, download full source code for this article </p>
<div style="padding-right: 0px; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px; display: inline" id="scid:4c033bbc-1f2f-4686-a55f-26926c847a06:594a177b-c713-498f-a82e-24ca44e30cff" class="wlWriterSmartContent">
<p><a href="http://blogs.microsoft.co.il/blogs/tamir/WindowsLiveWriter/WebcamcontrolwithWPForhowtocreatehighfra_12F13/AvCapWPF_1.zip" title="AvCapWPF.zip [32.7 Kb]">AvCapWPF.zip [32.7 Kb]</a></p>
</div>
<p>…and be good people and don’t tell anymore, that WPF performance in terms of imaging is sucks <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><em>P.S.</em> small ‘r’ if you have more, then one WebCam connected. Inside CapDevice class there is member, public static FilterInfo[] DeviceMonikes, that provides you with all DirectShow devices installed. So, the only thing you should do in order to change the device is to set deviceMoniker = DeviceMonikes[0].MonikerString; with the moniker of your device. This sample works with first one.</p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/webcam-control-with-wpf-or-how-to-create-high-framerate-player-with-directshow-by-using-interopbitmap-in-wpf-application/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
	</channel>
</rss>

