Tag Archives: muaz-khan

Capturing webcam using DirectShow.NET library


I’m using DirectShow.NET library to capture and preview all webcams connected to my PC.

Download Demo | Download Source Code | Latest file available here (.msi)

Origianl Source code of DirectShow.NET Library edited by Muaz Khan

What is DirectShow.NET?

DirectShow.NET is a library for manage code (.NET framework) that allows developers access (preview/capture) video devices (webcams, TV-tunnels, scanners etc.) by using simple objects like enums, structs and interfaces. Developers don’t have to worry about filters, memory addresses, and GUIDs as C++ and COM developers do all these things manually.

Filters filters = new Filters();

Filters” class do following jobs:

  1. Track all video devices attached to your PC
  2. Track all audio devices attached to your PC
  3. Track all video compressors
  4. Track all audio compressors

To access first video device (webcam) and first audio device connected to your PC:

Capture capture = new Capture(
    filters.VideoInputDevices[0],
    filters.AudioInputDevices[0]
);

By setting “PreviewWindow” property; you can preview the captured video into a panel or in any container windows forms control:

capture.PreviewWindow = panel;

In the above line, “panel” is System.Windows.Forms.Panel object.

And your last task is start previewing the video stream!

capture.Start();

To save the captured video into the Disk device; you’ve to set “FileName” property:

if (!capture.Cued) capture.Filename = "captured-video.wmv";

For tracking second or third video or audio device connected to your PC, just increment the index:

Capturecapture = new Capture(
    filters.VideoInputDevices[increment_index],
    filters.AudioInputDevices[increment_index]
);

It is better to use first audio device (index: 0) if all webcams are placed in the same room.

In case, when there is no video device attached to your PC, the program will throw an error. I recommend you use this technique instead of using try-catch blocks to handle the error:

if (filters.VideoInputDevices != null)
{

// all code goes here

}

To stop streaming (previewing or capturing into disk):

capture.Stop();

To capture as quickly as possible, use “capture.Cue()” method:

capture.Cue();

capture.Start();

This will speedup streaming/capturing into disk.

In the demo project, I’m not only previewing and capturing into disk but also using timer to automatically change file name after each 10 minutes.

I’m using timer because the size of video file goes into GB after some time; so we’ve to split video files for FTP upload or other uses!

timer.Interval = 600000; // 10 minutes!

In the “Tick” event of the “timer” object:

counter++;
if (!capture.Cued) capture.Filename = counter + ".wmv";

Where I’m incrementing “counter” object on each tick.

I’m capturing video into “WMV” file; you can also use “AVI” or other supported formats.

DirectShow supports ASF, WMA, WMV, AIFF, AU, AVI, MIDI, SND, and WAV video formats.

You can also compress the video:

capture.VideoCompressor = filters.VideoCompressors[0];
capture.AudioCompressor = filters.AudioCompressors[0];

DirectShow supports compression formats such as H.264, AAC, Cinepak, DV (Digital Video), ISO MPEG-4 video version 1.0, Microsoft MPEG-4 version 3, MJPEG, MPEG Audio Layer-3 (MP3) (decompression only), MPEG-1 layer I and layer II audio, MPEG-1 video, MPEG-2 audio, and MPEG-2 video.You can also use third party codecs.

Downloads:

  1. Download DirectShow.NET Library
  2. Download Demo
  3. Download Source Code of the Demo Project
  4. Origianl Source code of DirectShow.NET Library edited by Muaz Khan

Updated at March 1, 2013:

You can set width and height of the “panel” element to control frame size (i.e. min/max width/height) of the preview screen:

panel.Width = this.Width;
panel.Height = this.Height;

Above two lines will set panel’s width and height equal to current window’s width and height.

CSP (Content Security Policy)


In this post, I’ll practically show you one promising new defense using CSP (Content Security Policy) that can significantly reduce possible XSS (Cross-Site Scripting) attacks in modern web-browsers (currently Chrome 16+ and Firefox 4+)!

I’ll not only block inline/outer scripts but also ask user-agent to auto-generate report for each violated activity it founds that violates my pre-defined policy.

Read full post:

Exploring CSP (Content Security Policy) using ASP.NET MVC

Test online: http://csp.somee.com/

Interesting behavior of lineWidth on Opera


I found an interesting behavior of lineWidth on Opera when setting its value very large:

context.lineWidth = 222;

This is a rectangle whose lineWidth is 222!

On Google Chrome, Firefox or IE – it doesn’t act like Opera!

