Android Tutorial Android based Closed Circuit TV (CCTV) example

Better example is available here: https://www.b4x.com/android/forum/threads/mjpeg-cctv-server.73792/

This example is made of two components:

Client - Basic4android program that takes the camera preview frames and sends them to the server.

Server - C# program that accepts incoming connections and shows the camera frames.

The code of both components is pretty simple and is a good example of creating network based solutions. Note that both the client and server components should overcome network problems and continue to work when the network is again available.

How to run this example
1. Find the desktop ip address (you can run ipconfig from the command line).
2. Set this address in the device program - ServerIp variable.

Most complicated step:
3. By default Windows firewall blocks incoming connection. You need to open the firewall settings and add an exception for port 17178 (TCP).
Windows 7:

SS-2012-11-22_17.12.41.png


Run the desktop program and press Start.
Run the device program and check the logs in the IDE.

The source code of both projects is attached as well as the compiled desktop executable.

This example requires Android 2.2+ as the API that converts the preview image to JPEG is not available on older devices. The reflection library is also required.

Feel free to ask any question about this implementation.

The client code was updated to use CameraEx class. Note that it requires Camera library v2.0+.
 

Attachments

  • CCTVServer.zip
    30.1 KB · Views: 4,254
  • CameraCCTVClient.zip
    10.3 KB · Views: 4,112
Last edited:

LucaMs

Expert
Licensed User
Longtime User
It doesn't happen here. It is probably a hardware lag. Make sure to run the Android app in Release mode. You can also lower the frame rate. Maybe it is too fast for the device.


I had missed this reply.

I think I've tried with the Release, surely not the framerate.

I'll try.

Thank you, Erel

P.S. The problem could be related to the fact that I also have:
"the preview image in the PC side is rotated 90 Clockwise" as realblue wrote?
In fact, the picture freezes even when I change the orientation of my smartphone.

Ok, don't answer, thanks, i'll try all again :)
 
Last edited:

Douglas Farias

Expert
Licensed User
Longtime User
erel how is the code to user put ip manual in app ?
start app and have a question what the ip you want use ?
and the user set manual the ip

for exemple i m open the app in my phone and i put 192.168.1.1
?
 

Douglas Farias

Expert
Licensed User
Longtime User
how can i make this erel ?

B4X:
Sub Process_Globals
  Private frontCamera As Boolean = False
  Public ServerIp As String = edittext1 '?????
  Public ServerPort As Int = 17178
  Private IntervalMs As Int = 150
  Private lastPreviewSaved As Long
End Sub
 

Douglas Farias

Expert
Licensed User
Longtime User
Erel sorry for call you again
i read the documentation but it dont work

what i make wrong in my code?

when i open the app tell me a question ip i want.
i put my ip

and

ServerIp = Id.Input

