LiveViewFragment.java 15.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 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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
/*
 *  Copyright (c) 2013 - 2014 EyeTech Digital Systems. All rights reserved.
 */

package com.example.aeyetabs;

import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.Vector;
import java.lang.Runnable;

import com.eyetechds.quicklink.QLFrameData;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

public class LiveViewFragment extends QLFragment
{
	CameraSurfaceView	m_surfaceView	= null;

	public LiveViewFragment()
	{
		super();
		objectName = "LiveView";
	}

	// Creates a thread that polls the QLFrameData and draws the scaled image
	// with cross hairs
	// public View onCreateView(LayoutInflater inflater, ViewGroup container,
	// Bundle savedInstanceState)
	// {
	// View view = inflater.inflate(R.layout.tab, container, false);
	// TextView textview = (TextView) view.findViewById(R.id.tabtextview);
	// textview.setText("Live View");
	//
	// return view;
	// }

	// Creates a thread that polls the QLDeviceGetFrameData function
	// and draws the cursor
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		// TODO: Figure out the best way to add some buttons!
		m_surfaceView = new CameraSurfaceView(getActivity());
		return m_surfaceView;
	}

	@Override
	public void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		m_surfaceView.onResumeSurfaceView();
	}

	@Override
	public void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		m_surfaceView.onPauseSurfaceView();
	}

	class CameraSurfaceView extends SurfaceView implements Runnable, SurfaceHolder.Callback
	{
		int					pupilSizeRadiusMM	= 4;
		float				pupilSizeRadiusDp	= TypedValue.applyDimension(
														TypedValue.COMPLEX_UNIT_MM,
														pupilSizeRadiusMM,
														getResources().getDisplayMetrics());

		float				scaleHeight			= 1;
		Matrix				m_scaleMatrix		= new Matrix();
		Matrix				m_drawMatrix		= new Matrix();

		int					m_width				= 0;
		int					m_height			= 0;

		// Example usage of surface view taken from:
		// http://android-coding.blogspot.com/2011/05/basic-implementation-of-surfaceview.html
		Thread				thread				= null;
		SurfaceHolder		surfaceHolder		= null;
		volatile boolean	running				= false;
		Paint				paint				= new Paint();

		public CameraSurfaceView(Context context)
		{
			super(context);
			surfaceHolder = getHolder();
			surfaceHolder.addCallback(this);
		}

		void onResumeSurfaceView()
		{
			Log.d("QL2", "LiveViewFragment: onResumeSurfaceView()");

			// if(qlDevice != null)
			// qlDevice.start();

			// running = true;
			// thread = new Thread(this);
			// thread.start();
		}

		void onPauseSurfaceView()
		{
			Log.d("QL2", "LiveViewFragment: onPauseSurfaceView()");

			// if(qlDevice != null)
			// qlDevice.stop();

			boolean retry = true;
			running = false;
			while(retry)
			{
				try
				{
					thread.join();
					retry = false;
				}
				catch(InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		// @Override
		public void run()
		{
			long prevTime = 0;
			long time = 0;
			int count = 0;
			String fpsString = "~10";
			Vector<Long> deltaTimes = new Vector<Long>();
			int previousFrameNumber = 0;
			

			Bitmap rawGrayImage = null;
			Bitmap scaledGrayImage = null;
			Bitmap scaledRGBImage = null;
			byte[] bufRGB = null;

			QLFrameData frame = null;
			DecimalFormat df = new DecimalFormat("#");
			int fontSize = 20;
			float fontSizeDp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, fontSize,
					getResources().getDisplayMetrics());

			while(running)
			{
				if(!isStarted)
					continue;
				frame = qlDevice.getFrame(1000);
				
				if(frame == null)
					continue;
				
				if(frame.imageData.frameNumber == previousFrameNumber)
					Log.d("QL2 sameFrame", "Same frame returned, frameNumber: " +  frame.imageData.frameNumber);

				previousFrameNumber = frame.imageData.frameNumber;
				
				prevTime = time;
				time = SystemClock.elapsedRealtime();
				if(prevTime != 0)
				{
					deltaTimes.addElement(time - prevTime);
					if(deltaTimes.size() > 10)
						deltaTimes.remove(0);

					count = (count + 1) % 10;
					if(count == 0)
					{
						int sum = 0;
						for(int i = 0; i < deltaTimes.size(); i++)
							sum += deltaTimes.get(i);

						float avgDelta = (float) sum / (float) deltaTimes.size();

						Log.d("QL2 fps",
								"sum: " + sum + ", deltaTimes.size(): " + deltaTimes.size());

						fpsString = df.format((1000.0) / avgDelta);
					}
				}

				boolean drawOnCanvas = false;
				int scaleRightX = 0, scaleRightY = 0, scaleLeftX = 0, scaleLeftY = 0;

				Log.d("QL2", "frame.imageData.scaleFactor: " + frame.imageData.scaleFactor);

				if(frame != null && frame.imageData != null && frame.imageData.pixelData != null
						&& (frame.imageData.width > 0) && (frame.imageData.height > 0)
						&& (frame.imageData.scaleFactor >= 1.))
				{
					ByteBuffer grayBuffer = null;
					// ByteBuffer rgbBuffer;
					int scaledWidth = 0;
					int scaledHeight = 0;

					if((m_width >= frame.imageData.width) && (m_height >= frame.imageData.height))
					{
						grayBuffer = frame.imageData.pixelData;
						scaledWidth = frame.imageData.width;
						scaledHeight = frame.imageData.height;

						// Free the memory for the raw gray image because we are not using it now.
						if(rawGrayImage != null)
						{
							rawGrayImage.recycle();
							rawGrayImage = null;
						}
					}

					else
					{
						if((rawGrayImage == null)
								|| (rawGrayImage.getWidth() != frame.imageData.width)
								|| (rawGrayImage.getHeight() != frame.imageData.height))
						{
							if(rawGrayImage != null)
								rawGrayImage.recycle();

							rawGrayImage = Bitmap.createBitmap(frame.imageData.width,
									frame.imageData.height, Bitmap.Config.ALPHA_8);

							calculateMatrix(frame.imageData.width, frame.imageData.height);
						}
						rawGrayImage.copyPixelsFromBuffer(frame.imageData.pixelData);

						scaledGrayImage = Bitmap.createBitmap(rawGrayImage, 0, 0,
								frame.imageData.width, frame.imageData.height, m_scaleMatrix, false);

						scaledWidth = scaledGrayImage.getWidth();
						scaledHeight = scaledGrayImage.getHeight();
					}
					int numOfPixels = scaledWidth * scaledHeight;
					int minBitmapBufferSize = numOfPixels * 4;
					if((bufRGB == null) || (bufRGB.length < minBitmapBufferSize))
						;
					bufRGB = new byte[minBitmapBufferSize];

					ByteBuffer rgbBuffer = ByteBuffer.wrap(bufRGB);
					if(grayBuffer == null)
					{
						rgbBuffer.position(numOfPixels * 3);
						grayBuffer = rgbBuffer.slice();
						grayBuffer.rewind();

						try
						{
							scaledGrayImage.copyPixelsToBuffer(grayBuffer);
						}
						catch(Exception e)
						{
							continue;
						}
					}

					// Free the memory for the scaled gray image because we no longer need it.
					if(scaledGrayImage != null)
					{
						scaledGrayImage.recycle();
						scaledGrayImage = null;
					}

					// Rewind the rgb and gray buffers.
					grayBuffer.rewind();
					rgbBuffer.rewind();

					byte[] rgbArray = rgbBuffer.array();
					int rgbOffset = rgbBuffer.arrayOffset();

					byte[] grayArray = grayBuffer.array();
					int grayOffset = grayBuffer.arrayOffset();

					int k = 0;
					byte pixel;

					for(int j = 0; j < numOfPixels; j++)
					{
						pixel = grayArray[grayOffset + j];

						rgbArray[rgbOffset + k] = pixel;
						rgbArray[rgbOffset + k + 1] = pixel;
						rgbArray[rgbOffset + k + 2] = pixel;
						rgbArray[rgbOffset + k + 3] = -1;
						k += 4;
					}

					// http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
					// BitmapFactory.Options options = new
					// BitmapFactory.Options();
					// BitmapFactory.decodeByteArray(buf, offset, pLength,
					// options);

					// ByteBuffer buffer = ByteBuffer.allocate(bitmapBufferSize); // Create a
					// // new
					// // buffer
					// buffer.put(buf);
					// buffer.position(0);

					Log.v("QL2 ImageMetrics", "scaledWidth: " + scaledWidth + ", scaledHeight: "
							+ scaledHeight);

					if((scaledRGBImage == null) || (scaledRGBImage.getWidth() != scaledWidth)
							|| (scaledRGBImage.getHeight() != scaledHeight))
					{
						if(scaledRGBImage != null)
							scaledRGBImage.recycle();

						scaledRGBImage = Bitmap.createBitmap(scaledWidth, scaledHeight,
								Bitmap.Config.ARGB_8888);
					}
					scaledRGBImage.copyPixelsFromBuffer(rgbBuffer);
				}
				else if(frame != null)
				{
					if(frame.imageData.scaleFactor < 1.)
					{
						drawOnCanvas = true;

						int w = m_surfaceView.getWidth();
						int h = m_surfaceView.getHeight();
						int frameWidth = frame.imageData.width;
						int frameHeight = frame.imageData.height;

						if(w == 0 || h == 0 || frameWidth == 0 || frameHeight == 0)
						{
							drawOnCanvas = false;
						}
						else
						{
							float ratio_x = (float) w / (float) frameWidth;
							float ratio_y = (float) h / (float) frameHeight;

							scaleRightX = (int) (w - (ratio_x * frame.rightEye.pupil.x));
							scaleRightY = (int) (ratio_y * frame.rightEye.pupil.y);
							scaleLeftX = (int) (w - (ratio_x * frame.leftEye.pupil.x));
							scaleLeftY = (int) (ratio_y * frame.leftEye.pupil.y);
						}

					}
					else
						continue;
				}
				else if(frame == null)
				{
					Log.d("QL2", "frame was null: " + qlDevice.getLastError());
					continue;
				}

				if(surfaceHolder.getSurface().isValid())
				{
					Canvas canvas = surfaceHolder.lockCanvas();
					// ... actual drawing on canvas

					if(drawOnCanvas)
					{
						canvas.drawColor(Color.BLACK);
						paint.setFlags(Paint.ANTI_ALIAS_FLAG);
						paint.setStyle(Paint.Style.STROKE);
						paint.setStrokeWidth(2.0f);
						if(frame.rightEye.found)
						{
							paint.setColor(Color.RED);
							canvas.drawCircle(scaleRightX, scaleRightY, pupilSizeRadiusDp, paint);
						}
						if(frame.leftEye.found)
						{
							paint.setColor(Color.CYAN);
							canvas.drawCircle(scaleLeftX, scaleLeftY, pupilSizeRadiusDp, paint);
						}
						paint.setTextSize(fontSizeDp);
						paint.setColor(Color.WHITE);
						paint.setStrokeWidth(0.0f);
						canvas.drawText(fpsString, 30, 90, paint);
					}
					else if(scaledRGBImage != null)
					{
						canvas.drawColor(Color.BLACK);

						int x = (canvas.getWidth() - scaledRGBImage.getWidth()) / 2;
						int y = (canvas.getHeight() - scaledRGBImage.getHeight()) / 2;

						m_drawMatrix.reset();
						m_drawMatrix.postTranslate((float) (-x) - scaledRGBImage.getWidth(),
								(float) y);
						m_drawMatrix.postScale(-1.0f, 1.0f);

						canvas.drawBitmap(scaledRGBImage, m_drawMatrix, paint);

						float scale = Math.min((float) m_width / (float) frame.imageData.width,
								1.0f);
						double side = scaledRGBImage.getHeight() / 10;
						boolean flipx = true;
						paint.setFlags(Paint.ANTI_ALIAS_FLAG);
						paint.setStyle(Paint.Style.STROKE);
						if(frame.rightEye.found)
						{
							double eyePosX = x
									+ (flipx ? frame.imageData.width - frame.rightEye.pupil.x
											: frame.rightEye.pupil.x) * scale;
							double eyePosY = y + (frame.rightEye.pupil.y * scale);

							paint.setColor(Color.RED);
							canvas.drawLine((float) (eyePosX - (side / 2.)), (float) eyePosY,
									(float) (eyePosX + (side / 2.)), (float) eyePosY, paint);
							canvas.drawLine((float) eyePosX, (float) (eyePosY - (side / 2.)),
									(float) eyePosX, (float) (eyePosY + (side / 2.)), paint);
						}
						if(frame.leftEye.found)
						{
							double eyePosX = x
									+ (flipx ? frame.imageData.width - frame.leftEye.pupil.x
											: frame.leftEye.pupil.x) * scale;
							double eyePosY = y + (frame.leftEye.pupil.y * scale);

							paint.setColor(Color.CYAN);
							canvas.drawLine((float) (eyePosX - (side / 2.)), (float) eyePosY,
									(float) (eyePosX + (side / 2.)), (float) eyePosY, paint);
							canvas.drawLine((float) eyePosX, (float) (eyePosY - (side / 2.)),
									(float) eyePosX, (float) (eyePosY + (side / 2.)), paint);
						}

						paint.setTextSize(fontSizeDp);
						paint.setColor(Color.WHITE);
						paint.setStrokeWidth(0.0f);
						canvas.drawText(fpsString, x + 30, y + 90, paint);

					}

					surfaceHolder.unlockCanvasAndPost(canvas);

				}
			}
		}

		// public Bitmap plotCross (Bitmap bit, int crossW, int crossH, int x,
		// int y, int color)
		public void plotCross(Bitmap bit, int crossW, int crossH, int x, int y, int color)
		{

			int imgW = bit.getWidth();
			int imgH = bit.getHeight();

			int k = 0; // iterator index
			int halfWidth = crossW / 2;
			int halfHeight = crossH / 2;

			// if(x < halfWidth || x > imgW - halfWidth || y < halfHeight || y >
			// imgH - halfHeight)
			// return;

			// paint Horizontal line with the given width (crossW) with center
			// at given x
			int trimLeft = 0;
			int trimRight = 0;
			int trimTop = 0;
			int trimBottom = 0;

			if(x < halfWidth)
				trimLeft = halfWidth - x;
			else if(x > imgW - halfWidth)
				trimRight = x - imgW + halfWidth;

			if(y < halfWidth)
				trimTop = halfWidth - y;
			else if(y > imgH - halfWidth)
				trimBottom = y - imgH + halfWidth;

			int pixelX = 0;
			int pixelY = 0;
			for(k = -halfWidth + trimLeft; k < halfWidth - trimRight; k++)
			{
				pixelX = x + k;
				pixelY = y;
				if((pixelX >= 0) && (pixelY >= 0) && (pixelX < imgW) && (pixelY < imgH))
					bit.setPixel(pixelX, pixelY, color);
			}

			// paint Vertical line with the given height (crossH) with center at
			// given y
			for(k = -halfHeight + trimTop; k < halfHeight - trimBottom; k++)
			{
				pixelX = x;
				pixelY = y + k;
				if((pixelX >= 0) && (pixelY >= 0) && (pixelX < imgW) && (pixelY < imgH))
					bit.setPixel(pixelX, pixelY, color);
			}
		}

		void calculateMatrix(int frameWidth, int frameHeight)
		{
			if(m_width == 0 || m_height == 0 || frameWidth == 0 || frameHeight == 0)
			{
				Log.d("QL2 Matrix", "m_width: " + m_width + ", m_height: " + m_height
						+ ", frameWidth: " + frameWidth + ", frameHeight: " + frameHeight
						+ ", ERROR!");
				return;
			}

			float ratio_x = (float) m_width / (float) frameWidth;
			float ratio_y = (float) m_height / (float) frameHeight;

			Log.d("QL2 Matrix", "w: " + m_width + ", h: " + m_height + ", frameWidth: "
					+ frameWidth + ", frameHeight: " + frameHeight + ", ratio_x: " + ratio_x
					+ ", ratio_y: " + ratio_y);

			if(ratio_x < ratio_y)
				m_scaleMatrix.postScale(ratio_x, ratio_x);

			else
				m_scaleMatrix.postScale(ratio_y, ratio_y);
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder)
		{
			Log.d("QL2 surfaceCreated", "surfaceCreated");
			return;
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
		{
			// TODO Auto-generated method stub
			Log.d("QL2 surfaceChanged", "surfaceChanged");

			m_width = width;
			m_height = height;

			running = true;
			thread = new Thread(this);
			thread.start();

			return;
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder)
		{
			// TODO Auto-generated method stub
			Log.d("QL2 surfaceDestroyed", "surfaceDestroyed");
			return;
		}
	}
}