Name: William Ryan

Supervisor: Dr. Abdur Rahman

 

 

 

 

Internet Home Video Security System

 

 

 

 

 

 

 

UNIVERSITY of LIMERICK

OLLSCOIL LUIMNIGH

 

 

 

 

 

FINAL YEAR PROJECT REPORT 2002

 

 

 

 

 

 

 

 

 

Submitted in part fulfilment of the requirements of a Bachelor of Engineering, Computer Engineering Degree, to the Department of Electronic and Computer Engineering, University of Limerick.

 


 

NAME:                           William Ryan

 

 

ID:                                   9841377

 

 

COURSE:                        Computer Engineering

 

 

                                                DEPARTMENT:            Electronic and Computer Engineering

 

SUPERVISOR                Dr. Abdur Rahman

 

 

DATE                              18/04/2002

 

 

SIGNED                          _______________

                                         William Ryan

 

Acknowledgements

 

I would like to thank the following people who all contributed to the project in some way:

 

 

My FYP supervisor Dr. Abdur Rahman for all his help.

 

Mr. Eoin O’ Connell in the DATACOMMS lab up in B2 for his help installing the software.

 

All my family and friends for the generous support I received.

 

 

Go raibh mile maith agaibh go leir.

 


 

Abstract

 

Home security is a major issue in this day and age. People seem to be going to greater cost and longer lengths to protect their homes and belongings. There are many different means people use to do this, security alarms, more secure windows. A lot of these preventative measures are fine but the reality is that when thieves get away there is little hope of recovering the missing items unless they can be recognised.

It’s a big industry and many people and businesses, unknowingly, pay over the top prices for “peace of mind” products that could be easily replaced by equipment they already have. CCTV systems can help in the capture of the perpetrators but these are generally very expensive and can easily be replaced by existing resources. With an ordinary PC and web cam or digital camera, and the right software any home or business can be protected effectively and efficiently with very little cost.

With this in mind, I set out to develop a piece of appropriate software to do this, the result being the “HomeCam Internet Security System”.


 

Table of Contents

Acknowledgements.. 3

Abstract. 4

Table of Contents.. 5

 

1. Introduction.. 6

1.1 Changes since Interim report 6

1.2 Main tasks. 8

 

2. Technology.. 9

2.1 PC. 9

2.2 Logitech Quickcam® Pro 3000. 10

2.3 TrackerCam, TrackerPod and software. 11

2.4 Microsoft Visual Basic. 11

2.5 ezVidC60.ocx Visual Basic control 13

2.6 Microsoft Visual C++. 13

2.7 Borland C++. 15

2.8 MiniMax web server 17

2.9 File formats used. 18

 

3. Implementation.. 20

3.1 Streaming overview. 22

 

4. Why do we need ‘a level of tolerance’?.. 24

 

5. Explanation of the Image Processing algorithm... 26

5.1 8-colour setting. 26

5.2 64-colour setting. 26

 

6. User interface and manual 28

6.1 Application: HomeCam.exe. 30

6.2 Web and CGI Pages. 43

6.3 Using TrackPod in conjunction with HomeCam.. 47

6.4 Data files. 48

 

7. Conclusions.. 51

 

8. Discussion.. 53

8.1 Problems with the project 53

8.2 Future developments. 54

 

References.. 56

 

Appendices.. 58

Visual Basic Code. 58

Visual C++ Code for C_Bmp.dll 84

Code using Borland C++, Version 5.01. 87

 

1. Introduction

 

 

The aim of this project is to produce a piece of software which integrates an Internet-video based Home security system using an ordinary PC and a web cam.

On detection of movement in a room by the web cam, save a video clip of the scene, compress it, upload to a web server (or web folder). The user should then be able to access these home video clips from any Internet terminal via video streaming.

 

1.1 Changes since Interim report

In last Semester’s report, I outlined the technology I would be using to develop this system. There have been a number of significant changes since then.

 

At the time, I outlined that I would be using the TrackerCam®1 tripod and software to implement the image and video capturing capabilities of the system. On obtaining this product, however, I found it to be largely unsuitable for this purpose. Its functionality did not allow for proper image analysis as it only captured images in the compressed JPEG format. An uncompressed image format is more practical. However, it does has remote control capabilities, which allow a pre-registered user (or guest) to login to the home PC over the Internet, from any remote terminal and move the camera to face any desired location in the room so one can view live pictures of your house from any location in the world. The camera is fixed to a motorised tripod stand which makes this possible. This can be used supplementary to the HomeCam application and together give a very strong and dynamic system.

 

Instead, I will be using Microsoft® Windows2 own capturing system, VfW (Video for Windows). This allows for powerful image and video capture capability and means that the user can decide exactly when the precise moments where capture starts and ends. VfW supports AVI video files and uncompressed DIB (windows bitmap) image file format among many others but these are the formats that the HomeCam system uses.

 

Configuration of the captured video images can also be easily achieved. There are options to configure video size, quality, brightness, audio (if required) and compression values can also be specified. VfW can cope with up to nine separate capture devices simultaneously, so in theory, up to nine different cameras can be used to create an effective premises-wide surveillance network. In general, there are only two USB ports installed on computers so serial ports and external power supplies would probably have to be used to use more than this.

 

1.2 Main tasks

The main details that had to be decided upon before the to complete this project are as follows:

 


 

2. Technology

The following components were decided upon in undertaking the project

 

 

2.1 PC

Any recent home PC will do, possibly 500MHz+, with Windows 98, Me, 2000, XP (not tested on XP). The Logitech Quickcam3 device driver is only compatible with Windows versions 98 and up and must have at least one Universal Serial Bus (USB) installed, two if TrackerCam1 also installed. USB ports allow devices to be powered directly from the PC source. A sufficient current is supplied to these devices so they do not need to be connected to a power source themselves. Must have Windows Media Player installed to play AVI files.

 

                                    

                connector into the computer's USB port                        USB port12

 

2.2 Logitech Quickcam® Pro 30003

This is the camera that came with the TrackerCam1 tripod. (above is a picture). This USB powered camera can take pictures with up to 640x480 resolution. Includes a built-in microphone for optional audio capture.

The Logitech Quick Cam Pro 3000, is the latest in their ‘Pro’ range and, for a web cam, gives pretty impressive results. Best capture quality, however, is still in natural light. For best contrasting, try to use in a smaller rather than a larger area.

 

TrackerPod® and Logitech QuickCam®1

 

2.3 TrackerCam, TrackerPod and software

TrackerCam and TrackerPod1 add remote robotic positioning capability to PC video cameras. The system consists of a small robotic tripod (TrackerPod), on which the Logitech Quickcam®3 camera sits, and Artificial Intelligence software (TrackerCam) to control camera movement from the computer and remotely over the Internet. With the system installed, the camera can move around, panning, tilting and zooming under the computer's control. TrackerCam's specialty is automatic tracking, which means locking onto a subject in the camera's view and then automatically following them with the camera so that they stay in view. These features will complement HomeCam functionality.

 

2.4 Microsoft Visual Basic2

This environment was chosen to create the GUI. Also some of the general operation code is written in Visual Basic. VB also has some extremely useful and easy to use functions and interacts very easily with dlls to create a very powerful application based language. This is a highly object-oriented language but its graphic nature allows easy interfacing between objects. It allows users to create very attractive applications because of its drag and create philosophy. It is a very trivial matter to set a timer in VB. By adjusting this time interval, we can create longer or shorter gaps between one image capture and the next during surveillance.

Overview of VB code

Behind each of the Visual Basic forms lies the code it needs to function. There is also a separate section of code called the module (not compulsory). This usually contains code which may need to be called more than once from multiple forms or maybe just for tidiness sake. It is also desirable to declare any global variables and external (dll) functions here.

External function calls to dlls, e.g. kernel32.dll or C_Bmp.dll can be made in Visual Basic by declaring the external function as such. VB parameters can then be passed in. The values must be explicitly marked as being passed by value or by reference (the default is by reference). Values can then be returned from the dll.

Having used this throughout much of my Coop, it was the natural choice.

 

Declaration reference

A Function returns a value of specified type.

A Sub does not return a value.

 

Variables, subs or functions declared as:

·        Public – globally accessible

·        Private – accessible within a form.

·        Dim – accessible within a Sub or Function.

 

To comment out a line, the “ ’ ” character is used.

 

Uses in this project:

GUI, Opening - deleting - closing files, sending email, getting IP and checking if the application is running by checking processes.

 

2.5 ezVidC60.ocx5 Visual Basic control

Windows contains a powerful set of video file functions called the AVIFile API ('Application Programming Interface').  The AVIFile API set of functions is part of an even larger API called the Video For Windows API. This VB component for video capture under Win32, written by Ray Mercer5, utilises VfW and has the same functionality as C/C++’s VfW.H.

VideoForWindows (VfW) was originally released as an add-on to the Windows 3.1 API. It added support for video capture hardware and enhanced the limited Win16 GDI functions enough to allow video playback at low resolutions. The major drawback of this technology is, however, that it has a maximum file size of 2 Gbytes. This is because it originated on a Win16 based architecture (Windows 3.1 can only address up to 2 Gbytes of virtual memory).

Microsoft have since replaced VfW with a true Win 32 bit architecture technology, ActiveMovie, thus removing the 2 GByte limit.

 

Uses in this project:

Bitmap image capture, AVI Video capture.

 

2.6 Microsoft Visual C++2

Microsoft Visual Studio was used in this project to write a dll (Dynamic link library) to be call from the Visual Basic code. This dll was written to process the byte-by-byte analysis of the captured bitmap images (See bitmap description). Visual basic code was found to be too slow for this process so the obvious language choice where speed is concerned is C/C++. Analysis for a 160x120 resolution bitmap (approx.57,000 bytes) took about 4 seconds in VB, too long for a real time application, whereas in C++ it occurs almost instantaneously.

Overview of C_Bmp.dll

Image processing can mean extremely lengthy program execution times. Each pixel must be analysed and the data then processed. This cold mean loops iterating up to hundreds of thousands of times. Therefore we need a programming language capable of high-speed execution times. C/C++ fits the bill perfectly. The easiest way of accessing C++ function from the VB interface was to compile the C/C++ functions as a dll and make external calls from VB.

 

The code used to create C_Bmp.dll (dynamic link library) consists of normal C functions. What sets the dll apart from usual C code is that no main function is needed. This is because the dll itself is not executed and therefore does not need the starting point that the main function provides. Rather the individual functions are called from external sources; in the case of the project, VB.

The _stdcall function keyword is also used. The _stdcall keyword, defined as CCONV in this project, forces the compiler to generate function calls using the Standard calling convention12. The resulting function calls are smaller and faster. Functions must pass the correct number and type of arguments; this is unlike normal C use, which permits a variable number of function arguments. Such functions comply with the standard WIN32 argument-passing convention.

C_Bmp.cpp requires C_Bmp.def to function properly. This defines the functions that export values from the dll. The library file relating to the dll being used is also declared at the top of C_Bmp.def.

To compile the dll using Microsoft Visual Studio, open up this application from the start button in Windows and choose the create dynamic link library option from the list of project types.

An extremely useful feature of Visual Studio is its ability to debug the code from the external application that will be using the dll. Choose the name of the desired program, in my case, HomeCam.exe, in the project – options – debug menu. This is not without its bugs however. To debug, a new PCH (pre-compile header) must be created. The problem is that the old fails to be over-written unless it is deleted first. This caused major problems early in the project until the fault was figured out.

 

Uses in this project:

Image processing in dll, creating mask.

 

2.7 Borland C++6

This environment was chosen to create the CGI (Common Gateway Interface) scripts used to display the videos created by the application on the web. I used the dir.h library, and functions findfirst() and findnext(), which are not available in Visual Studio, to search the video directory and display them on web pages in html form. These functions search a given directory for a given filename eg. “*.avi” and “Go.avi”. This gives a very useful dynamic feature to the web pages. Data can also be sent between CGI pages using the GET method from html forms.

Overview of CGI code

Common Gateway Interface is a method which allows server-side executions dynamically create client-side web pages. CGI is not strictly a programming language. In fact, any programming language can be used to create a CGI program. As I have previously stated, I used C because this is the language I am most familiar with. PERL is also widely used for this purpose.

All we must do to let a browser know that it is a CGI script/program is to in included the following as the first line of the code:

            printf("Content-type: text/html");

This lets the browser know that all the data following this statement is html code.

If the line printf("<head> My Page </head>"); is included in the C code it appears on the html page as:

            <head> My Page </head>

In this way, we can incorporate the functionally of C code, i.e. For loops, If statements, into a web page.

