Table of Contents
Seeing today’s surveillance tecnologies, it can be concluded that there is a srongly growing industry trend towards replacing analog CCTV (Closed-Circuit Television) with IP (Internet Protocol) systems. Concerning to the fact that some level of protecting homes, working places, possessions and personal safety is inevitable, I’m more and more interested in building customized IP camera solutions. That’s why I’m going to outline one of the most important fields of IP camera programming in the form of this article.
Although any IP camera allows you to view its image in a webbrowser, it doesn’t enable to integrate that into your own website. In this article I’ll show how to build live IP camera streaming into your website to be able to monitor the area that is under video surveillance.
For protecting your property by installing an IP surveillance system, a high-quality security IP camera is essentially needed. An IP camera (also called ’network camera’) is a networked digital video camera that transmits data over Internet Protocol. IP cameras are most often used for IP surveillance, a digitized and networked version of closed-circuit television (CCTV). IP cameras use the Internet Protocol used by most Local Area Networks to transmit video across the networks in digital form. It can be transmitted through the public Internet, which allows you to view your camera via any broadband connection available via PC or smartphone.
An IP camera has several benefits over analog technology. One of the greatest advantages is that IP cameras allow remote administration from any location. IP cameras has the ability to easily send images and video anywhere with an Internet connection. Progressive scanning enables better quality images extracted from the video, especially for moving targets. Some further benefits and functionalities: digital zoom, adjustable frame rates and resolution to meet specific needs, two-way communication, lower cabling requirements, the ability to send alerts if suspicious activity is detected, support for intelligent video, etc.
Before purchasing an IP camera, take a little time to discover the IP camera market and select the best one based on your needs. Regardless of their usage, reliability and image quality are the main charasteristics that differentiate good cameras from bad ones. And the features, of course, they come with determine their functionality. (And the functionality determines what kind of developments can be possible in the future, since if your camera doesn't support the required functionality, then you won't be able to implement that on your own.) You can find many comparisons and reviews on the Internet that helps you to choose the best device. For instance, the following figure illustrates some of the most powerful IP network cameras according to the Top10thebest’s review:
Some of the most powerful IP network cameras - Source: 1.
In order to address issues of standardization of IP video surveillance, the Open Network Video Interface Forum (ONVIF) industry group has been established in 2008.
ONVIF is an IP-based security standard. Quoting of the the official website of ONVIF: ’ONVIF (Open Network Video Interface Forum) is an open industry forum for the development of a global standard for the interface of IP-based physical security products.’ ONVIF is established to act on behalf of the members to facilitate the development of a global open standard for the interface of IP-based physical security products. (Some of the members: AXIS Communications, Bosch, Canon, Cisco, LG, Panasonic, Samsung, Sony, Synology, etc.)
On this basis, ONVIF standardizes communication between IP-based physical security; enables interoperability between IP-based physical security products regardless of manufacturer and it is open to all companies and organizations.
The ONVIF specification defines a common protocol for the exchange of information between network video devices including automatic device discovery, video streaming and intelligence metadata.
The ONVIG logo - Source: 4.
Now, after studying the technical background of IP surveillance systems, it’s time to start your IP camera project. To be able to broadcast live IP camera stream to your website, you will need the followings: (1) Webserver, (2) ONVIF SDK, (3) IDE for C# programming. Okay, now let’s see what you need to do with the previous three software.
Concerning that this application will be able to display your IP camera image on a website, a webserver is essentially needed. In order to reach my website in a browser, I used Apache that can be downloaded from the official website of Apache. After you have installed the webserver, you need to establish connection between your IP camera and the webserver. The most simple way for this purpose, if you download my FlashClient.zip source code then copy and paste all contents of its bin-debug folder into the WWW folder of the Apache.
In order to implement any kind of IP camera software there is a need for an IP camera SDK that supports ONVIF. For this purpose I used Ozeki Camera SDK that is based on ONVIF standards so it’s compatible with other standard-based products. You can download the SDK from its official website. For using this SDK the .NET Framework components required to run on the target machine architecture and OS. So is is also needed to download and install the Microsoft .NET Framework 4 web installer package.
As I always use Microsoft Visual Studio for programming in C#, I also use this IDE for this project. It can be obtained from the official website of Microsoft. Since in case of this application it doesn’t needed to display the IP camera image in a Windows Forms Application, it’s enough to create a Console Application. For this purpose you need to create a new Visual Studio project by clicking on the ’New project’ icon. Now you need to add the DLL file (provided by the ONVIF SDK) as a reference to your project. Now only one setting left to do in order to avoid any problems: click on the Project menu and select the [YourApplication'sName] Properties element. After right clicking on the first tab there is an option, called ’Target framework’. Make sure that this setting is ’.NET Framework 4.0’.
Okay, now your system’s ready to build your own IP Camera project.
Now I’m going to show all of the classes that are essentially needed to be able to display the image of your IP camera in your webbowser. Accordingly, three classes will be introduced: MyMediaGateway.cs
; MyClient.cs
and Program.cs
.
Below you can see the MyMediaGateway
class that allows your application to build the connection between your Console Application and your webserver. This way, you will be able to send data from your website to your C# application. As you can see below, when the application is running it is possible to forward the captured image of the camera to the HTML interface of your website:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ozeki.MediaGateway;
using Ozeki.Media.IPCamera;
using Ozeki.MediaGateway.Config;
using Ozeki.MediaGateway.Service;
namespace Display_IP_Camera_Stream_On_Website
{
public class MyMediaGateway : MediaGateway
{
private Dictionary<IClient, MyClient> clients;
private IStreamService _streamService;
public event EventHandler<EventArgs> ClientCountChange;
public MyMediaGateway(MediaGatewayConfig config)
: base(config)
{
clients = new Dictionary<IClient, MyClient>();
}
#region MediaGateway methods
public override void OnStart()
{
base.OnStart();
_streamService = GetService<IStreamService>();
Console.WriteLine("MediaGateway started.");
}
public override void OnClientConnect(IClient client, object[] parameters)
{
Console.WriteLine(client.RemoteAddress + " client connected to the server with " + client.ClientType);
if (clients.ContainsKey(client)) return;
clients.Add(client, new MyClient(client, _streamService));
ClientChange();
}
public override void OnClientDisconnect(IClient client)
{
var disconnectedClient = GetClient(client);
if (disconnectedClient == null)
return;
disconnectedClient.DisconnectCamera();
clients.Remove(client);
ClientChange();
}
private void ClientChange()
{
var handler = ClientCountChange;
if (handler != null)
ClientCountChange(this, new EventArgs());
}
#endregion
#region Client invokes
public void CameraConnect(IClient client, string uri)
{
Console.WriteLine(client.RemoteAddress + " client IP camera connect " + uri);
var myClient = GetClient(client);
if (myClient == null)
return;
myClient.ConnectCamera(uri);
}
public void CameraDisconnect(IClient client)
{
Console.WriteLine(client.RemoteAddress + " client IP camera disconnect.");
var myClient = GetClient(client);
if (myClient == null)
return;
myClient.DisconnectCamera();
}
#endregion
MyClient GetClient(IClient client)
{
return !clients.ContainsKey(client) ? null : clients[client];
}
}
}
As the previous and the next code snippets show, the camera image transmission is based on the MyClient
class that is used by the MyMediaGateway
class. Below you can see the MyClient
class that contains all the necessary methods and members that are needed to build the IP camera connection and to stream its image to your C# application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ozeki.Media.MediaHandlers;
using Ozeki.Media.IPCamera;
using Ozeki.Media.MediaHandlers.IPCamera;
using Ozeki.MediaGateway;
using Ozeki.MediaGateway.Service;
namespace Display_IP_Camera_Stream_On_Website
{
class MyClient
{
private IClient _client;
private IStreamService _streamService;
private IMediaStream _mediaStream;
private MediaGatewayVideoReceiver _videoReceiver;
private MediaConnector _connector;
private IIPCamera _camera;
public MyClient(IClient client, IStreamService streamService)
{
this._client = client;
this._streamService = streamService;
_connector = new MediaConnector();
}
internal void ConnectCamera(string uri)
{
if (String.IsNullOrEmpty(uri)) return;
_camera = IPCameraFactory.GetCamera(uri, "admin", "admin");
_camera.Start();
if (_camera == null)
{
NotifyCameraStateChanged(IPCameraState.Error);
return;
}
NotifyCameraStateChanged(IPCameraState.Connected);
var playStreamName = Guid.NewGuid().ToString();
_mediaStream = _streamService.CreateStream(playStreamName);
_videoReceiver = new MediaGatewayVideoReceiver(_mediaStream);
_connector.Connect(_camera.VideoChannel, _videoReceiver);
OnPlayRemoteStream(playStreamName);
}
internal void DisconnectCamera()
{
if (_camera == null) return;
_camera.Disconnect();
_connector.Disconnect(_camera.VideoChannel, _videoReceiver);
_videoReceiver.Dispose();
_mediaStream.Close();
NotifyCameraStateChanged(IPCameraState.Disconnected);
}
private void NotifyCameraStateChanged(IPCameraState state)
{
try
{
_client.InvokeMethod("OnCameraStateChanged", state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
void OnPlayRemoteStream(string streamName)
{
try
{
_client.InvokeMethod("OnPlayRemoteStream", streamName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
And finally take a look at the Program.cs
class that controls the whole process. As you can see below, in the Main
section you need to create a MediaGateway
type of object and add the FlashConfig
element. (The above-mentioned Flash content contains all the rest of the C# source code.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ozeki.Media.MediaHandlers.IPCamera;
using Ozeki.Media.MediaHandlers.IPCamera.Types;
using Ozeki.Media.Video;
using Ozeki.Media.Video.Controls;
using Ozeki.MediaGateway.Config;
namespace Display_IP_Camera_Stream_On_Website
{
class Program
{
static void Main(string[] args)
{
var config = new MediaGatewayConfig();
config.AddConfigElement(new FlashConfig { ServiceName = "IPCameraServer" });
MyMediaGateway _mediaGateway = new MyMediaGateway(config);
_mediaGateway.Start();
Console.Read();
}
}
}
In order to avoid any problems, I recommend you to add System.Configuration.dll as a new reference to your project in Visual Studio. It provides access to configuration files for client applications.
Okay, now take a look at the Graphical User Interface that can be achieved by using my code example. After you have built and run your project succesfully, you can see something similar on your webbrowser like the following figure. It demonstrates how simple it is to monitor your workstation through the Internet in a Chrome webbowser. As you can see, it is now possible for me to check my table and my PC even if I'm out of the house.
ONVIF IP camera streaming to a website - Source: Self made
As a small supplement, in this section I’m going to show how to capture still images from your broadcasted IP camera on a website. Due to this functionality you will be able to take camera snapshots through web-broadcasting and display this image on your website. The snapshots captured on your website will be saved and stored automatically into the folder where your webserver has been installed to.
To make the implementation of this feature easier, I attached a new source code that has been created especially for this functionality. So if you are interested in this solution, please download the SnapshotDuringWebBroadcasting.zip file, that - in addition to the source code - contains a new flash-based content. After downloading it, you need to overwrite the previous files with this content.
Okay, it's time to see how to capture still images during a web-broadcasting using C#.NET. First of all, please add one more new item to your References in Visual Studio in the usual way: right-click on ’References’, then ’click on ’Add reference’. Here click on the ’.NET’ tab, then choose and add the System.Drawing.dll file to your references.
Now let’s see the changes you need to carry out for implementing this functionality. In the MyMediaGateway.cs
class you need to add a path as follows. It allows you to find out easily where the snapshots will be found after capturing. After this modification, the MyMediaGateway
class should start with the following section:
private Dictionary<IClient, MyClient> clients;
private IStreamService _streamService;
private string path;
public event EventHandler<EventArgs> ClientCountChange;
public MyMediaGateway(MediaGatewayConfig config, string path)
: base(config)
{
clients = new Dictionary<IClient, MyClient>();
this.path = path;
}
Having done the previous modification, let’s continue the development by rewriting the Client invokes
region. It should contain the CameraImageCapture
method as you can see below:
#region Client invokes
public void CameraConnect(IClient client, string uri)
{
Console.WriteLine(client.RemoteAddress + " client IP camera connect " + uri);
var myClient = GetClient(client);
if (myClient == null)
return;
myClient.ConnectCamera(uri);
}
public void CameraImageCapture(IClient client)
{
var snapShotImage = MyClient.Snapshot.TakeSnapshot().ToImage();
snapShotImage.Save(path + "\\snapshot.jpg");
}
public void CameraDisconnect(IClient client)
{
Console.WriteLine(client.RemoteAddress + " client IP camera disconnect.");
var myClient = GetClient(client);
if (myClient == null)
return;
myClient.DisconnectCamera();
}
#endregion
Concerning that the MyClient.cs
is responsible for creating the IP camera connection and for streaming its image to your C# application, leave this class unchanged. Let’s move on to the Program.cs
class where you need to carry out some modifications. After inserting the necessary additional lines, it should look like as follows:
class Program
{
static void Main(string[] args)
{
var config = new MediaGatewayConfig();
config.AddConfigElement(new FlashConfig { ServiceName = "IPCameraServer" });
Console.Write("Please give the path to the server's Main.html file:");
var path = Console.ReadLine();
MyMediaGateway _mediaGateway = new MyMediaGateway(config, path);
_mediaGateway.Start();
Console.Read();
}
}
After you have done all the necessary modifications succesfully, let’s run the application. When you start the streaming in order to view the camera image in your webbrowser, you can see the same web GUI as before, but a new button can be also seen. This is the 'Capture image' button that can be used to capture the current camera image. After pressing this button, the snapshot will appear automatically in the webbrowser and it will be saved on your PC as well.
ONVIF technology provides a great way for improving your security system by implementing different kind of IP camera solutions. This article demonstrated how to build live IP camera streaming into your website to be able to monitor the area that is under video surveillance through your website. It makes remote surveillance possible as well. In addition to surveillance/ security systems, I can also recommend this project if you’re a video blogger or an ERP system operator. For using my source code, the following prerequsites need to be installed on your PC: a webserver (like Apache), an ONVIF SDK (like Ozeki Camera SDK) and an IDE for C# programming (like Microsoft Visual Studio).
I learned a lot of interesting things about ONVIF technology while writing this article. I discovered how extensive its fields of use. I'm afraid there's far more in this topic such as motion detection, video analytics, etc. So I've dug deeper and I created a new camera application: a camera video recorder.
If you're interested in recording your camera's stream, take a look at this article in which I show how to record audio and video stream into MPEG-4 file format by using C# to be able to save and store what happened in the area that is under video surveillance:
How to Create a Video Recording Application (NVR/DVR software) for an ONVIF IP Camera using C#.NET:
http://www.codeproject.com/Tips/826531/How-to-Create-a-Video-Recording-Application-NVR-DV
To find out more on how to archive events in a video surveillance system, check out the following article that explains briefly how to take an ONVIF IP camera snapshot and save this image as a JPG file by using C# to be able to preserve/share the most important moments:
How to Create ONVIF IP Camera Snapshot as a JPG image file by using C#.NET:
http://www.codeproject.com/Articles/829261/How-to-create-ONVIF-IP-camera-snapshot-as-a-JPG-im
In this section I listed all the webpages that I used as resources to write this article. Below you can also find the direct download links for the necessary software:
1. http://whatis.techtarget.com/definition/IP-camera
2. http://en.wikipedia.org/wiki/IP_camera
3. http://top10thebest.com/top-10-best-wireless-ip-network-cameras-2014-reviews/
4. http://www.onvif.org/
5. http://httpd.apache.org/download.cgi
6. http://www.camera-sdk.com/p_13-download-onvif.html
7. http://www.microsoft.com/en-US/download/details.aspx?id=17851
8. http://www.microsoft.com/en-us/download/details.aspx?id=43721