but dont work =(

this is changes

i tryed remove

Public ServerIp As String

but give me error in comunicator

B4X:
Private Sub Connect
    If tryingToConnect Then Return
   
    tryingToConnect = True
    Log("Connecting to: " & Main.ServerIp & ":" & Main.ServerPort)
    client.Initialize("client")
    client.Connect(Main.ServerIp, Main.ServerPort, 20000)
End Sub




B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: False
    #ApplicationLabel: Cliente Servidor
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: landscape
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: true
    #IncludeTitle: false
#End Region

'Activity module
Sub Process_Globals
    Private frontCamera As Boolean = False
    Public ServerPort As Int
    Private IntervalMs As Int = 150
    Private lastPreviewSaved As Long
    Public ServerIp As String
   
End Sub

Sub Globals
    Private Panel1 As Panel
    Private camEx As CameraExClass
   
    Private CamNum As Int = 0
   
    Private btnCameraNumber As Button
    Private EditText1 As EditText
    Dim Id As InputDialog
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    'Dim Id As InputDialog
    Id.Input = ""
   
    Id.Show("", "", "OK", "","", Null  )
   
    btnCameraNumber_Click
    StartService(Communicator)
    ServerIp = Id.Input
    ServerPort = 17174 + CamNum
    StartService(Communicator)
    End Sub

Sub Activity_Resume
    InitializeCamera
End Sub

Private Sub InitializeCamera
    Try
        camEx.Initialize(Panel1, frontCamera, Me, "Camera1")
    Catch
        frontCamera = True
        camEx.Initialize(Panel1, frontCamera, Me, "Camera1")
    End Try
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    camEx.Release
End Sub

Sub Camera1_Ready (Success As Boolean)
    If Success Then
        camEx.StartPreview
        Log("Supported sizes:")
        For Each size As CameraSize In camEx.GetSupportedPicturesSizes
            Log(size.Width & "x" & size.Height)
        Next
        camEx.SetJpegQuality(90)
        Log(camEx.GetSupportedFlashModes)
        camEx.CommitParameters
    Else
        ToastMessageShow("Cannot open camera.", True)
    End If
End Sub

Sub btnTakePicture_Click
    camEx.TakePicture
End Sub

Sub Camera1_Preview (PreviewPic() As Byte)
    If DateTime.Now > lastPreviewSaved + IntervalMs Then
        Dim jpeg() As Byte = camEx.PreviewImageToJpeg(PreviewPic, 70)
        lastPreviewSaved = DateTime.Now
        CallSubDelayed2(Communicator, "Send", jpeg)
    End If
End Sub

Sub Camera1_PictureTaken (Data() As Byte)
    camEx.SavePictureToFile(Data, File.DirRootExternal, "1.jpg")
    camEx.StartPreview
End Sub

Sub btnEffect_Click
    Dim effects() As String = Array As String("aqua", "blackboard", "mono", "negative", "posterize", _
        "sepia", "solarize", "whiteboard")
    Dim effect As String = effects(Rnd(0, effects.Length))
    camEx.SetColorEffect(effect)
    ToastMessageShow(effect, False)
    camEx.CommitParameters
End Sub

Sub ChangeCamera_Click
    camEx.Release
    frontCamera = Not(frontCamera)
    InitializeCamera
End Sub
   
Sub btnCameraNumber_Click
    CamNum = CamNum +1
    If CamNum = 5 Then CamNum = 1
    btnCameraNumber.text = "# " & CamNum
    StopService(Communicator)
    ServerPort = 17174 + CamNum
    StartService(Communicator)
   
End Sub
 

Douglas Farias

Expert
Licensed User
Longtime User
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    'Dim Id As InputDialog
    Id.Input = ""
    Id.Show("", "", "OK", "","", Null  )
    btnCameraNumber_Click
    StartService(Communicator)
    ServerIp = Id.Input
    msgbox("my ip is: " & ServerIp, "test")
    ServerPort = 17174 + CamNum
    StartService(Communicator)
    End Sub
 
Last edited:

Douglas Farias

Expert
Licensed User
Longtime User
Sory for bump
I tried to simplify the most of what I'm trying to do.

I put serverIP As String Public and i make this
B4X:
Public Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    Id.Input = ""
    Id.Show("", "Put Here your ip", "OK", "","", Null  )
    btnCameraNumber_Click
 
    StartService(Communicator)
    ServerIp = Id.Input
    ServerPort = 17174 + CamNum
    StartService(Communicator)
 
        Msgbox("my ip is:" & ServerIp , "test")
    End Sub

when you start the app tell you what ip you want.
ok you put the ip, ok all is ok for now.

later i make a msgbox with the serverip
and ip shows me that I put at the beginning of the application ok.

but dont work

in comunicator

B4X:
Private Sub Connect
    If tryingToConnect Then Return
   
    tryingToConnect = True
    Log("Connecting to: " & Main.ServerIp & ":" & Main.ServerPort)
    client.Initialize("client")
    client.Connect(Main.ServerIp, Main.ServerPort, 20000)
End Sub

but Main.ServerIp is = 0 o_O I DONT KNOW WHY THIS
in my msg box show me a correct ip but i think the comunicator dont show my code, i thin comunicator use only this
Public ServerIp As String

and not this ServerIp = Id.Input


B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: False
    #ApplicationLabel: Cliente Servidor
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: landscape
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: true
    #IncludeTitle: false
#End Region

'Activity module
Sub Process_Globals
    Private frontCamera As Boolean = False
    Public ServerPort As Int
    Public ServerIp As String
    Private IntervalMs As Int = 150
    Private lastPreviewSaved As Long
End Sub

Sub Globals
    Private Panel1 As Panel
    Private camEx As CameraExClass
   
    Private CamNum As Int = 0
   
    Private btnCameraNumber As Button
    Private EditText1 As EditText
    Dim Id As InputDialog
End Sub

Public Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    Id.Input = ""
    Id.Show("", "Put Here your ip", "OK", "","", Null  )
    btnCameraNumber_Click
   
    StartService(Communicator)
    ServerIp = Id.Input
    ServerPort = 17174 + CamNum
    StartService(Communicator)
   
        Msgbox("my ip is:" & ServerIp , "test")
    End Sub

Sub Activity_Resume
    InitializeCamera
End Sub

Private Sub InitializeCamera
    Try
        camEx.Initialize(Panel1, frontCamera, Me, "Camera1")
    Catch
        frontCamera = True
        camEx.Initialize(Panel1, frontCamera, Me, "Camera1")
    End Try
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    camEx.Release
End Sub

Sub Camera1_Ready (Success As Boolean)
    If Success Then
        camEx.StartPreview
        Log("Supported sizes:")
        For Each size As CameraSize In camEx.GetSupportedPicturesSizes
            Log(size.Width & "x" & size.Height)
        Next
        camEx.SetJpegQuality(90)
        Log(camEx.GetSupportedFlashModes)
        camEx.CommitParameters
    Else
        ToastMessageShow("Cannot open camera.", True)
    End If
End Sub

Sub btnTakePicture_Click
    camEx.TakePicture
End Sub

Sub Camera1_Preview (PreviewPic() As Byte)
    If DateTime.Now > lastPreviewSaved + IntervalMs Then
        Dim jpeg() As Byte = camEx.PreviewImageToJpeg(PreviewPic, 70)
        lastPreviewSaved = DateTime.Now
        CallSubDelayed2(Communicator, "Send", jpeg)
    End If
End Sub

Sub Camera1_PictureTaken (Data() As Byte)
    camEx.SavePictureToFile(Data, File.DirRootExternal, "1.jpg")
    camEx.StartPreview
End Sub

Sub btnEffect_Click
    Dim effects() As String = Array As String("aqua", "blackboard", "mono", "negative", "posterize", _
        "sepia", "solarize", "whiteboard")
    Dim effect As String = effects(Rnd(0, effects.Length))
    camEx.SetColorEffect(effect)
    ToastMessageShow(effect, False)
    camEx.CommitParameters
End Sub

Sub ChangeCamera_Click
    camEx.Release
    frontCamera = Not(frontCamera)
    InitializeCamera
End Sub
   
Sub btnCameraNumber_Click
    CamNum = CamNum +1
    If CamNum = 5 Then CamNum = 1
    btnCameraNumber.text = "# " & CamNum
    StopService(Communicator)
    ServerPort = 17174 + CamNum
    StartService(Communicator)
   
End Sub

please someone help me?
I put pictures of how the application is
 

Attachments

  • 1.jpg
    1.jpg
    402.2 KB · Views: 887
  • 2.jpg
    2.jpg
    403.6 KB · Views: 845
  • 3.jpg
    3.jpg
    401.2 KB · Views: 821

Douglas Farias

Expert
Licensed User
Longtime User
Erel how to fix this error:

I have galaxy star and the client run fine. no problems

i have tested in my tablet, my table have only front camera.
when i start the app give me error in camera initializate java.

show me a option want continue yes or no
i press yes open the app and no show the camera, i press change camera button to change to front and again give me the error of camera initializate you know what this problem ?

m tablet is android 3.2 and the camera works fine in anothers app at google play
 

Douglas Farias

Expert
Licensed User
Longtime User
Last edited:

roger.jau

Member
Licensed User
Longtime User
Hi Erel, is possible to do the reverse (I think so but don´t know how) the computer or ipcam send image to the android app ? have a sample ?
 

Eliezio

Member
Licensed User
Longtime User
greetings to all,
this tutorial is for a video stream from phone to computer, I wonder how do I get the opposite, the video stream from my computer to the phone. I have IP cameras and frames it in visual studio, you want to develop an android application to receive the stream of video on my cell phone.
Thank you
 
Top