To create the CGI program just compile the C code as normal and the outputted EXE can be rested on a web server. Some servers require a cgi-bin but this is not the case for MiniMax.4

 

Uses in this project:

HomeCam’s CGI script based Web pages.

 

2.8 MiniMax4 web server

This is a secure, fast and small (<60k) http/1.1 web server for Windows-based computers. It is ideal for a home PC or small company. MiniMax is free for corporate, personal, academic or government use and a license to distribute it is available. Visual C++ source code is also available. Installing MiniMax is very easy, and it keeps a low memory profile.

 

Installation: Create a shortcut to MiniMax.exe with the path to the web root on the command line, and the path to the log folder in the "Start In" folder. For example:

 

Shortcut:         "c:\WEB\Binary\MiniMax.exe" c:\WEB\WWWRoot
Start In:           "c:\WEB\logs"

 

Running MiniMax11

·        Any files that do not begin with "_" in the root folder or and subfolder of the root will be available to browse.

·        Any files beginning with "_" are hidden files that cannot be browsed.

·        Any executable files that do not begin with "_" in the folders will execute as CGI programs. (Executable files are defined in the Windows environment variable PATHEXT. From a DOS window type SET PATHEXT to see the list.)

·        Any executable files that do begin with "_" will not execute and can be downloaded by the browser. To allow users to download them, provide a link without the "_". For example, To allow downloads from the URL http://MyHost/MyProg.exe name the file _MyProg.exe. The underscore should not be used in the URL.

·        For URLs with no file name given, MiniMax will try index.htm, index.html, index.pl, and index.exe in that order.

Other Information:

·        MiniMax creates log files in the W3C Extended Common format. The Logfile name is MiniMaxHttpLog.txt.

·        It does not create a window, nor does it place an icon in the system tray. One may find MiniMax.exe in the task manager.

·        To close MiniMax, or to detect that it is running, run the program CloseMiniMax.exe, then click Yes or No on the pop-up window. MiniMax will make a short sound to signify that it is exiting.

·        MiniMax runs on the web port 80.

·        To see how MiniMax is licensed, run a DOS window and run 'MiniMax license'. A pop-up window will show a license summary.

 

2.9 File formats used

Why use bitmaps9?

·        They are widely use and easy to fabricate.

·        Each pixel is three ASCII characters, the first one being Red, the second, Green and the third, Blue.

·        The pixels are one long line in the file and are easily readable by HEX editors. C_Bmp.dll, coded in C++, reads in one long string and begins processing the images.

·        Pixels can easily be converted into integer triplets, for easy manipulation, and returned to character type.

 

This file format consists of a 14-byte file header and a 40-byte information header. These two headers contain information about exactly what is stored in the file and in what order.

 

Why use Avi’s10?

·        AVI stands for Audio Video Interleave and is a special case of the RIFF (Resource Interchange File Format).

·        AVI is defined by Microsoft and it is the most common format for audio and video data on PCs.

·        AVI originally was, and largely still is the de facto standard for video files.

·        The AVI file and file format is a central part of Video for Windows.


 

3. Implementation

 

The operation of the HomeCam system is relatively simple. It can be explained using the following diagram.

 

 

(1)       Video capture device.

The Logitech Quickcam pro 30003 is connected, via USB port, to the computer.

 

(2)               This is the PC where the actual database of video clips is stored. These video files are stored to the Application path/Web/WWWRoot/Videos folder (the application path is the location of the HomeCam root directory). Together, the camera and the PC’s capture card make up the video capturing tools. The HomeCam log file, which records both errors and settings changes, is located in Application path/logs/HomeCamlog.txt.

 

(3)       This represents the MiniMax web server running on port 8080 on the computer. This runs from Application path/Run Project with all of the paths defined in MiniMax.lnk (server log path and web root directory). The PC is now transformed into a web host, globally accessible over the Internet.

 

(4)7      The Internet is a computer network made up of thousands of networks worldwide. No one is in charge of the Internet. There are many organizations which develop technical aspects of this network and set standards for creating applications on it, but no governing body is in control. The Internet backbone through which Internet traffic flows, is owned by private companies.

All computers on the Internet communicate with one another using the Transmission Control Protocol/Internet Protocol suite, abbreviated to TCP/IP. Computers on the Internet use a client/server architecture.

 

Client/server diagram8

 

This means that the remote server machine provides files and services to the user's local client machine. Software can be installed on a client computer to take advantage of the latest access technology.

The Internet consists primarily of a variety of access protocols (e.g. HTTP, FTP, TELNET etc.). Many of these protocols feature programs that allow users to search for and retrieve material made available by the protocol.

CGI scripts provided server side functionality. They are treated like server side executables but provide html output in the client’s browser window.

 

(5)       The material on the host server is accessible on any terminal connected to the Internet, provided the domain name (IP address) and the password on the index page is known. The client, the user in this case, views the downloaded web pages and CGI executables in a browser window and also the streaming video files in an appropriate media player.

 

3.1 Streaming overview

It is preferred in ordinary circumstances that the video files be streamed using HTTP streaming. It might give a lesser quality output, but the fact that it is free is a major plus.

Many of the products on the market use the own streaming technology, e.g. Real Systems use their own RealServer streaming protocol which allows for multiple streaming bandwidths, i.e. 28k, 56k, T1 etc. HTTP streaming is not capable of this. Others including Windows Streaming Media Technologies offer more or less the same service. This method of streaming media is mainly used by corporations where high video and live streaming is required for, perhaps, video conferencing.

Many firewalls refuse all traffic except HTTP. The transfer of such immense amounts of data across a network can slow down the functioning of the network considerably. With this in mind it is desirable, in many cases, to restrict streaming the video files to solely HTTP to fool the firewall into thinking that it is just ordinary traffic.


 

4. Why do we need ‘a level of tolerance’?

When the two subject images are examined, percentage pixel difference between them must exceed the tolerance level for video to be captured. When attempting to describe why we need a tolerance level we must examine the images in a number of ways. For decent image analysis, the image must have the following:

 

·        Excellent contrast.

·        No apparent noise.

·        Quality, uniform lighting.

 

When any of these is missing, the quality is depleted. No matter how we try two sequential pictures will not be quite identical. To ensure we have the above conditions, we must provide the following:

 

·        Ensure that whatever camera is being used, it is properly in focus and the lens has no visible dirt or smudge on it.

·        Ensure that there is no apparent interference from outside sources, for example, electrical or electronic devices situated nearby. This is unlikely but still a possibility depending on the camera being used.

·        It is imperative that lighting be kept as constant and as uniform as possible. This means proper positioning of the camera as well as light quality.

·        Also try to avoid placing the camera facing areas of extremely high or low intensity brightness and particularly try to avoid shiny surfaces or objects.

 

Obviously, camera quality has a huge bearing on the eventual image and, like everything, generally the more expensive they are, the better. Digital cameras have a much higher level of quality than web cams and are not affected as much as by bad lighting and give much better contrast that web cams.

The camera in use for this project is the Logitech Quick Cam Pro 3000, a middle of the range web cam. It gives good results for a web cam but there is always a sight difference from one snapshot to the next. Because of this, there will always have to be a tolerance level in using this equipment of greater than zero to avoid constant video capture. No one wants huge chucks of their hard drive taken up with useless video and in-boxes plagued with never ending emails. The picture quality and tolerance level must always be checked when switching on the surveillance mode.

Every time the HomeCam application detects a change in the tolerance value, the HomeCamLog is updated, including its new value.


 

5. Explanation of the Image Processing algorithm

 

This application allows for two different image analysis settings. Either can be used effectively depending on the quality of the camera and the lighting.

As previously explained a single bitmap pixel consists of three 8-bit ASCII characters (Red, Green, Blue). Value ‘0’ implies none of this constituent colour makes up the overall pixel colour while ‘255’ implies that ‘pure green’ is a constituent.

 

5.1 8-colour setting

Initially, an integer variable ‘colour’ is defined.

This firstly analyses the ‘red’ byte of the pixel. If this value is greater than ‘127’ then the value ‘1’ is added to the variable ‘colour’.

The same is done for the ‘green’ byte but this time the value ‘2’ is added if the ‘>127’ condition is met and again for the ‘blue’ byte where ‘4’ would be added.

This gives us a colour value for the pixel in the range 0 – 7.

The corresponding pixel in the second image is also analysed in this way and if the colours are different, then the pixel is said to have changed from one image to the next.

 

5.2 64-colour setting

The 64-colour setting is implemented similarly to the 8-colour except each byte is split into four sections instead of two. This leaves us with a colour value in the range 0 – 63.

This setting is more accurate than the previous and makes the surveillance process more sensitive to changes in the room and aberrations in the image capture.

 


 

6. User interface and manual

 

Simplified flow diagram for Application capture

 


 

Explaining the above diagram in Words

(1)               Once the start-up procedures have been carried out, the application waits for the surveillance event timer.

(2)               If the surveillance process is activated and there is at least one video driver installed, then an image snapshot is taken with the web cam and saved else goto wait for surveillance event timer.

(3)               If there are more than one saved images:

·        Search the saved image folder and examine the time and date of the first found bitmap.

·        If it is found to be the most recent file then it is stored as such, if the second most recent then it is also saved as such. Otherwise, this file is disregarded.

·        Loop until no file returned, i.e. all files have been examined

else goto wait for surveillance event timer.

(4)               Delete all of the redundant images. Note that because of the method used in coding this system there should never be any more than 3 bitmap files in this folder. Therefore only one file has to be deleted at a time. This improves the overall efficiency of the application.

(5)               Compare the two most recent files and record the percentage image difference between them.

(6)               If this image difference is greater than the stored image difference tolerance level, the video capture is allowed to occur else goto wait for surveillance event timer.

(7)               Note: to quit this program, both the surveillance process and the web server must be deactivated.

 

6.1 Application: HomeCam.exe

 

The following is a guide to the layout, functionality and the backround to the application itself. Each of the nine forms one can encounter while running the program

 

The opening form: frmMain

 

 

This is the form seen on opening the application. This is where it all begins! On loading of this form, it checks to see if HomeCam.exe is already running. If it is then it tells you the number of times HomeCam is running and asks if you want to open it up again. Video for Windows allows for up to nine capture devices to run on a machine simultaneously so it is handy to know how many times the application is opened.

 

 

A number of the buttons on this form open up secondary forms. Clicking..

The forms’ details are outlined below.

 

Some, however, perform functions in there own right. Clicking..

The ON process involves the following steps:

1.      Caption changes to Surveillance ON.

2.      A snapshot is taken of the cameras view.

3.      If there is more than one image saved then the two most recent images are compared, otherwise it waits for a second image. If there are more than two images, all other image files, except the two most recent are deleted.

4.      If the percentage of pixels (each of size 3 bytes), compared to the size of the files, are greater than a percentage tolerance set in frmTol, (according to an algorithm defined in C_Bmp.dll) then a video clip begins to save. If the difference is less than the tolerance level then no motion is assumed and so no video is saved. The saved video clip has a name incorporating the following; the current year followed by the month, the day, the hour, the minute and the second the clip began to save. If desired, an email is send to the address specified in frmSetup.

5.      While the application does is inactive in saving video, lblRecStatus (the main label) should be red and display the caption “Not Recording” in plain text. If it is in recording mode, however the caption should read “Recording Video” with a green backround and bold text.

6.      All of the snapshot bitmap images stored are deleted.

7.      Steps 1 – 4 are repeated until it is stopped.

(The time between snapshots and the length of the saved video clip are saved in frmSetup)

The OFF process involves the following steps:

1.      Caption changes to Surveillance OFF.

2.      The surveillance process stops.

3.      All of the snapshot bitmap images stored are deleted.

It also checks what Windows processes are running. If it detects that MiniMax.exe is still running, then an appropriate message also appears and you will not be allowed to exit until it is switched off.

Email (MS Outlook), when checked, enables the email facility

 

frmViewVideo

 

 

This form also opens up on start-up and an information message is displayed if no video capture device is detected.

 

It displays the image of the scene currently being viewed by the camera. This is done by using ezVidC60.ocx, a Visual Basic video capture component, which uses VfW (Video for Windows) functionality.

 

This form also allows for configuration of the video and image capture. ezVidC60.ocx also performs these tasks. All buttons, except the exit button, are initially disabled. If then the currently selected video driver supports that configuration utility, then the appropriate button becomes enabled.

 

The combo-box in the top left hand corner displays all the video capture drivers currently installed on the computer. The ezVidC60.ocx display is just underneath. Moving right, we find the colour palette option-box. This allows the user to have the option for each of the captured pictures to be analysed in an eight or sixty-four colour palette (explained in code description section). Finally, on the extreme right are the functionality buttons. Clicking..