If you want to test it quickly, open my tool: Canvas Designer

Selectrectangle” from tool-box; set lineWidth=222 (from tool-box) and draw rectangle! (You must do this in Opera!)

Relative Points vs. Absolute Points


Relative Points:

In simple words, points that are relative to each other are called relative points.

 Absolute Points:

Absolute points contain exact values.

I started using the concept of “Relative Points” while within my first tool “Curvature” (I continued using it in “Canvas Designer“!) – where I allowed end-users to get auto-generated code in relative/absolute formats. Relative points helped them move/drag shapes easily by just changing two objects: x and y. (x-y coordinating system!)

My all tools contain this feature and personally I use it in my real experiments and projects, too.

Relative points help you in complex animations like flying bird, scene movement (rolling camera), rocket fire or any other kind of animating experiment!

See an example: http://muaz-khan.github.com/Everything/Canvas/Experiments/Flying-Bird/

The process of “Relative Points”:

I get topmost x-y coordinates and then I extract all other points from those coordinates accordingly.

In case of additional complex shapes like Bezier/quadratic curves, I get topmost four points (one starting point, two control points and one ending point) and I set these values to four variables and use them accordingly. You can see it in action in my tool “Curvature“.

———————————–

An absolute point specifies a unique point on the screen as measured from the top-left corner of the screen.

The difference between the two types of coordinates is their origin.

Absolute coordinates are always measured from the origin (top-left corner of the screen or a specific object), and relative coordinates are measured from the current position (or a specific position), where this might be.

Following statement draws a line using absolute coordinates:

context.moveTo(20, 20);

context.lineTo(500, 500);

Following statement draws a line using relative coordinates:

var x = 20, y = 20;context.moveTo(x, y);
context.lineTo( x + 480, y + 480);

Relative coordinates are using frequently in drawing closed shapes, be it’s easier to define an endpoint by its distance from the previous one.

http://muaz-khan.github.com/UseMe/


Just designed a simplest project: UseMe

UseMe allows you to compare features side-by-side or search any feature as quickly and easily as possible!

Features are relevant to HTML5CSS3 and JavaScript specifications (also WebGL/SVG etc.)

Data has taken from +caniuse.com (awesome website!)

If I misused any feature; please let me know in the case.

I wanna make its design awesome using Canvas 2d API but my exams are about to starts (college exams) that’s why I’m early releasing a simplest version of UseMe.

Some individual features:
❶ http://muaz-khan.github.com/UseMe/#Canvas
❷ http://muaz-khan.github.com/UseMe/#WebGL
❸ http://muaz-khan.github.com/UseMe/#Video

Some features comparatively:
❶ http://muaz-khan.github.com/UseMe/#Canvas/vs/WebGL
❷ http://muaz-khan.github.com/UseMe/#Audio/vs/Video
❸ http://muaz-khan.github.com/UseMe/#requestAnimationFrame/vs/Canvas

https://github.com/muaz-khan/UseMe

Related: https://plus.google.com/100325991024054712503/posts/3A826CiDJzp

Dragging/Moving shapes smoothly using Canvas 2d APIs


Did you ever write code to drag or move shapes using Canvas 2d APIs? If you did, then didn’t you ever face a situation (an unexpected behaviour) when you drag or move a shape (e.g. circle, rectangle, image, Bezier cubic/quadratic curve, etc.)?

This post helps you write code to drag or move shapes as smoothly and accurately as possible using HTML5 Canvas 2d APIs.

Read full blog post

Dragging-or-Moving-Shapes-smoothly-using-HTML5-Canvas-2D-APIs

Curvature: HTML5 Canvas Curves Generator/Tool


Today I am happy to announce the release of Curvature: a tool lets you design curves using Canvas 2d APIs!

Curvature lets you draw unlimited Bezier curves and also generates exact code for you in two formats:

1) Absolute Coordinates

context.moveTo(200, 300);

context.bezierCurveTo(200, 300, 400, 500, 600, 700);

These are absolutely positioned points/coordinates.

Now let’s make an assumption: you had drawn one hundred (100) curves. Could you easily move all curves (as they are) on any portion of the screen?

The answer is: No, never. Not so easy!

Why it is not easy to move absolutely positioned coordinates on the screen?

You are drawing Bezier curves; not a simple line, arc or rectangle! For Bezier curves you have to understand its two control points and one ending point.

Canvas 2d API for Bezier curve looks like this:

CanvasRenderingContext2D.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y);

So what is the solution? The solution is relative positioned coordinates. If you had drawn hundreds of thousands of curves; no matter; Curvaturewill do all job for you!

2) Relative Coordinates

/* First curve where we set default values for x and y ! */

/* All subsequent curves will be extracted from these two objects! */

context.moveTo( x = 359, y = 319 );

context.bezierCurveTo( x + 25, y – 164, x + 191, y – 169, x + 285, y – 57 );

// Second Curve

context.moveTo( x , y  );

context.bezierCurveTo( x + 25, y – 164, x + 157, y + 51, x + 285, y – 57 );

// Third Curve

context.moveTo( x , y  );

context.bezierCurveTo( x + 25, y – 164, x + 234, y – 256, x + 285, y – 57 );

As you saw in the above code; when we call context.moveTo Canvas 2d API first time; we initialize default position for two variables or objects: x and y.

All subsequent values/points are relative to these two objects.

Changing them will affect all others accordingly.

How relative positioned coordinates can helps me?

Just copy auto generated code and you have to change only two points or coordinates or values:

x = e.pageX    // or whatever

y = e.pageY      // or whatever

Curvature auto-generates code for you! – Just copy and you are done!

Just draw more than one Bezier curves copy auto-generated code and you are done! Happy!!!

Try the tool:

https://canvature.appspot.com/

Just try! – Don’t hesitate to feedback! – You are most welcome!

You feedback may help me bring something better!

Cross-Origin requests and ASP.NET MVC


We can initiate cross-domain request in our webpage by creating either XMLHttpRequest object or XDomainRequest object. End user’s web-browser will request data from the domain’s server by sending an “Origin” header with the value of origin. If server responds with an “Access-Control-Allow-Origin:* | Origin” then we are permitted to access data; otherwise response will be unauthorized request.

Because we’ve to handle our server response for allowing cross-origin requests; we’ll use BeginRequest event handler in the Global.asax file for adding “Access-Control-Allow-Origin” header in our response.

HttpApplication.BeginRequest event occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request. The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader(
                "Access-Control-Allow-Origin", "*");    /* HttpContext.Current.Response.AddHeader(
      "Access-Control-Allow-Origin", 
      "http://AllowedDomain.com"); */
}

Asterisk (*) symbol indicates that request is public; however for the sake of security; we can allow a specific domain. In that case, the server will check whether request’s “Origin” header matches with domain-name that we allowed. So server will block unauthorized requests as soon as possible.

You can validate requests action-level by creating an attribute inherited to “ActionFilterAttribute” and allow only one action method to be accessible from cross-domains.

Support of Cross Browsers

Cross-Origin requests supported on IE8 (Windows 7 version),
Safari 4+
, Chrome and Firefox 3.5+ web-browsers. Preflight or Credential requests are supported on Firefox 3.5+Safari 4+ and Chrome web-browsers; IE8 doesn’t support them. You’ve to use XDomainRequest object for supporting IE8+ for cross-origin requests. IE6 and IE7 are not
supporting cross-origin requests.

For more details: please read Nicholas C. Zakas‘s article: Cross-domain Ajax with Cross-Origin Resource Sharing

Possible Attacks

Same origin used by web browsers
has a most significant protection again attack; however, cross origin requests are mostly vulnerable to attack.

  • CSRF attack: Cross-Site Request Forgery attack. CSRF interacts
    with user credentials and do malicious stuff on behalf of the user. It mostly applied to email accounts.
  • XSS attack: Cross-Site Scripting attack occurs to inject malicious
    data with POST/GET messages.
  • DNS Rebinding attack is interaction with DNS hostnames and networks address. Hacker injects malicious code and executes it; on the server side; server consider hacker’s request as authentic request because hostname matches.
  • Spoofing and re-direction attacks are mostly applied
    to cross-origin requests because server heavily relies upon HTTP headers to determine which site can access resources as well as what action they are permitted to do.

For cross-origin requests’ security: “Ensure user authority cannot be misused or compromised“.

A while ago, I wrote an article “ASP.NET MVC security and hacking: Defense-in-depth“, in which I talked about XSS and CSRF attacks. All of those attacking techniques also apply to cross-origin requests.

There is no definitive way to protect your cross-origin requests however; you can make your requests harder to attack by using some techniques as Google,
Twitter and Facebook are doing with their cross-origin APIs like Twitter‘s tweets APIs; Facebook‘s live stream and comments APIs.