-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathMjpegProcessor.cs
More file actions
215 lines (182 loc) · 7.2 KB
/
MjpegProcessor.cs
File metadata and controls
215 lines (182 loc) · 7.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
public class MjpegProcessor {
// 2 byte header for JPEG images
private readonly byte[] JpegHeader = new byte[] { 0xff, 0xd8 };
// pull down 1024 bytes at a time
private int _chunkSize = 1024*4;
// used to cancel reading the stream
private bool _streamActive;
// current encoded JPEG image
public byte[] CurrentFrame { get; private set; }
// WPF, Silverlight
//public BitmapImage BitmapImage { get; set; }
// used to marshal back to UI thread
private SynchronizationContext _context;
public byte[] latestFrame = null;
private bool responseReceived = false;
// event to get the buffer above handed to you
public event EventHandler<FrameReadyEventArgs> FrameReady;
public event EventHandler<ErrorEventArgs> Error;
public MjpegProcessor(int chunkSize = 4 * 1024)
{
_context = SynchronizationContext.Current;
_chunkSize = chunkSize;
}
public void ParseStream(Uri uri)
{
ParseStream(uri, null, null);
}
public void ParseStream(Uri uri, string username, string password)
{
Debug.Log("Parsing Stream " + uri.ToString());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
request.Credentials = new NetworkCredential(username, password);
// asynchronously get a response
request.BeginGetResponse(OnGetResponse, request);
}
public void StopStream()
{
_streamActive = false;
}
public static int FindBytes(byte[] buff, byte[] search)
{
// enumerate the buffer but don't overstep the bounds
for (int start = 0; start < buff.Length - search.Length; start++)
{
// we found the first character
if (buff[start] == search[0])
{
int next;
// traverse the rest of the bytes
for (next = 1; next < search.Length; next++)
{
// if we don't match, bail
if (buff[start + next] != search[next])
break;
}
if (next == search.Length)
return start;
}
}
// not found
return -1;
}
public static int FindBytesInReverse(byte[] buff, byte[] search)
{
// enumerate the buffer but don't overstep the bounds
for (int start = buff.Length - search.Length - 1; start > 0; start--)
{
// we found the first character
if (buff[start] == search[0])
{
int next;
// traverse the rest of the bytes
for (next = 1; next < search.Length; next++)
{
// if we don't match, bail
if (buff[start + next] != search[next])
break;
}
if (next == search.Length)
return start;
}
}
// not found
return -1;
}
private void OnGetResponse(IAsyncResult asyncResult)
{
responseReceived = true;
Debug.Log("OnGetResponse");
byte[] imageBuffer = new byte[1024 * 1024];
Debug.Log("Starting request");
// get the response
HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState;
try
{
Debug.Log("OnGetResponse try entered.");
HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
Debug.Log("response received");
// find our magic boundary value
string contentType = resp.Headers["Content-Type"];
if (!string.IsNullOrEmpty(contentType) && !contentType.Contains("="))
{
Debug.Log("MJPEG Exception thrown");
throw new Exception("Invalid content-type header. The camera is likely not returning a proper MJPEG stream.");
}
string boundary = resp.Headers["Content-Type"].Split('=')[1].Replace("\"", "");
byte[] boundaryBytes = Encoding.UTF8.GetBytes(boundary.StartsWith("--") ? boundary : "--" + boundary);
Stream s = resp.GetResponseStream();
BinaryReader br = new BinaryReader(s);
_streamActive = true;
byte[] buff = br.ReadBytes(_chunkSize);
while (_streamActive)
{
// find the JPEG header
int imageStart = FindBytes(buff, JpegHeader);// buff.Find(JpegHeader);
if (imageStart != -1)
{
// copy the start of the JPEG image to the imageBuffer
int size = buff.Length - imageStart;
Array.Copy(buff, imageStart, imageBuffer, 0, size);
while (true)
{
buff = br.ReadBytes(_chunkSize);
// Find the end of the jpeg
int imageEnd = FindBytes(buff, boundaryBytes);
if (imageEnd != -1)
{
// copy the remainder of the JPEG to the imageBuffer
Array.Copy(buff, 0, imageBuffer, size, imageEnd);
size += imageEnd;
// Copy the latest frame into `CurrentFrame`
byte[] frame = new byte[size];
Array.Copy(imageBuffer, 0, frame, 0, size);
CurrentFrame = frame;
// tell whoever's listening that we have a frame to draw
if (FrameReady != null)
FrameReady(this, new FrameReadyEventArgs());
// copy the leftover data to the start
Array.Copy(buff, imageEnd, buff, 0, buff.Length - imageEnd);
// fill the remainder of the buffer with new data and start over
byte[] temp = br.ReadBytes(imageEnd);
Array.Copy(temp, 0, buff, buff.Length - imageEnd, temp.Length);
break;
}
// copy all of the data to the imageBuffer
Array.Copy(buff, 0, imageBuffer, size, buff.Length);
size += buff.Length;
if (!_streamActive)
{
Debug.Log("CLOSING");
resp.Close();
break;
}
}
}
}
resp.Close();
}
catch (Exception ex)
{
if (Error != null)
_context.Post(delegate { Error(this, new ErrorEventArgs() { Message = ex.Message }); }, null);
return;
}
}
}
public class FrameReadyEventArgs : EventArgs
{
}
public sealed class ErrorEventArgs : EventArgs
{
public string Message { get; set; }
public int ErrorCode { get; set; }
}