·        Configure compression displays a dialog box in which the user can select a compressor (codec) to use during the capture process. The list of available compressors can vary with the video format selected in the capture driver's Video Format dialog box. This message is most useful in the step capture operation to combine capture and compression in a single operation. Compressing frames with a software compressor as part of a real-time capture operation is too time-consuming to perform. Video compression is vital for streaming media over the Internet as uncompressed files are just too big to stream.

·        Configure format Displays a dialog box in which the user can select the video format. The Video Format dialog box might be used to select image dimensions, bit depth, and hardware compression options. This project, however, uses the 160x120 resolution bitmap (approx.57,000 bytes) as its small size allows the user to view virtually all forms at once on the screen. This does not affect the running of the application. The Video Format dialog box is unique for each capture driver. Some capture drivers might not support a Video Format dialog box.

·        Configure display displays a dialog box in which the user can set or adjust the video output. This dialog box might contain controls that affect the hue, contrast, and brightness of the displayed image, as well as key colour alignment. The controls in this dialog box do not affect digitised video data; they affect only the output or redisplay of the video signal. In the above picture (fig. 3), this is the only option to remain disabled, as the specified video driver does not support it.

·        Configure source Displays a dialog box in which the user can control the video source. The Video Source dialog box might contain controls that select input sources; alter the hue, contrast and brightness of the image; and modify the video quality before digitising the images into the frame buffer. The Video Source dialog box is unique for each capture driver. Some capture drivers might not support a Video Source dialog box.


 

frmDisplay

 

 

This form is opened by clicking the Display pictures command button on the main form. It shows the HomeCam logo by default. When surveillance is activated, it shows the two most recent pictures (bitmap images) taken. The pixel difference value is calculated by analysis of the colour of a pixel in one image to the colour of the corresponding pixel in the other image. This is done in C_Bmp.dll and is performed using the 8-colour or 64-colour palette system (outlined in code description section). The Auto Refresh check-box, when checked, updates the pictures every time a new one is saved. To still the two images currently been shown, uncheck this box.

·        Exit hides this form and frmExaminediff.

·        Difference Mask opens up a form to graphically let the user see what difference is between the images (frmExamineDiff).

·        Tol opens up a form to let the user set a value for the tolerance level. Due to aberration in the camera, there will always be slight differences between the two images even if they are expected to be identical.

Video clips will only be saved if the pixel difference value is higher than the tolerance value set.

 

frmExamineDiff

 

 

This form is opened when the Display pictures button on the main form or on clicking the Difference Mask button on frmDisplay.

frmExamineDiff displays the actual differences between the two current most recent images in the form of a mask. If a pixel is found to have changed, it is displayed here as white. If it is deemed the same colour, then black. This image, which is called ExamineBmp.bmp, is created in C_Bmp.dll where the image comparison algorithm is implemented. Clicking..

·        Close hides the form. It is also hidden when the Exit button on frmDisplay is clicked.


 

frmSetup

 

 

Here the user can make further settings changes, this time relating to

1.      The interval between surveillance snapshots. This can be any number up to 3 decimal places as the Visual Basic timers used allow for millisecond gaps. Values of one second and over give best results.

2.      The length of the film clips that the use wishes to save. This, in theory, allows for 0.001 sec to an infinitely long clip. A value 20 - 30 seconds should suffice.

3.      The email address that messages are sent to under the following instances:

·        On detection of an error.

·        On a new Video clip being saved.

·        On a new IP address being saved.

(This feature only works with MS Outlook.)

The buttons do the following. Clicking..

·        Exit hides the form.

·        Store saves the values currently displayed. These values take immediate effect, even if the surveillance is running.

·        Reset set the displayed values in the textboxes to their previous stored values.

 

frmIp

 

 

This form displays the current IP address an Internet terminal has. If the computer is not connected to the Internet, the local loop-back address 127.0.0.1 is displayed. This feature is especially important for machines with dynamic addresses. This IP address is used to create the links in the CGI scripts on the web server. The user must know at all times what the IP address is so the video files can be viewed from a remote terminal. This is achieved by sending an email, via Outlook only, to the email address specified in frmSetup, if the check box in the main form is true. The dynamic web pages (CGI scripts) can be viewed by typing the IP address in to the address toolbar in any web browser.

Here is the functionality. Clicking..

·        Exit hides the form.

·        Get current IP address executes code to evaluate the current IP address of the machine and display it.

·        Store this IP address saves the presently displayed value. An email is sent to a predetermined address with the new value.

The HomeCamLog is also updated with the data.

 

frmAvi

 

 

This form is called directly from the main form by clicking on View Avi. Here the user can view all of the avi files that are currently in the new video clips web directory. This form uses the Windows Media Player Visual Basic component to embed the media player on the form itself. A file is selected by double clicking on the desired file in the listbox.

·        Exit hides the form

·        Refresh gets the updated list of avi files for viewing.

·        Play selected file plays the avi file which has been selected and is currently being displayed in the textbox directly below the list.

·        Delete selected file erases the avi file which is currently being displayed completely. The HomeCamlog file is also appended with the delete details.

Note the quality of the displayed video here might not appear to be very good. This is because a flag has been set to expand the video image to fill the video screen. The video here has been saved in the 160 X 120 format and is being played in a screen substantially larger. To view the video clip in its natural size, open it up directly from its own folder.

 

frmTol

 

 

This form is opened in the Display form by clicking Tolerance and sets the tolerance level for the surveillance process. The percentage of different pixels between the two most recent bitmap images is calculated during surveillance and if this exceeds the value set here then a video clip is saved. This tolerance level can be any real number.

·        Exit hides the form.

·        Get current tolerance sets the value in the textbox to the previously saved value.

·        Store this tolerance saves the displayed value to file.

 

6.2 Web and CGI Pages

 

Index.html

 

 

This is the index page for the video access website. The user must know the IP address of the server, if it on a dynamic IP machine (e.g. Dial up connection). A script box has been coded into the web page for security where a password, defined in the code, must be entered in order to continue. If the wrong password is entered, the java script function history.back(1) is called so the previous web page is restored to the browser window.

 

 

On clicking the icon or the ‘enter’ link, the CGI page h_o_m_e_p_a_g_e.exe is called.

 

h_o_m_e_p_a_g_e.exe

 

 

This CGI script, written in Borland C, counts the number of avi files in the new videos web folder. And displays the appropriate number (and ‘new’ logo). This makes use of the Borland DIR.H library functions findfirst and findnext to do this. The links are as follows:

·        New video files displays the CGI page create_new.exe.

·        Archived video files displays the CGI page create_arch.exe.

·        View MiniMax UserManual displays the MiniMax web server help page and user manual.

 

create_new.exe

 

This lists the avi file currently in the new videos folder. To view the avi file, just click on the desired link and it should start streaming, provided the media player options are set up to allow this. The file size is also displayed.

To archive any number of files, check the appropriate box and click Archive. This moves the selected video clips to the archived video web folder and the create_new_response.exe CGI web page is displayed.

 

create_new_response.exe

 

This CGI script displays the files which have just been archived. The web server also sends data such as the name and version of the server, the name of the computer it is running on as well as the port number. This has been filtered out by code in the script so it does not appear on the web page.


create_arch.exe

 

 

This CGI script page lists the AVI file currently in the archived videos folder. As before, to view the AVI file, just click on the desired link and, again, it should start streaming, provided the media player options are set up to allow this. The file size is also displayed again. It is similar to the create_new.exe CGI script, but does not include the archive option.

 

6.3 Using TrackPod in conjunction with HomeCam

TrackerCam® software provides but the one which interests us as regards this project is the ability to login to the TrackerCam system remotely and view the live images. Firstly, the surveillance system must be temporarily suspended from operating so moving the camera around with trackerpod does not trigger video capture. Once this occurs the user logged in on the TrackerCam can safely navigate the room.

The live video link can be viewed by browsing the IP address where the TrackCam is installed as its software runs a web server. MiniMax runs on port 8080 so an alternative comm. port must be chosen. Say the IP address of the machine is “101.102.103.104” and it runs on comm. port “8081”, then address inputted to the browser should be “101.102.103.104:8081”. Full details in the TrackerCam installation and user manual13.

 

6.4 Data files

This section describes the data files (.dat) used in the application. These are stored in the Application path/Run Project/Data folder. (Alphabetical order)

 

DiffPix.dat

This file stores the most recent pixel difference value obtained from analysing the latest pictures. This value is used to calculate the percentage difference value, which in turn, decides whether or not a video clip is saved.

 

EmailAdd.dat

This is the data file that holds the email address that the user wishes to send the update messages to. This can be changed from frmSetup.

 

FileSize.dat

Stores the file size value obtained from analysing the most recent picture. This value is used to calculate the percentage difference value, which in turn, decides whether or not a video clip is saved.

 

LatestBmp.dat

Contains the name of the most recent bitmap image that has been saved.

 

PrevBmp.dat

Contains the name of the second most recent bitmap image that has been saved.

 

TimeRec.dat

This data file states how long the video clips to be saved are. This value is loaded at start-up. This value can be changed in frmSetup and the new value takes effect the moment it is saved.

 

TimeSur.dat

This file states how long the intervals between surveillance image capture. Like above, this value is loaded at start-up, can be changed in frmSetup and this new value also takes effect the moment it is saved.

 

Tolerance.dat

This file holds the percentage tolerance value. This is the threshold value whereby if the percentage difference value exceeds this value, video is saved. This value can be changed from the form frmTol.

 

_IP.txt

This stores the current IP address used in creating links etc. It is not stored in the data folder but rather in the web root folder. It cannot be viewed over the net, however, as the MiniMax web server does not allow files beginning with “_” to be browsed.


7. Conclusions

 

The main aim of this project was to demonstrate that it is very possible to develop a video security system. Indeed, with more time it would be very possible to develop a highly adaptable network of camera covering a wide area. The main goals have been achieved and are as follows:

 

·        It is simple, inexpensive, contains technologies that are readily available and most people already possess them.

·        The system, once set up, runs unattended, indefinitely, needs little maintenance.

·        Is robust and can process high rates of data very quickly. Speed I provided by the power of the ‘C’ coded image processing dll.

·        The GUI is attractive, easy to use and provides full functionality to the user. Even allows for the captured AVI clips to be viewed in a provided window.

·        Perfect for home use because it allows for dynamic IP allocation which is the service ISP’s give to the majority of home subscribers.

·        Access to the video files is available globally. All that is required is a connection to the Internet and knowledge of the IP address the server is run on.

·        Changes to the system data, new files and errors are all logged and the user can be notified globally, if desired, in an email outlining the details and sent to a predefined address.

·        The index web page is protected by a java-script prompt that pushes back the page in the browser by one page if the incorrect password is entered but the fact that only the user should know the server IP makes this system quite secure to strangers attempting to view the home video clips.

·        Dynamic web page, provided by CGI functionality, makes use of the web site more user friendly. Rather than just listing all the video files saved on the system, the archive function allows the user to separate the viewed and the unviewed files.

·        Even though it is extremely small in size, the MiniMax web server is perfect for use with this project as it executes CGI programs, is free to download and its minuscule size ensures the application is portable on a floppy disk.

 

I would be very confident that a large number of conscientious homeowners and businesspeople would be very interested in installing such a system in their home and workplaces.

The HomeCam Internet Security System would bring a new and different slant to the apparently saturated video security market. The appeal of this inexpensive alternative to the existing products, would, no doubt, prove to be a big hit.


 

8. Discussion

 

8.1 Problems with the project

 

The main problems encountered throughout the project were mostly code based and the majority were solved with the help of various resources such as the MSDN help library and Internet help sites. However there were some more time consuming problems.

 

Before eventually deciding on Video for Windows as the image and video capture method, I had tired a number of other means including using other programs to do this. This introduced timing problems as the external program and HomeCam ran completely asynchronously. This is no problem using the VfW based VB component as the program waits for the image capture to take place.

 

Choosing an appropriate algorithm to perform the image processing also posed problems. Along with the system used in this project, I also toyed with the idea of using a light filter. This would have made it possible to distinguish between the same pictures with different light intensities. This means that if the brightness in the room change from one picture to the next, the algorithm would take this into account when deciding on the difference between the images. After attempting this, the results were not found to be satisfactory enough to include this feature with the application.

 

8.2 Future developments

 

