-
Notifications
You must be signed in to change notification settings - Fork 1
/
CamStream.java
408 lines (375 loc) · 11.2 KB
/
CamStream.java
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/**
** com/charliemouse/cambozola/shared/CamStream.java
** Copyright (C) Andy Wilcock, 2001.
** Available from http://www.charliemouse.com
**
** This file is part of the Cambozola package (c) Andy Wilcock, 2001.
** Available from http://www.charliemouse.com
**
** Cambozola is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** Cambozola is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Cambozola; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**/
//package com.charliemouse.cambozola.shared;
import java.awt.Image;
//import java.awt.Toolkit;
import android.graphics.*;
import java.awt.image.ImageObserver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class CamStream extends Thread {
public static final int CONNECT_STYLE_SOCKET = 1;
public static final int CONNECT_STYLE_HTTP = 2;
private static final int IMG_FLUFF_FACTOR = 1;
private ExceptionReporter m_reporter = null;
private Vector m_listeners;
private Bitmap m_imain = null;
//private BitmapFactory m_tk;
//m_tk;
private URL m_stream;
private String m_userpassEncoded;
private URL m_docBase;
private DataInputStream m_inputStream = null;
private boolean m_isDefunct = false;
private boolean m_collecting = false;
private byte[] m_rawImage;
private String m_imageType = "image/jpeg";
private long m_startTime = 0;
private int m_imgidx = 0;
private int m_retryCount = 1;
private int m_retryDelay = 1000;
private String m_appName = "";
private boolean m_debug = true;
public CamStream(URL strm, String app, URL docBase, int retryCount, int retryDelay, ExceptionReporter reporter, boolean debug)
{
// m_tk = Toolkit.getDefaultToolkit();
m_listeners = new Vector();
//
// Pull open stream - look for user/password.
//
m_stream = strm;
String userPass = strm.getUserInfo();
//
// Encode if needed...
//
m_userpassEncoded = null;
if (userPass != null && userPass.length() > 0)
{
m_userpassEncoded = Base64.encode(userPass.getBytes());
}
m_appName = app;
m_reporter = reporter;
m_isDefunct = false;
m_docBase = docBase;
m_retryCount = retryCount;
m_retryDelay = retryDelay;
m_debug = debug;
}
public synchronized Bitmap getCurrent()
{
return m_imain;
}
public synchronized final byte[] getRawImage()
{
return m_rawImage;
}
public synchronized int getIndex()
{
return m_imgidx;
}
public synchronized String getType()
{
return m_imageType;
}
public URL getStreamURL()
{
return m_stream;
}
public double getFPS()
{
if (m_startTime == 0) {
return 0.0;
}
long currTime = System.currentTimeMillis();
return (1000.0 * (m_imgidx - IMG_FLUFF_FACTOR)) / (currTime - m_startTime);
}
public void addImageChangeListener(ImageChangeListener cl)
{
m_listeners.addElement(cl);
}
public void removeImageChangeListener(ImageChangeListener cl)
{
m_listeners.removeElement(cl);
}
private void fireImageChange()
{
ImageChangeEvent ce = new ImageChangeEvent(this);
for (Enumeration e = m_listeners.elements(); e.hasMoreElements();) {
((ImageChangeListener) e.nextElement()).imageChanged(ce);
}
}
public void run()
{
StreamSplit ssplit;
try {
//
// Loop for a while until we either give up (hit m_retryCount), or
// get a connection.... Sleep inbetween.
//
String connectionError;
String ctype;
Hashtable headers;
int tryIndex = 0;
int retryCount = m_retryCount;
int retryDelay = m_retryDelay;
//
do {
//
// Keep track of how many times we tried.
//
tryIndex++;
if (m_debug)
{
System.err.println("// Connection URL = " + m_stream);
}
//
// Better method - access via URL Connection
//
URLConnection conn = m_stream.openConnection();
if (m_docBase != null) {
conn.setRequestProperty("Referer", m_docBase.toString());
}
conn.setRequestProperty("User-Agent", m_appName);
conn.setRequestProperty("Host", m_stream.getHost());
if (m_userpassEncoded != null) {
conn.setRequestProperty("Authorization", "Basic " + m_userpassEncoded);
}
m_inputStream = new DataInputStream(new BufferedInputStream(conn.getInputStream()));
//
// Read Headers for the main thing...
//
headers = StreamSplit.readHeaders(conn);
ssplit = new StreamSplit(m_inputStream);
//
if (m_debug)
{
System.err.println("// Request sent; Main Response headers:");
for (Enumeration enm = headers.keys();enm.hasMoreElements();)
{
String hkey = (String)enm.nextElement();
System.err.println("// " + hkey + " = " + headers.get(hkey));
}
}
//
m_collecting = true;
//
// Work out the content type/boundary.
//
connectionError = null;
ctype = (String) headers.get("content-type");
if (ctype == null) {
connectionError = "No main content type";
} else if (ctype.indexOf("text") != -1) {
String response;
//noinspection deprecation
while ((response = m_inputStream.readLine()) != null) {
System.out.println(response);
}
connectionError = "Failed to connect to server (denied?)";
}
if (connectionError == null)
{
break; // Yay!! got one.
} else if (m_isDefunct) {
//
// Not wanted any more...
//
return;
} else {
//
// Wait a while before retrying...
//
if (m_debug)
{
System.err.println("// Waiting for " + retryDelay + " ms");
}
m_reporter.reportFailure(connectionError);
sleep(retryDelay);
}
} while (tryIndex < retryCount);
//
if (connectionError != null)
{
return;
}
//
// Boundary will always be something - '--' or '--foobar'
//
int bidx = ctype.indexOf("boundary=");
String boundary = StreamSplit.BOUNDARY_MARKER_PREFIX;
if (bidx != -1) {
boundary = ctype.substring(bidx + 9);
ctype = ctype.substring(0, bidx);
//
// Remove quotes around boundary string [if present]
//
if (boundary.startsWith("\"") && boundary.endsWith("\""))
{
boundary = boundary.substring(1, boundary.length()-1);
}
if (!boundary.startsWith(StreamSplit.BOUNDARY_MARKER_PREFIX)) {
boundary = StreamSplit.BOUNDARY_MARKER_PREFIX + boundary;
}
}
//
// Now if we have a boundary, read up to that.
//
if (ctype.startsWith("multipart/x-mixed-replace")) {
if (m_debug)
{
System.err.println("// Reading up to boundary");
}
ssplit.skipToBoundary(boundary);
}
do {
if (m_collecting) {
//
// Now we have the real type...
// More headers (for the part), then the object...
//
if (boundary != null) {
headers = ssplit.readHeaders();
if (m_debug) {
System.err.println("// Chunk Headers recieved:");
for (Enumeration enm = headers.keys();enm.hasMoreElements();)
{
String hkey = (String)enm.nextElement();
System.err.println("// " + hkey + " = " + headers.get(hkey));
}
}
//
// Are we at the end of the m_stream?
//
if (ssplit.isAtStreamEnd()) {
break;
}
ctype = (String) headers.get("content-type");
if (ctype == null) {
throw new Exception("No part content type");
}
}
//
// Mixed Type -> just skip...
//
if (ctype.startsWith("multipart/x-mixed-replace")) {
//
// Skip
//
bidx = ctype.indexOf("boundary=");
boundary = ctype.substring(bidx + 9);
//
if (m_debug) {
System.err.println("// Skipping to boundary");
}
ssplit.skipToBoundary(boundary);
} else {
//
// Something we want to keep...
//
if (m_debug) {
System.err.println("// Reading to boundary");
}
byte[] img = ssplit.readToBoundary(boundary);
if (img.length == 0) {
break;
}
//
// FPS counter.
//
if (m_imgidx > IMG_FLUFF_FACTOR && m_startTime == 0) {
m_startTime = System.currentTimeMillis();
}
//
// Update the image [fores events off]
//
updateImage(ctype, img);
}
}
try {
Thread.sleep(20);
} catch (InterruptedException ignored) {
}
} while (!m_isDefunct);
} catch (Exception e) {
if (!m_collecting)
{
m_reporter.reportFailure(e.toString());
} else if (!m_isDefunct) {
m_reporter.reportError(e);
}
} finally {
unhook();
}
//
// At this point, the m_stream m_inputStream done
// [could dispplay a that's all folks - leaving it as it m_inputStream
// will leave the last frame up]
//
}
private synchronized void updateImage(String ctype, byte[] img)
{
//
// Update our image...
//
m_imageType = ctype;
//m_imain = m_tk.createImage(img);
m_imain = BitmapFactory.decodeByteArray(img,0,img.length);
m_rawImage = img;
m_imgidx++;
m_imain.getWidth();
/*new ImageObserver()
{
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
boolean fully = ((infoflags & (ImageObserver.ALLBITS | ImageObserver.PROPERTIES)) != 0);
if (fully) {
fireImageChange();
}
return !fully;
}
});*/
}
public void finalize() throws Throwable
{
unhook();
super.finalize();
}
public void unhook()
{
m_collecting = false;
m_isDefunct = true;
try {
if (m_inputStream != null)
{
m_inputStream.close();
}
m_inputStream = null;
} catch (Exception ignored) {
}
}
}