As mentioned previously, Video for Windows allows for up to nine capture devices to run simultaneously on a machine. Microsoft’s new video capture technology, DirectX, could foreseeably, be incorporated into this application. The advantages of this would be substantial. Microsoft are no longer actively developing VfW so any problems that exist cannot be ironed out. DirectX, on the other hand, is constantly being upgraded and developed to sort out any bugs that are there and are also constantly developing new features. Support is also an issue when developing with Software Development Kits (SDKs) and with DirectX this should be first class.

Having said all this, there is ample documentation on VfW on the Internet and in literature to perform excellent results with this resource.

 

As regards the CGI programs, I pondered with the idea of adding a delete button to create_arch.exe. This, I subsequently decided against, the main reason being security. Until such time as a complete login system would be up and running, I though it best to refrain from any functionality that allows files to be deleted across the Internet. The construction of a proper login system would also be a top priority if carrying this project farther. Perhaps only one user should be allowed to be logged in at any one time because of the potentially sensitive nature of the information that could be accessed.

 

The HomeCam system would, possibly, be enhanced by using a central web server rather than one running on the users own machine. This system work by automatically dialling up to their ISP whenever a video clip is saved and uploading this file to the main HomeCam web server via FTP. On completion of the upload the Internet connection would be terminated.

This system minimises the time the users machine must spend online. This is desirable from a security and a cost viewpoint. The user could then login to this service to view the video clips.

 


 

References

These are the references made in the report itself.

1.      http://www.eagletron.com

2.      http://www.microsoft.com

3.      http://www.quickcam.com

4.      http://www.infomage.com

5.      http://www.shrinkwrapvb.com

6.      http://www.borland.com

7.      http://library.albany.edu/internet/internet.html

8.      http://library.uhh.hawaii.edu/instruction/web/clientserv_diagram.htm

9.      http://orca.st.usm.edu/~wbond/csc510/ImageProcessing.pps

10. http://www.jmcgowan.com/avi.html

11. http://www.shrinkwrapvb.com/avihelp/avihelp.htm

12. Borland help

13. http://www.trackercam.com/TCamWeb/UserGuide/index.html

 

CGI : Internet programming with C++ and C / Mark Felton                      1997

HTML 3.2 and CGI unleashed/John December and Mark Ginsburg      1996

Introductory digital image processing : a remote sensing perspective

Jensen, John R                                                                                              1986

Digital image analysis : selected techniques and applications / editors, Walter G Kropattsch/Horst Bischof                                                                        2001

 

The MSDN reference was called upon time and time again to solve the majority of the coding problems encountered.


 

Appendices

This section includes the project code along with extensive commenting.

 

Visual Basic Code

 

Code Module

''''''''''''''''''''''''''''''''''''''''

'This is the project module. This mainly

'contains the public functions and

'and declarations needed in the project.

''''''''''''''''''''''''''''''''''''''''

 

'Forces the programmer to pick a scope

'option eg. Public, Private etc.

Option Explicit

 

'Used in naming captured bitmap image

Public BmpNum As Integer

 

'The return error value when

'trying to resolve the IP num

Public Const SOCKET_ERROR = -1

 

'Declares the data type 'T_WSA'

'This holds the Winsock data

Private Type T_WSA

    wVersion As Integer

    wHighVersion As Integer

    szDescription(0 To 255) As Byte

    szSystemStatus(0 To 128) As Byte

    iMaxSockets As Integer

    iMaxUdpDg As Integer

    lpVendorInfo As Long

End Type

 

'Declares object of type T_WSA

Dim WSAData As T_WSA

 

'Declares the data type

'Inet_Address which holds

'the IP address

Type Inet_Address

    Byte4 As String * 1

    Byte3 As String * 1

    Byte2 As String * 1

    Byte1 As String * 1

End Type

 

Public IPStruct As Inet_Address

 

'Declares the data type 'T_Host'

'Holds host info

Type T_Host

    h_name As Long

    h_aliases As Long

    h_addrtype As Integer

    h_length As Integer

    h_addr_list As Long

End Type

 

'Declares the data type 'SYSTEMDATE'

'Used to get date info for naming

'video files.

Type SYSTEMDATE

    wYear As Integer

    wMonth As Integer

    wDayOfWeek As Integer

    wDay As Integer

    wHour As Integer

    wMinute As Integer

    wSecond As Integer

    wMilliseconds As Integer

End Type

 

'USER32.DLL functions.

'used to remove the 'X' close button in the top right corner

Declare Function DeleteMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long

Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long

 

'C_Bmp.DLL functions

'used in image processing

Declare Function DiffBitmap8 Lib "C_Bmp.dll" (ByVal LateBmp As String, ByVal PrevBmp As String, ByVal CharWhite As String, ByVal CharBlack As String, ByVal mode As Integer) As Long

 

'KERNEL32.DLL functions

'used in functions which attempt to resolve the IP address

Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (Dest As Any, Src As Any, ByVal cb&)

'needed to get system date. Used in naming the video clips.

Declare Sub GetSystemTime Lib "kernel32.dll" (lpSystemTime As SYSTEMDATE)

'all needed in resolving if the HomeCam application is running already

Public Declare Function Process32First Lib "kernel32.dll" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long

Public Declare Function Process32Next Lib "kernel32.dll" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long

Public Declare Function CloseHandle Lib "kernel32.dll" (ByVal Handle As Long) As Long

Public Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long

Public Declare Function CreateToolhelp32Snapshot Lib "kernel32.dll" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long

Public Declare Function GetVersionExA Lib "kernel32.dll" (lpVersionInformation As OSVERSIONINFO) As Integer

 

'WSOCK32.DLL functions

'all used to get IP address

Declare Function GetHostByName Lib "wsock32.dll" Alias "gethostbyname" (ByVal HostName As String) As Long

Declare Function WSAStartup Lib "wsock32.dll" (ByVal a As Long, b As T_WSA) As Long

Declare Function WSACleanUp Lib "wsock32.dll" Alias "WSACleanup" () As Integer

 

'PSAPI.DLL functions

'all needed in resolving if the HomeCam application is running already

Public Declare Function EnumProcesses Lib "psapi.dll" (ByRef lpidProcess As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long

Public Declare Function GetModuleFileNameExA Lib "psapi.dll" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long

Public Declare Function EnumProcessModules Lib "psapi.dll" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long

 

'Data type used to evaluate

'processes on Windows 95/98

Public Type PROCESSENTRY32

   dwSize As Long

   cntUsage As Long

   th32ProcessID As Long           ' This process

   th32DefaultHeapID As Long

   th32ModuleID As Long            ' Associated exe

   cntThreads As Long

   th32ParentProcessID As Long     ' This process's parent process

   pcPriClassBase As Long          ' Base priority of process threads

   dwFlags As Long

   szExeFile As String * 260       ' MAX_PATH

End Type

 

'Data type to hold operating

'system details

Public Type OSVERSIONINFO

   dwOSVersionInfoSize As Long

   dwMajorVersion As Long

   dwMinorVersion As Long

   dwBuildNumber As Long

   dwPlatformId As Long

    '1 = Windows 95.

    '2 = Windows NT

   szCSDVersion As String * 128

End Type

 

'Declarations to evaluate processes

'running

Public Const PROCESS_QUERY_INFORMATION = 1024

Public Const PROCESS_VM_READ = 16

Public Const MAX_PATH = 260

Public Const STANDARD_RIGHTS_REQUIRED = &HF0000

Public Const SYNCHRONIZE = &H100000

'STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF

Public Const PROCESS_ALL_ACCESS = &H1F0FFF

Public Const TH32CS_SNAPPROCESS = &H2&

Public Const hNull = 0

 

'Functions

 

'The following function tries

'to evaluate the host machine address.

'Parameters:    none

'Returns:       IP address as string

Function HostByName() As String

On Error GoTo er

    Dim p As Long

    Dim Host As T_Host

    Dim ListAddress As Long

    Dim ListAddr As Long

    Dim Address As Long

 

    'Evaluates host IP in Long int form

    p = GetHostByName("")

    If p = SOCKET_ERROR Then

        Exit Function

    ElseIf p <> 0 Then

        CopyMemory Host.h_name, ByVal p, Len(Host)

        ListAddress = Host.h_addr_list

        CopyMemory ListAddr, ByVal ListAddress, 4

        CopyMemory Address, ByVal ListAddr, 4

        'Evaluates host IP in four 8 byte string

        'format.

        HostByName = InetAddrLongToString(Address)

    End If

Exit Function

er:

HomeCamLog Err.Number, Err.Description, "Module", "HostByName"

End Function

 

'The following function accepts the

'IP address as a long integer and returns

'it in the more familiar string form

'to evaluate the host machine address.

'Parameters:    IP address as long

'Returns:       IP address as string

Private Function InetAddrLongToString(Address As Long) As String

CopyMemory IPStruct, Address, 4

InetAddrLongToString = CStr(Asc(IPStruct.Byte4)) + "." + CStr(Asc(IPStruct.Byte3)) + "." + CStr(Asc(IPStruct.Byte2)) + "." + CStr(Asc(IPStruct.Byte1))

End Function

 

'Initialises the Windows Sockets.

'Parameters:    none

'Returns:       nothing

Public Sub WinsockInit()

    WSAStartup &H101, WSAData

End Sub

 

'This function deletes all

'.bmp files contained in the

''App.Path & "\SurImg"' folder.

'Parameters:    none

'Returns:       nothing

Public Sub DelBmp()

On Err GoTo er

Dim FileName As String

'Change working directory to

'"\SurImg", where the deletion

'is required.

ChDir App.Path & "\SurImg"

FileName = Dir("*.bmp")

Do While FileName <> ""

    'delete

    Kill FileName

    FileName = Dir

Loop

'Return to old directory

ChDir App.Path

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, "Module", "DelBmp"

End Sub

 

'If Surveillance is running and if the

'Tolerance is exceeded by DiffPix value

'Video is captured and saved under a

'name derived from the systemdate

'and two latest images are displayed

'in their respective windows.

'If Surveillance is not running, the

'default 'HomeCam' picture is shown.

'Parameters:    none

'Returns:       nothing

Public Sub Refresh1()

On Error GoTo er

Dim i As Integer

Dim PathStr As String

Dim pic As String

Dim DiffStr As String

Dim FileStr As String

Dim StrTol As String

Dim Diff As Double

Dim Month1 As String

Dim Day1 As String

Dim Hour1 As String

Dim Min1 As String

Dim Sec1 As String

Dim FileName As String

 

'If Surveillance is ON

If frmMain.cmdSur.Caption = "&Surveillance ON" Then

    'If auto-refresh is checked

    If frmDisplay.chkAutoRefresh.Value = 1 Then

        'Load pictures

        Open App.Path & "\data\LatestBmp.dat" For Input Access Read As #1

            Line Input #1, pic

        Close #1

        frmDisplay.imgA.Picture = LoadPicture(App.Path & "\SurImg\" & pic)

        Open App.Path & "\data\PrevBmp.dat" For Input Access Read As #1

           Line Input #1, pic

        Close #1

        frmDisplay.imgB.Picture = LoadPicture(App.Path & "\SurImg\" & pic)

        'Display difference mask

        frmExamineDiff.imgA.Picture = LoadPicture(App.Path & "\Data\ExamineBmp.bmp")

    End If

   

    Open App.Path & "\data\DiffPix.dat" For Input Access Read As #1

        Line Input #1, DiffStr

    Close #1

    Open App.Path & "\data\FileSize.dat" For Input Access Read As #1

        Line Input #1, FileStr

    Close #1

    'File size and pixel diference data analysed

    '''(no of pixels)*3 = (no of bytes - 54)'''

    Diff = CLng(DiffStr) / (CLng(FileStr) - 54) * 3 * 100

    If frmDisplay.chkAutoRefresh.Value = 1 Then frmDisplay.txtPercent.Text = CInt(Diff)

    Open App.Path & "\data\Tolerance.dat" For Input Access Read As #1

        Line Input #1, StrTol

    Close #1

    'If Num. of Difference Pixel > Tolerance

    If Diff > CDbl(StrTol) Then

        'Get the system date for output video filename

        Dim SysDate As SYSTEMDATE

        GetSystemTime SysDate

       

        frmMain.lblRecStatus.Font.Bold = True

        frmMain.lblRecStatus.Caption = "Recording Video"

        frmMain.lblRecStatus.BackColor = &HFF00&

        'Reslove clip name

        If Len(CStr(SysDate.wMonth)) = 1 Then

            Month1 = "0" & CStr(SysDate.wMonth)

        Else

            Month1 = CStr(SysDate.wMonth)

        End If

        If Len(CStr(SysDate.wDay)) = 1 Then

            Day1 = "0" & CStr(SysDate.wDay)

        Else

            Day1 = CStr(SysDate.wDay)

        End If

        If Len(CStr(SysDate.wHour)) = 1 Then

            Hour1 = "0" & CStr(SysDate.wHour)

        Else

            Hour1 = CStr(SysDate.wHour)

        End If

        If Len(CStr(SysDate.wMinute)) = 1 Then

            Min1 = "0" & CStr(SysDate.wMinute)

        Else

            Min1 = CStr(SysDate.wMinute)

        End If

        If Len(CStr(SysDate.wSecond)) = 1 Then

            Sec1 = "0" & CStr(SysDate.wSecond)

        Else

            Sec1 = CStr(SysDate.wSecond)

        End If

        frmViewVideo.vidCap.CaptureFile = App.Path & "\..\Web\WWWRoot\Videos\" & SysDate.wYear & Month1 & Day1 & Hour1 & Min1 & Sec1 & ".avi"

        'Start video capture. System waits

        'until capture complete

        frmViewVideo.vidCap.CaptureVideo

        HomeCamLog 0, "New video file recorded", "Module", "Refresh1"

        frmMain.lblRecStatus.Font.Bold = False

        frmMain.lblRecStatus.Caption = "Not Recording"

        frmMain.lblRecStatus.BackColor = &HFF&

        'Deletes the stored bitmaps.

        'Surveillance must now wait until

        'two images are again stored.

        'This prevents an image maybe 30

        'secs old being compared to a new

        'image.

        DelBmp

    End If

Else

    'If Surveillance not running show

    'default pic.

    frmDisplay.imgA.Picture = LoadPicture(App.Path & "\default.bmp")

    frmDisplay.imgB.Picture = LoadPicture(App.Path & "\default.bmp")

    'Clear difference text box

    frmDisplay.txtPercent.Text = ""

    frmExamineDiff.imgA.Picture = LoadPicture(App.Path & "\default.bmp")

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, "Module", "Refresh1"

End Sub

 

'Sets up timer lengths on start-up.

'1/ the length between image captures.

'2/ the length of the film clips.

'These values have been previously

'saved in TimeSur.dat and TimeRec.dat.

'Parameters:    none

'Returns:       nothing

Public Sub SetSetup()

On Error GoTo er

Dim Time1 As String

Open App.Path & "\Data\TimeSur.dat" For Input Access Read As #1

    Line Input #1, Time1

Close #1

'Interval time

frmMain.tmeSurveillance.Interval = CInt(Time1) * 1000

Open App.Path & "\Data\TimeRec.dat" For Input Access Read As #1

    Line Input #1, Time1

Close #1

'Length of video clip

frmViewVideo.vidCap.TimeLimit = CInt(Time1)

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, "Module", "getVersion"

End Sub

 

'Called when a new video driver is

'selected and also on HomeCam startup.

'Sets up the new driver chosen or

'returns to the old one if there is

'an error.

'Parameters:    none

'Returns:       nothing

Public Sub GetVidDrivers()

On Error GoTo er

Dim oldDriver As Long

oldDriver = frmViewVideo.vidCap.DriverIndex

On Error Resume Next

'Sets new driver

frmViewVideo.vidCap.DriverIndex = frmViewVideo.cboVidDrivers.ListIndex

If Err Then

    'restore the old settings

    frmViewVideo.vidCap.DriverIndex = oldDriver

    frmViewVideo.cboVidDrivers.ListIndex = oldDriver

    MsgBox "Could not connect!", vbCritical, "Error"

    GoTo er

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, "Module", "GetVidDrivers"

End Sub

 

'This function adds updates the

'log file 'HomeCamLog.txt' and

'calls the function to send an

'email on the update.

'Parameters:    Error Num as long

'               Description as string

'               Form Name as string

'               Function as string

'Returns:       nothing

Public Sub HomeCamLog(ErrNum As Long, ErrDesc As String, FormName As String, Func As String)

Dim Str1 As String

''''remove'''''

If ErrNum <> 0 Then MsgBox "Error " & ErrNum & " " & ErrDesc & " in '" & FormName & " - " & Func & "'."

'''''''''''''''

'If a function exits in a difference

'directory, this resets the current

'working dir.

ChDir App.Path

Open App.Path & "\..\logs\HomeCamLog.txt" For Append As #10

    If ErrNum <> 0 Then

        Print #10, "Logged(mm/dd/yy): " & Date & "  " & Time & ":   Error: " & ErrNum & " " & ErrDesc & " in '" & FormName & " - " & Func & "'."

    Else

        Print #10, "Logged(mm/dd/yy): " & Date & "  " & Time & ":   " & ErrDesc & "."

    End If

Close #10

'If an outlook object cannot be

'created, goto the end.

If ErrNum = 429 Then GoTo End1

If ErrNum <> 0 Then

    SendMessage "Error " & ErrNum & " " & ErrDesc & " in '" & FormName & " - " & Func & "'."

Else

    SendMessage ErrDesc

End If

End1:

End Sub

 

'This function creates an MS OutLook

'object to create and send an email.

'The code is only executed if the

'checkbox is set to true on the main

'form. An attachment can even be added

'but this is not required here. An error

'is logged if the Outlook is not

'available.

'Parameters:    Mail Message as string

'Returns:       nothing

Public Sub SendMessage(MessageInMail As String)

On Error GoTo er

If frmMain.chkEmail Then

    'Open mail, adress, attach report

    Dim objOutlk As Object    'Outlook

    Dim objMail As Object 'Email item

    Const olMailItem = 0

    Dim MailAdd As String

    'Get mail address

    Open App.Path & "\Data\EmailAdd.dat" For Input Access Read As #1

        Line Input #1, MailAdd

    Close #1

    'Create a new message

    Set objOutlk = CreateObject("Outlook.Application")

    Set objMail = objOutlk.createitem(olMailItem)

    objMail.To = MailAdd

    objMail.cc = ""

    'Set up Subject Line

    objMail.subject = "HomeCam mail"

    'Add the body

   

    'To add an attachment, use:

    'objMail.attachments.add("C:\MyAttachmentFile.txt")

    objMail.body = MessageInMail

    'objMail.display 'Use this To display before sending, otherwise call objMail.Send to send without reviewing

    objMail.Send

    'Clean up

    Set objMail = Nothing

    Set objOutlk = Nothing

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, "Module", "SendMessage"

End Sub

 

'Formats the process name string.

'Parameters:    Process name string to format

'Returns:       Formatted process name string

Function StrZToStr(s As String) As String

   StrZToStr = Left$(s, Len(s) - 1)

End Function

 

'Gets the operating system info currently

'being used as stores it uses the user

'defined data type 'OSVERSIONINFO'. The method

'to get the processes' names can then be

'resolved.

'Parameters:    none

'Returns:       nothing

Public Function getVersion() As Long

On Error GoTo er

Dim osinfo As OSVERSIONINFO

Dim retvalue As Integer

 

osinfo.dwOSVersionInfoSize = 148

osinfo.szCSDVersion = Space$(128)

retvalue = GetVersionExA(osinfo)

getVersion = osinfo.dwPlatformId

Exit Function

er:

HomeCamLog Err.Number, Err.Description, "Module", "getVersion"

End Function

 

'Returns the number of times HomeCam.exe

'is running already. Does this by two

'different methods, depending on the

'operating system.

'Parameters:    HomeCam name as string

'Returns:       No. of times running as integer

Public Function CheckIfRunning(ProcessStr As String) As Integer

On Error GoTo er

Select Case getVersion()

Case 1 'Windows 95/98(/XP?????)

 

   Dim f As Long, sname As String

   Dim hSnap As Long, proc As PROCESSENTRY32

   hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)

   If hSnap = hNull Then Exit Function

   proc.dwSize = Len(proc)

   ' Iterate through the processes

   f = Process32First(hSnap, proc)

   Do While f

     sname = StrZToStr(proc.szExeFile)

     If UCase(ProcessStr) = UCase(sname) Then CheckIfRunning = CheckIfRunning + 1

     f = Process32Next(hSnap, proc)

   Loop

 

Case 2 'Windows NT/2000

 

   Dim cb As Long

   Dim cbNeeded As Long

   Dim NumElements As Long

   Dim ProcessIDs() As Long

   Dim cbNeeded2 As Long

   Dim NumElements2 As Long

   Dim Modules(1 To 200) As Long

   Dim lRet As Long

   Dim ModuleName As String

   Dim nSize As Long

   Dim hProcess As Long

   Dim i As Long

   'Get the array containing the process id's for each process object

   cb = 8

   cbNeeded = 96

   Do While cb <= cbNeeded

      cb = cb * 2

      ReDim ProcessIDs(cb / 4) As Long

      lRet = EnumProcesses(ProcessIDs(1), cb, cbNeeded)

   Loop

   NumElements = cbNeeded / 4

 

   For i = 1 To NumElements

      'Get a handle to the Process

      hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, ProcessIDs(i))

      'Got a Process handle

      If hProcess <> 0 Then

          'Get an array of the module handles for the specified

          'process

          lRet = EnumProcessModules(hProcess, Modules(1), 200, cbNeeded2)

          'If the Module Array is retrieved, Get the ModuleFileName

          If lRet <> 0 Then

             ModuleName = Space(MAX_PATH)

             nSize = 500

             lRet = GetModuleFileNameExA(hProcess, Modules(1), ModuleName, nSize)

             If UCase(Left(ModuleName, lRet)) = UCase(ProcessStr) Then CheckIfRunning = CheckIfRunning + 1

          End If

      End If

    'Close the handle to the process

   lRet = CloseHandle(hProcess)

   Next

End Select

Exit Function

er:

HomeCamLog Err.Number, Err.Description, "Module", "CheckIfRunning"

End Function

 

frmMain

'''''''''''''''''''''''''''''''''''''''''''''

'This is the code for the main form, where

'the application begins.

'''''''''''''''''''''''''''''''''''''''''''''

 

'Variables private to this form are declared

'here

Private Flag As Integer

 

'This Sub displays the 'About' form

'Parameters:    none

'Returns:       nothing

Private Sub cmdAbout_Click()

frmAbout.Show

End Sub

 

'This Sub displays the avi form

'Parameters:    none

'Returns:       nothing

Private Sub cmdAvi_Click()

frmAvi.Show

End Sub

 

'This Sub displays the live video viewing form

'Parameters:    none

'Returns:       nothing

Private Sub cmdCamera_Click()

frmViewVideo.Show

End Sub

 

'This Sub displays the latest pictures and

'mask forms

'Parameters:    none

'Returns:       nothing

Private Sub cmdDisplay_Click()

frmDisplay.Show

frmExamineDiff.Show

End Sub

 

'This Sub displays the form to change ip address

'Parameters:    none

'Returns:       nothing

Private Sub cmdIp_Click()

frmIp.Show

End Sub

 

'This Sub is called when the exit button is

'clicked

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

'for error capture  and loging

On Error GoTo er

Dim Res As Integer

Res = MsgBox("Are you sure you want to exit?", vbYesNo, App.Title)

If Res = vbNo Then GoTo StayOpen

If CheckIfRunning(App.Path & "\MiniMax.exe") Then

'check if server is running

    MsgBox "WebServer still running!", vbExclamation, "Notice"

    Exit Sub

ElseIf cmdSur.Caption = "&Surveillance ON" Then

    MsgBox "Surveillance still running!!", vbExclamation, "Notice"

    Exit Sub

End If

'Make addition to log file

HomeCamLog 0, "HomeCam Exited", App.Title, "Form_Activate"

End

er:

'Make addition to log file

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdQuit_Click"

StayOpen:

End Sub

 

'This Sub displays the form to change the settings

'Parameters:    none

'Returns:       nothing

Private Sub cmdSetup_Click()

frmSetup.Show

End Sub

 

'Called when the surveillence button clicked

'Parameters:    none

'Returns:       nothing

Private Sub cmdSur_Click()

On Error GoTo er

If cmdSur.Caption = "&Surveillance OFF" Then

    If frmViewVideo.cboVidDrivers.Text <> "<none>" Then

        MsgBox "Surveillance now running.", vbExclamation, "Notice"

        cmdSur.Caption = "&Surveillance ON"

        cmdSur.Font.Bold = True

    Else

        MsgBox "No Video Capture Device!", vbInformation, App.Title

    End If

Else

    cmdSur.Caption = "&Surveillance OFF"

    cmdSur.Font.Bold = False

    DelBmp

    MsgBox "Surveillance stopped.", vbExclamation, "Notice"

    Refresh1

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdSur_Click"

End Sub

 

'Calls batch file to open MiniMax Web Server

'via MiniMaxStart.bat and subsequently

'MiniMax.lnk

'Parameters:    none

'Returns:       nothing

Private Sub cmdWeb1_Click()

On Error GoTo er

Shell "MiniMaxStart.bat", 1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdWeb1_Click"

End Sub

 

'Calls exe to close MiniMax Web Server if the

'yes option in the dialog box is clicked

'Parameters:    none

'Returns:       nothing

Private Sub cmdWeb2_Click()

On Error GoTo er

Shell "CloseMiniMax.exe", 1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdWeb2_Click"

End Sub

 

'This Sub is called only once at start-up

'and performs the set-up routines

'Parameters:    none

'Returns:       nothing

Private Sub Form_Activate()

If Flag = 0 Then

    ' Remove the Close system menu item

    Dim hMenu As Long

    Const MF_BYPOSITION = &H400&

    ' Get the form's system menu handle.

    hMenu = GetSystemMenu(hWnd, False)

    DeleteMenu hMenu, 6, MF_BYPOSITION

    SetSetup

       

    Dim Chk As Integer

    'Check if it is already running from this directory

    Chk = CheckIfRunning(App.Path & "\Homecam.exe")

    'If it is already running from this directory

    'a message is displayed telling the user this

    If Chk > 1 Then

        Dim Res As Integer

        Res = MsgBox("'Homecam.exe' is already running " & Chk - 1 & " times. Do you want to open it again?", vbYesNo, "Notice")

        If Res = vbNo Then End

    End If

    'Flag so function will not be called again

    'when the form is activated

    Flag = 1

    HomeCamLog 0, "HomeCam Activated", App.Title, "Form_Activate"

    'Displays camera form

    frmViewVideo.Show

    GetVidDrivers

End If

End Sub

 

'This function is called every n seconds to

'take a new snapshot if Surveillance process

'is activated and video drivers are detected

'Parameters:    none

'Returns:       nothing

Private Sub tmeSurveillance_Timer()

On Error GoTo er

Dim PathStr As String

Dim FileName As String

Dim BmpStr As String

Dim OnSur As String

 

'If Surveillance process is activated and

'video drivers are detected, take image snapshot.

If cmdSur.Font.Bold = True And frmViewVideo.cboVidDrivers.Text <> "<none>" Then

    BmpNum = BmpNum + 1

    If Len(CStr(BmpNum)) = 1 Then

        BmpStr = CStr(BmpNum)

    Else

        BmpStr = "0"

        BmpNum = 0

    End If

    'Save Bmp file

    frmViewVideo.vidCap.SaveDIB App.Path & "\SurImg\SurvBmp" & BmpStr & ".bmp"

End If

PathStr = App.Path & "\SurImg\*.bmp"

FileName = Dir(PathStr)

Do While FileName <> ""

    i = i + 1

    FileName = Dir

Loop

'If more than one '.avi' file exists, then call

'StartSurvFromTimer

If i > 1 Then

    StartSurvFromTimer

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "tmeSurveillance_Timer"

End Sub

 

 

'Deletes .avi files which are not found to

'be one of the two most recent pictures taken

'Parameters:    none

'Returns:       nothing

Private Sub BitmapCleanUp()

On Error GoTo er

Dim PathStr As String

Dim RecStr As String

Dim FileName As String

Dim File1 As String

Dim File2 As String

Dim NewDate As Date

Dim Date1 As Date

Dim Date2 As Date

 

PathStr = App.Path & "\SurImg\*.bmp"

FileName = Dir(PathStr)

Do While FileName <> ""

    If UCase(FileName) <> "DEFAULT.BMP" Then

        NewDate = FileDateTime(App.Path & "\SurImg\" & FileName)

        If NewDate >= Date1 Then

            File2 = File1

            Date2 = Date1

            File1 = FileName

            Date1 = NewDate

        ElseIf NewDate >= Date2 Then

            File2 = FileName

            Date2 = NewDate

        End If

    End If

    FileName = Dir

Loop

Open App.Path & "\data\LatestBmp.dat" For Output As #1

    Print #1, File1

Close #1

Open App.Path & "\data\PrevBmp.dat" For Output As #1

    Print #1, File2

Close #1

 

FileName = Dir(PathStr)

Do While FileName <> ""

    If (UCase(FileName) <> "DEFAULT.BMP") And (UCase(FileName) <> UCase(File1)) And (UCase(FileName) <> UCase(File2)) Then

        Kill App.Path & "\SurImg\" & FileName

    End If

    FileName = Dir

Loop

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "BitmapCleanUp"

End Sub

 

'Finds the total file size and calls dll function

'which calculates differance between the two images

'Parameters:    none

'Returns:       long int: Number of pixels differant

Private Function Compare() As Long

On Error GoTo er

Dim i As Long

Dim Late As String

Dim Prev As String

Dim ColLate As Integer

Dim ColPrev As Integer

Dim Mode1 As Integer

 

Open App.Path & "\data\LatestBmp.dat" For Input Access Read As #1

    Line Input #1, Late

Close #1

Open App.Path & "\data\PrevBmp.dat" For Input Access Read As #1

    Line Input #1, Prev

Close #1

 

Open App.Path & "\SurImg\" & Late For Binary Access Read As #1

Open App.Path & "\SurImg\" & Prev For Binary Access Read As #2

Open App.Path & "\data\FileSize.dat" For Output As #3

    If LOF(1) > LOF(2) Then

        Print #3, Trim(LOF(2))

    Else

        Print #3, Trim(LOF(1))

    End If

Close #3

Close #2

Close #1

Late = App.Path & "\SurImg\" & Late

Prev = App.Path & "\SurImg\" & Prev

If frmViewVideo.opt64Colour.Value Then Mode1 = 1

Compare = DiffBitmap8(Late, Prev, Chr(255), Chr(0), Mode1)

If Compare < 0 Then HomeCamLog 0, "Error comparing bmps and writing ExamineBmp.bmp", Me.Name, "Compare"

Exit Function

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "Compare"

End Function

 

'Initiates capture process

'Parameters:    none

'Returns:       none

Private Sub StartSurvFromTimer()

On Error GoTo er

Dim StrPath As String

Dim StrDate As String

Dim Date1 As String

Dim OnSur As String

Dim Diff As Long

Dim SysDate As SYSTEMDATE

 

If cmdSur.Font.Bold = True Then

    BitmapCleanUp

    Open App.Path & "\data\DiffPix.dat" For Output As #100

        Print #100, CStr(Compare())

    Close #100

    Refresh1

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "StartSurvFromTimer"

End Sub

 

frmAbout

''''''''''''''''''''''''''''''''''''''''

'This form displays the program details

''''''''''''''''''''''''''''''''''''''''

'Hides about form

'Parameters:    none

'Returns:       none

Private Sub cmdOk_Click()

frmAbout.Hide

End Sub

 

frmAvi

''''''''''''''''''''''''''''''''''''''''

'This form allows the user to display

'the list of avi files saved, play them,

'and also to archive or delete them

'completely

''''''''''''''''''''''''''''''''''''''''

 

'Declares array used by the file listbox

Private ListArray(0 To 1000) As String

 

'Hides about form

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

Me.Hide

End Sub

 

'Refreshes the listbox contents

'Parameters:    none

'Returns:       nothing

Private Sub cmdRefreshList_Click()

Form_Load

End Sub

 

'Plays the selected file

'Parameters:    none

'Returns:       nothing

Private Sub cmdView_Click()

On Error GoTo er

If txtAvi.Text = "Select" Then

    MsgBox "Select a valid file", vbCritical, "Error"

Else

    'If a valid file is selected, the correct

    'directory is choosen and is played

    If Me.cmdDeleteAvi.Caption = "&Delete selected file" Then

        ChDir (App.Path & "\..\Web\WWWRoot\Videos\Archive")

    Else

        ChDir (App.Path & "\..\Web\WWWRoot\Videos")

    End If

    plyPlayer.FileName = txtAvi.Text

    plyPlayer.Play

    ChDir (App.Path)

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdView_Click"

End Sub

 

'Deletes the selected file

'Parameters:    none

'Returns:       nothing

Private Sub cmdDeleteAvi_Click()

On Error GoTo er

Dim Res As Integer

 

'If a valid file is selected, the correct

'directory is choosen and is deleted

If Me.cmdDeleteAvi.Caption = "&Delete selected file" Then

    ChDir (App.Path & "\..\Web\WWWRoot\Videos\Archive")

Else

    ChDir (App.Path & "\..\Web\WWWRoot\Videos")

End If

If txtAvi.Text <> "Select" Then

    Res = MsgBox("Are you sure?", vbYesNo, "Delete")

    If Res = vbYes Then

        plyPlayer.FileName = ""

        If Me.cmdDeleteAvi.Caption = "&Delete selected file" Then

            Kill txtAvi.Text

            HomeCamLog 0, txtAvi.Text & "deleted", Me.Name, "cmdDeleteAvi_Click"

        Else

            FileCopy App.Path & "\..\Web\WWWRoot\Videos\" & txtAvi.Text, App.Path & "\..\Web\WWWRoot\Videos\Archive\" & txtAvi.Text

            ChDir (App.Path & "\..\Web\WWWRoot\Videos")

            Kill txtAvi.Text

            HomeCamLog 0, txtAvi.Text & "archived", Me.Name, "cmdDeleteAvi_Click"

        End If

        plyPlayer.ShowAudioControls = False

        plyPlayer.ShowPositionControls = False

        plyPlayer.Height = 3855

        plyPlayer.Width = 4095

        plyPlayer.AutoSize = False

        plyPlayer.DisplaySize = mpFitToSize

    Else

        GoTo end1

    End If

Else

    MsgBox "Select a valid file", vbCritical, "Error"

End If

txtAvi.Text = "Select"

Form_Load

end1:

ChDir (App.Path)

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdDeleteAvi_Click"

End Sub

 

'Called on form load and when refreshing

'the form

'Parameters:    none

'Returns:       nothing

Private Sub Form_Load()

On Error GoTo er

Dim FileName As String

Dim i As Integer

 

'Refresh the listbox and its array

lstAvi.Clear

txtAvi.Text = "Select"

For i = 0 To 1000

   ListArray(i) = ""

   i = i + 1

Next i

'Selects correct working directory,

'(New or Archive)

If Me.cmdDeleteAvi.Caption = "&Delete selected file" Then

    ChDir (App.Path & "\..\Web\WWWRoot\Videos\Archive")

Else

    ChDir (App.Path & "\..\Web\WWWRoot\Videos")

End If

'search for avi files and load listbox and array

FileName = Dir("*.avi")

i = 0

Do While FileName <> ""

    lstAvi.AddItem FileName

    ListArray(i) = FileName

    FileName = Dir

    i = i + 1

Loop

ChDir (App.Path)

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "Form_Load"

End Sub

 

'Sets the textbox value to the desired

'filename.

'Parameters:    none

'Returns:       nothing

Private Sub lstAvi_DblClick()

'Loaded from listbox array

txtAvi.Text = ListArray(lstAvi.ListIndex)

End Sub

 

'Refreshes form to load 'archived files' mode

'Parameters:    none

'Returns:       nothing

Private Sub optArch_Click()

Me.cmdDeleteAvi.Caption = "&Delete selected file"

Form_Load

End Sub

 

'Refreshes form to load 'new files' mode

'Parameters:    none

'Returns:       nothing

Private Sub optNew_Click()

Me.cmdDeleteAvi.Caption = "&Archive selected file"

Form_Load

End Sub

 

frmDisplay

 

''''''''''''''''''''''''''''''''''''''''

'This form displays the two latest images

'and the percentage pixel differance

'between them

''''''''''''''''''''''''''''''''''''''''

 

'Shows form which displays the image mask.

'Parameters:    none

'Returns:       nothing

Private Sub cmdExamineBmp_Click()

frmExamineDiff.Show

End Sub

 

'Hides the form.

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

frmExamineDiff.Hide

Me.Hide

End Sub

 

'Shows form which displays and sets the

'tolerance level.

'Parameters:    none

'Returns:       nothing

Private Sub cmdTolerance_Click()

frmTol.Show

End Sub

 

'Calls a module function which sets up

'the form.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Load()

Refresh1

End Sub

 

'Called every time the form is activated.

'Updates the textbox with the correct

'tolerance value.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Activate()

On Error GoTo end1

Dim TolStr As String

Open App.Path & "\Data\Tolerance.dat" For Input Access Read As #1

    Line Input #1, TolStr

Close #1

'Updates the command button caption

'with the correct tolerance value.

cmdTolerance.Caption = "&Tol = " & TolStr

Exit Sub

end1:

HomeCamLog Err.Number, Err.Description, Me.Name, "Form_Activate"

End Sub

 

frmExamineDiff

 

''''''''''''''''''''''''''''''''''''''''

'This form displays the mask which shows

'the differance btween the two latest images

''''''''''''''''''''''''''''''''''''''''

 

'Hides the form.

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

Me.Hide

End Sub

 

'On form load, the HomeCam default

'image is displayed

'Parameters:    none

'Returns:       nothing

Private Sub Form_Load()

frmExamineDiff.imgA.Picture = LoadPicture(App.Path & "\default.bmp")

End Sub

 

frmIp

 

''''''''''''''''''''''''''''''''''''''''

'This form displays the stored IP address

'and aslo allews the user to change it.

''''''''''''''''''''''''''''''''''''''''

 

'This sub initiates the process which

'gets the cuurent IP address. It makes

'a number of calls to module functions

'which in turn make calls to external dlls

'user32.dll and kernel32.dll.

'Parameters:    none

'Returns:       nothing

Private Sub cmdGetIp_Click()

On Error GoTo er

    'Calls set up functions

    WinsockInit

    'Returns the current IP to the text box

    txtIP.Text = HostByName

    'Calls clean up functions

    WSACleanUp

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdGetIp_Click"

End Sub

 

'Hides the form.

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

On Error GoTo er

frmIp.Hide

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdQuit_Click"

End Sub

 

'Stores the currently displayed IP

'address to file.

'Parameters:    none

'Returns:       nothing

Private Sub cmdStoreIp_Click()

On Error GoTo er

Dim IpStr As String

IpStr = Trim(txtIP.Text)

'Output to file

Open App.Path & "\..\WEB\WWWRoot\_Ip.txt" For Output As #1

    Print #1, IpStr

Close #1

HomeCamLog 0, "New IP address " & IpStr & " saved", Me.Name, "cmdStoreIp_Click"

MsgBox "New IP address saved to file", vbExclamation, "Saved"

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdStoreIp_Click"

End Sub

 

'On form activation, the IP address from

'file is restored.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Activate()

On Error GoTo er

Dim IpStr As String

'Sets focus on the 'Exit' button.

cmdQuit.SetFocus

Open App.Path & "\..\WEB\WWWRoot\_Ip.txt" For Input Access Read As #1

    Line Input #1, IpStr

    txtIP.Text = IpStr

Close #1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "Form_Activate"

End Sub

 

frmSetup

 

''''''''''''''''''''''''''''''''''''''''

'This form provides the interface

'for the user to view and change the

'following settings:

'1.The email address to send updates to,

'2.The time interval between image

'captures,

'3.The length of the captured avi files.

''''''''''''''''''''''''''''''''''''''''

 

'Hides this form.

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

On Error GoTo er

frmSetup.Hide

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdQuit_Click"

End Sub

 

'Resets this form by calling the 'load'

'function.

'Parameters:    none

'Returns:       nothing

Private Sub cmdReset_Click()

Form_Load

End Sub

 

'Saves the currently displayed values to file.

'Parameters:    none

'Returns:       nothing

Private Sub cmdStore_Click()

On Error GoTo er

If IsNumeric(txtTimeSur) And IsNumeric(txtTimeRec) Then

    Open App.Path & "\Data\TimeSur.dat" For Output As #1

        Print #1, txtTimeSur.Text

    Close #1

    Open App.Path & "\Data\TimeRec.dat" For Output As #1

        Print #1, txtTimeRec.Text

    Close #1

    Open App.Path & "\Data\EmailAdd.dat" For Output As #1

        Print #1, Trim(txtMail.Text)

    Close #1

    'Calls the function which enforces the

    'new values

    SetSetup

    HomeCamLog 0, "New setup values saved", Me.Name, "cmdStore_Click"

    MsgBox "New values saved", vbExclamation, "Saved"

Else

    MsgBox "Value or values not valid", vbExclamation, "Saved"

End If

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdStore_Click"

End Sub

 

'Loads the form with the previously

'stored values.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Load()

On Error GoTo er

Dim Data1 As String

Open App.Path & "\Data\TimeSur.dat" For Input Access Read As #1

    Line Input #1, Data1

    txtTimeSur.Text = Data1

Close #1

Open App.Path & "\Data\TimeRec.dat" For Input Access Read As #1

    Line Input #1, Data1

    txtTimeRec.Text = Data1

Close #1

Open App.Path & "\Data\EmailAdd.dat" For Input Access Read As #1

    Line Input #1, Data1

    txtMail.Text = Data1

Close #1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "Form_Load"

End Sub

 

frmTol

 

''''''''''''''''''''''''''''''''''''''''

'This form provides the interface

'for the user to view and change the

'following the pixel differance tolerance

''''''''''''''''''''''''''''''''''''''''

 

'Gets the current saved value.

'Parameters:    none

'Returns:       nothing

Private Sub cmdGetTol_Click()

On Error GoTo er

Dim TolStr As String

Open App.Path & "\Data\Tolerance.dat" For Input Access Read As #1

    Line Input #1, TolStr

    txtTol.Text = TolStr

Close #1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdGetTol_Click"

End Sub

 

'Hides the form.

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

On Error GoTo er

frmTol.Hide

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdQuit_Click"

End Sub

 

'Stores the currently displayed value.

'Parameters:    none

'Returns:       nothing

Private Sub cmdStoreTol_Click()

On Error GoTo er

Dim TolStr As String

 

'Must be an appropriate numeric value.

If IsNumeric(Trim(txtTol.Text)) Then

    TolStr = Trim(txtTol.Text)

Else

    MsgBox "Not an appropriate numeric value. Choose a value from 0 - 100.", vbCritical, "Error"

    Exit Sub

End If

Open App.Path & "\Data\Tolerance.dat" For Output As #1

    Print #1, TolStr

Close #1

HomeCamLog 0, "New tolerance value '" & TolStr & "' saved", Me.Name, "cmdStoreTol_Click"

MsgBox "New tolerance value saved to file", vbExclamation, "Saved"

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "cmdStoreTol_Click"

End Sub

 

'On form activation this function

'gets the current saved value.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Activate()

On Error GoTo er

Dim TolStr As String

cmdQuit.SetFocus

Open App.Path & "\Data\Tolerance.dat" For Input Access Read As #1

    Line Input #1, TolStr

    txtTol.Text = TolStr

Close #1

Exit Sub

er:

HomeCamLog Err.Number, Err.Description, Me.Name, "Form_Activate"

End Sub

 

frmViewVideo

 

''''''''''''''''''''''''''''''''''''''''

'This form provides the interface

'for the user to view and change the

'following the pixel differance tolerance

''''''''''''''''''''''''''''''''''''''''

 

'The following function occurs when

'the video driver is selected from the

'combo-box. Saves the old settings in

'case of an error.

'Parameters:    none

'Returns:       nothing

Private Sub cboVidDrivers_Click()

GetVidDrivers

End Sub

 

'Displays audio control dialog box

'Parameters:    none

'Returns:       nothing

Private Sub cmdAudioDlg_Click()

vidCap.ShowDlgAudioFormat

End Sub

 

'Displays commpression control dialog box

'Parameters:    none

'Returns:       nothing

Private Sub cmdCompDlg_Click()

vidCap.ShowDlgCompressionOptions

End Sub

 

'Displays display control dialog box

'Parameters:    none

'Returns:       nothing

Private Sub cmdDisplayDlg_Click()

vidCap.ShowDlgVideoDisplay

End Sub

 

'Displays video format control dialog box

'Parameters:    none

'Returns:       nothing

Private Sub cmdFormatDlg_Click()

vidCap.ShowDlgVideoFormat

End Sub

 

'Hides the form

'Parameters:    none

'Returns:       nothing

Private Sub cmdQuit_Click()

Me.Hide

End Sub

 

'Displays video source control dialog box

'Parameters:    none

'Returns:       nothing

Private Sub cmdSourceDlg_Click()

vidCap.ShowDlgVideoSource

End Sub

 

'This function executes the loading

'code for the form. It finds the number

'of video drivers available and loads

'them into the listbox. It also enables

'appropriate command button if the drivers

'support their use.

'Parameters:    none

'Returns:       nothing

Private Sub Form_Load()

If vidCap.NumCapDevs > 0 Then

    For i = 0 To vidCap.NumCapDevs - 1

        cboVidDrivers.AddItem (vidCap.GetDriverName(i))

    Next

    'Load combo box with the detected drivers

    cboVidDrivers.ListIndex = vidCap.DriverIndex

    cmdCompDlg.Enabled = True

    frmMain.cmdSur.Enabled = True

Else

    cboVidDrivers.AddItem ("<none>")

    cboVidDrivers.ListIndex = 0

    MsgBox "No Video Capture Device!", vbInformation, App.Title

End If

'enable appropriate buttons

If vidCap.HasAudio Then cmdAudioDlg.Enabled = True

If vidCap.HasDlgFormat Then cmdFormatDlg.Enabled = True

If vidCap.HasDlgDisplay Then cmdDisplayDlg.Enabled = True

If vidCap.HasDlgSource Then cmdSourceDlg.Enabled = True

End Sub

__________________________________________________________________________________


Visual C++ Code for C_Bmp.dll

 

C_Bmp.cpp

 

/*

  C_Bmp.dll for use with FYP

  Code explanation in main body

  of report.

*/

 

#include <windows.h>

#include <fstream.h>

#include <stdio.h>

#include <ctype.h>

#include <math.h>

 

#define CCONV _stdcall

 

//Changes unsigned char to workable char

char UnSignedChar2Char(unsigned char *UnSigned)

{

char Signed;

Signed = (*UnSigned & 0xffL);

return Signed;

}

//Called from VB code

int CCONV DiffBitmap8(char *LateBmp, char *PrevBmp, char *CharWhite, char *CharBlack, int mode)

{

  fstream                                 file1, file2, fileOut;

  unsigned long int               i=0, out_val=0;

  int                                                         colour1=0, colour2=0;

  unsigned char                     c1[8], c2[8];

 

  file1.open(LateBmp, ios::in | ios::binary);

  if (!file1)

  {

                  return -1;

  }

  file2.open(PrevBmp, ios::in | ios::binary);

  if (!file2)

  {

                  return -2;

  }

  fileOut.open("Data\\ExamineBmp.bmp", ios::out | ios::binary);

  if (!file2)

  {

                  return -3;

  }

 

  while(file1.read(c1,1))                        //Gets 1 byte

  {

                  file2.read(c2,1);

                  i++;

                  if (i<55)

                                  fileOut.write(c1,1);

                  else

                  {

                                  if (mode)

                                  {

                                                  if((i%3)==1)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < -64)

                                                                                  colour1;

                                                                  else if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1++;

                                                                  else if (UnSignedChar2Char(c1) < 64)

                                                                                  colour1+=2;

                                                                  else colour1+=3;

 

                                                                  if (UnSignedChar2Char(c2) < -64)

                                                                                  colour2;

                                                                  else if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2++;

                                                                  else if (UnSignedChar2Char(c2) < 64)

                                                                                  colour2+=2;

                                                                  else colour2+=3;

                                                  }

                                                  else if((i%3)==2)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < -64)

                                                                                  colour1;

                                                                  else if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1+=4;

                                                                  else if (UnSignedChar2Char(c1) < 64)

                                                                                  colour1+=8;

                                                                  else colour1+=12;

 

                                                                  if (UnSignedChar2Char(c2) < -64)

                                                                                  colour2;

                                                                  else if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2+=4;

                                                                  else if (UnSignedChar2Char(c2) < 64)

                                                                                  colour2+=8;

                                                                  else colour2+=12;

                                                  }

                                                  else if((i%3)==0)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < -64)

                                                                                  colour1;

                                                                  else if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1+=16;

                                                                  else if (UnSignedChar2Char(c1) < 64)

                                                                                  colour1+=32;

                                                                  else colour1+=48;

 

                                                                  if (UnSignedChar2Char(c2) < -64)

                                                                                  colour2;

                                                                  else if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2+=16;

                                                                  else if (UnSignedChar2Char(c2) < 64)

                                                                                  colour2+=32;

                                                                  else colour2+=48;

 

                                                                  if (colour1!=colour2)

                                                                  {

                                                                                  out_val++;

                                                                                  fileOut.write(CharWhite,1);

                                                                                  fileOut.write(CharWhite,1);

                                                                                  fileOut.write(CharWhite,1);

                                                                  }

                                                                  else

                                                                                  fileOut.write(CharBlack,3);

                                                                  colour1=0;

                                                                  colour2=0;

                                                  }

                                  }

                                  else

                                  {

                                                  if((i%3)==1)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1++;

                                                                  if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2++;

                                                  }

                                                  else if((i%3)==2)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1+=2;

                                                                  if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2+=2;

                                                  }

                                                  else if((i%3)==0)

                                                  {

                                                                  if (UnSignedChar2Char(c1) < 0)

                                                                                  colour1+=4;

                                                                  if (UnSignedChar2Char(c2) < 0)

                                                                                  colour2+=4;

 

                                                                  if (colour1!=colour2)

                                                                  {

                                                                                  out_val++;

                                                                                  fileOut.write(CharWhite,1);

                                                                                  fileOut.write(CharWhite,1);

                                                                                  fileOut.write(CharWhite,1);

                                                                  }

                                                                  else

                                                                                  fileOut.write(CharBlack,3);

                                                                  colour1=0;

                                                                  colour2=0;

                                                  }

                                  }

                  }

  }

  fileOut.close();

  file2.close();

  file1.close();

return out_val;

}

 

C_Bmp.def

 

LIBRARY   C_Bmp

 

EXPORTS   

                DiffBitmap8                                           @1

__________________________________________________________________________________

 


 

Code using Borland C++, Version 5.01

 

H_o_m_e_p_a_g_e.c

 

/*

  This CGI program lets the user know how many files are contained in the New

  videos folder on entering the web site. It also contains the welcome message,

  a link to the MiniMax User manual and a nice little gif of a house!

*/

//Header declarations

#include <stdio.h>

#include <string.h>

#include <conio.h>

#include <dir.h>

 

//Main program begins

int main()

{

  //Function declarations

  int         i, done_rm;

  char dir_old[256];

  char dir_new[256];

  //Structure defined in dir.h where file attribute details are stored when

  //using findfirst() or findnext() functions.

  struct ffblk ffblk;

 

  //Must be included to tell server to execute as html code

  printf("Content-type: text/html\n");

  //HTML code

  printf("<html>\n");

  printf("<title>HomeCam homepage</title>\n");

  printf("<body bgcolor=black text=yellow>\n");

 

  //Change working directory to the new videos folder

  getcwd(dir_old, 256);                                                        //Gets current working dir

  strcpy(dir_new, dir_old);

  strcat(dir_new, "\\videos");

  if (chdir(dir_new))

  {

                                perror("chdir()");

  }

 

  //Using findfirst and findnext(), get the number of files in directory

  //Number stored in 'i'.

  done_rm = findfirst("*.avi",&ffblk,0);

  i=0;

  while (!done_rm)

  {

                                i++;

                                done_rm = findnext(&ffblk);

  }

  //HTML code

  printf("<h1 align=center><b><font color=yellow face=Ravie>Welcome to the Homecam homepage.</font></b></h1>");

  printf("<p align=center>&nbsp;</p>");

  printf("<p align=center><img border=0 src=img/0430.gif width=38 height=35>");

  printf("<p align=center>");

  printf("<br><br><a href=/videos/create_new.exe><b>New video files</b></a>");

  if(i)

                                printf("<b> </b><img border=0 src=img/NEW.gif><b> (%d)</b>",i);

  printf("<br><br><a href=/videos/archive/create_arch.exe><b>Archived video files</b></a>");

  printf("<br><br><br><br><br></p>");

  printf("<p align=center><a href=MiniMax_UserManual.html><font size=1><i>View MiniMax UserManual</i></font></a></p>");

  printf("</body>");

  printf("</html>");

return 0;

}

 

create_new.c

 

/*

  This searches for all the '.avi' files in the new files directory.

  Also creates links to other pages.

*/

//Header declarations

#include <stdio.h>

#include <string.h>

#include <conio.h>

#include <dir.h>

 

//Main program begins

int main()

{

  //Function declarations

  FILE      *f;

  int         i, done_rm;

  char      ipa[20], ipb[20];

  //Structure defined in dir.h where file attribute details are stored when

  //using findfirst() or findnext() functions.

  struct ffblk ffblk;

 

  //Must be included to tell server to execute as html code

  printf("Content-type: text/html\n");

  //HTML code

  printf("<html>\n");

  printf("<head>\n");

  printf("<title>New video clips</title>\n");

  printf("</head>\n");

  printf("<body bgcolor=black text=yellow>\n");

  printf("<center>\n");

 

  //open up IP file. Used in creating links.

  f=fopen("../_ip.txt", "r");

  if (!f)

  {

                  return -1;

  }

  //Seek start of file and get IP.

  fseek(f,0,SEEK_SET);

  fgets(ipb,20,f);

 

  //format IP string so it is usable

  i=0;

  while (ipb[i]!='\0' && ipb[i]!='\n')

  {

                                ipa[i] = ipb[i];

      i++;

  }

  ipa[i] = '\0';

 

  //Using findfirst and findnext(), get the number of files in directory

  //Number stored in 'i'.

  done_rm = findfirst("*.avi",&ffblk,0);

  i=0;

  while (!done_rm)

  {

                                i++;

                                done_rm = findnext(&ffblk);

  }

  printf("<h1>There are %d files</h1>\n", i);

 

  //Create html form and specify the page data is sent to when the submit button

  //is pressed.

  printf("<FORM action=http://%s/videos/create_new_response.exe method=get>\n", ipa);

 

  //List the files in the folder as links and display the file sizes in bytes

  done_rm = findfirst("*.avi",&ffblk,0);

  i=0;

  while (!done_rm)

  {

      i++;

      printf("<table border=1 cellpadding=1 cellspacing=1 width=300>\n");

                                printf("<tr>\n");

 

                                printf("<td width=145 height=13>\n");

      printf("<A HREF=http://%s/videos/%s>%s</a>\n", ipa, ffblk.ff_name, ffblk.ff_name);

      printf("</td>\n");

 

      printf("<td width=105 height=13>\n");

      printf("%d Bytes\n", ffblk.ff_fsize);

      printf("</td>\n");

 

      printf("<td height=13>\n");

      //Create a checkbox for each file found. Give the user the option to archive

      printf("<INPUT TYPE=checkbox NAME=check%d VALUE=%s>\n", i, ffblk.ff_name);

                   printf("</td>\n");

 

                                printf("</tr>\n");

                                printf("</table>\n");

 

      done_rm = findnext(&ffblk);

  }

  //Display a submit button only if at least one avi file is found

  if (i>0)

  {

                                printf("<br>");

                                printf("<INPUT TYPE=submit VALUE=Archive>\n");

  }

  printf("</FORM>\n");

  //Close IP file.

  fclose(f);

  //Create links to other pages.

  printf("\n<H5><A HREF=http://%s/h_o_m_e_p_a_g_e.exe>Home</a>\t\t", ipa);

  printf("<A HREF=http://%s/videos/Archive/create_arch.exe>Archived</a></H5>\n", ipa);

  printf("</center>");

  printf("</body>\n");

  printf("</html>\n");

return 0;

}

 

create_arch.c

 

/*

  This searches for all the '.avi' files in the archive directory.

  Also creates links to other pages.

*/

//Header declarations

#include <stdio.h>

#include <string.h>

#include <conio.h>

#include <dir.h>

 

//Main program begins

int main()

{

  //Function declarations

  FILE      *f;

  int         i, done_rm;

  //To get IP

  char      ipa[20], ipb[20];

  //Structure defined in dir.h where file attribute details are stored when

  //using findfirst() or findnext() functions.

  struct ffblk ffblk;

 

  //Must be included to tell server to execute as html code

  printf("Content-type: text/html\n\n");

  //HTML code

  printf("<html>\n");

  printf("<head>\n");

  printf("<title>Archived video clips</title>\n");

  printf("</head>\n");

  printf("<body bgcolor=black text=yellow>\n");

  printf("<center>");

 

  //open up IP file. Used in creating links.

  f=fopen("../../_ip.txt", "r");

  if (!f)

  {

                  return -1;

  }

  //Seek start of file and get IP.

  fseek(f,0,SEEK_SET);

  fgets(ipb,20,f);

 

  //format IP string so it is usable

  i=0;

  while (ipb[i]!='\0' && ipb[i]!='\n')

  {

                                ipa[i] = ipb[i];

      i++;

  }

  ipa[i] = '\0';

 

  //Using findfirst and findnext(), get the number of files in directory

  //Number stored in 'i'.

  done_rm = findfirst("*.avi",&ffblk,0);

  i=0;

  while (!done_rm)

  {

                                i++;

                                done_rm = findnext(&ffblk);

  }

  printf("<h1>There are %d files</h1>\n", i);

 

  //List the files in the folder as links and display the file sizes in bytes

  done_rm = findfirst("*.avi",&ffblk,0);

  while (!done_rm)

  {

                                printf("<table border=1 cellpadding=1 cellspacing=1 width=250>\n");

                                printf("<tr>\n");

                                printf("<td width=145 height=13>\n");

                                printf("<A HREF=http://%s/videos/archive/%s>%s</a></td><td>%d Bytes\n", ipa, ffblk.ff_name, ffblk.ff_name, ffblk.ff_fsize);

                                printf("</td>\n");

                                printf("</tr>\n");

                                printf("</table>\n");

                                done_rm = findnext(&ffblk);

  }

  //Close IP file.

  fclose(f);

  //Create links to other pages.

  printf("\n<H5><A HREF=http://%s/h_o_m_e_p_a_g_e.exe>Home</a>\t\t", ipa);

  printf("<A HREF=http://%s/videos/create_new.exe>New</a></H5>\n", ipa);

  printf("</center>");

  printf("</body>\n");

  printf("</html>\n");

  return 0;

}

 

create_new_response.c

 

/*

  create_new_response displays the video files just archived. The web server

  also send its own data, ie. its name and version etc, so this must be filtered

  out.

  The data from create_new.exe is stored in a global environment variable

  called 'QUERY_STRING'. This is then manipluated to extract the desired data

*/

//Header declarations

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

 

//Function which does the file move operation.

//Does this using the 'rename' function defined in <stdio.h>.

//Parameter:           Name of file to archive as *char.

//Returns:     Result of operation as int.

int MoveTheFile(char *strFileToMove)

{

                int                           res;

                char        newDir[50]="archive//";

 

                strcat(newDir, strFileToMove);

                res = rename( strFileToMove, newDir);

return res;

}

 

//Main program begins

int main(void)

{

//Function declarations

char *data;

//These were used in debugging.

//char *data = "check1=a.avi&check2=NEW.MPG&check2=B.AVI&check2=OLD.TXT";

//char *data = "";

//char *data = "check1=ARMADILLO.AVI";

char *newData;

char tempData[2048]="";

int  i;

FILE        *f;

char ipa[20], ipb[20];

int finished;

 

//Must be included to tell server to execute as html code

printf("Content-Type:text/html\n");

printf("<body bgcolor=black text=yellow>");

printf("<TITLE>Archive results</TITLE>\n");

printf("<center>\n");

printf("<H2>Files Archived</H2>\n\n");

//Store the received string in *data

data = getenv("QUERY_STRING");

if(data == NULL)

  printf("<P>Error! Error in passing data from form to script.");

else

{

  if (strlen(data))

                                finished = 0;

  else

      finished = 1;

  while (!finished)

  {

     //Get rid of useless data

                  data = strstr( data, "=") + 1;

                  strcpy(tempData, data);

                  for (i=0;i<strlen(tempData)+1;i++)

                                  if (tempData[i] == '&' || tempData[i] == '\0')

                                  {

                                                  tempData[i] = '\0';

                                                  if (strstr(data, ".a") || strstr(data, ".A"))

           {

               //if avi file detected in the *data string then print its name

               //and archive this file.

               printf("\n<P>%s", tempData);

                                                                                if (MoveTheFile(tempData))

                  //printed to notify of an error in archiving

                                                printf("                   Error archiving!!");

           }

           else

               //flag if no files left to archive

               finished = 1;

                                  }

                  newData = data + i;

                  data = newData;

  }

}

//open ip file to create links

f=fopen("../_ip.txt", "r");

if (!f)

{

                printf("<P>\nError opening ip file!");

}

//Seek start of file

fseek(f,0,SEEK_SET);

fgets(ipb,20,f);

 

i=0;

while (ipb[i]!='\0' && ipb[i]!='\n')

{

                ipa[i] = ipb[i];

                i++;

}

ipa[i] = '\0';

 

//Link to other pages.

printf("\n<H5><A HREF=http://%s/h_o_m_e_p_a_g_e.exe>Home</a>\t\t", ipa);

printf("<A HREF=http://%s/videos/create_new.exe>New</a>\t\t", ipa);

printf("<A HREF=http://%s/videos/Archive/create_arch.exe>Archived</a></H5>\n", ipa);

printf("</center>\n");

printf("</body>");

return 0;

}

________________________________________________________________
Hosted by www.Geocities.ws

1