JPEGCam v1.0.9a
Webcam library for capturing JPEG images and submitting to a server
Copyright (c) 2008 - 2009 Joseph Huckaby <jhuckaby@goldcartridge.com>
Licensed under the GNU Lesser Public License
http://www.gnu.org/licenses/lgpl.html
/**
* Copyright Adam.Bradley ( http://wonderfl.net/user/Adam.Bradley )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/zXvF
*/
package {
/* JPEGCam v1.0.9a */
/* Webcam library for capturing JPEG images and submitting to a server */
/* Copyright (c) 2008 - 2009 Joseph Huckaby <jhuckaby@goldcartridge.com> */
/* Licensed under the GNU Lesser Public License */
/* http://www.gnu.org/licenses/lgpl.html */
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
import flash.utils.*;
import flash.media.Camera;
import flash.media.Video;
import flash.external.ExternalInterface;
import flash.net.*;
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.geom.Matrix;
import com.adobe.images.JPGEncoder;
import flash.utils.ByteArray;
public class Webcam extends Sprite {
private var video:Video;
private var encoder:JPGEncoder;
private var snd:Sound;
private var channel:SoundChannel = new SoundChannel();
private var jpeg_quality:int;
private var video_width:int;
private var video_height:int;
private var server_width:int;
private var server_height:int;
private var camera:Camera;
private var bmp:Bitmap;
private var bmpdata:BitmapData;
private var url:String;
private var stealth:int;
private var b64encoder:Base64Encoder;
private var version:String = "JPEGCam v1.0.9a-r1 - ";
public function Webcam() {
// class constructor
flash.system.Security.allowDomain("*");
var flashvars:Object = LoaderInfo(this.root.loaderInfo).parameters;
video_width = Math.floor( flashvars.width );
video_height = Math.floor( flashvars.height );
server_width = Math.floor( flashvars.server_width );
server_height = Math.floor( flashvars.server_height );
stage.scaleMode = StageScaleMode.NO_SCALE;
// stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.align = StageAlign.TOP_LEFT;
stage.stageWidth = Math.max(video_width, server_width);
stage.stageHeight = Math.max(video_height, server_height);
// Hack to auto-select iSight camera on Mac (JPEGCam Issue #5, submitted by manuel.gonzalez.noriega)
// From: http://www.squidder.com/2009/03/09/trick-auto-select-mac-isight-in-flash/
var cameraIdx:int = -1;
for (var idx = 0, len = Camera.names.length; idx < len; idx++) {
if (Camera.names[idx] == "USB Video Class Video") {
cameraIdx = idx;
idx = len;
}
}
if (cameraIdx > -1) camera = Camera.getCamera( String(cameraIdx) );
else camera = Camera.getCamera();
if (camera != null) {
camera.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
video = new Video( Math.max(video_width, server_width), Math.max(video_height, server_height) );
video.attachCamera(camera);
addChild(video);
if ((video_width < server_width) && (video_height < server_height)) {
video.scaleX = video_width / server_width;
video.scaleY = video_height / server_height;
}
camera.setQuality(0, 100);
camera.setKeyFrameInterval(10);
camera.setMode( Math.max(video_width, server_width), Math.max(video_height, server_height), 30);
// do not detect motion (may help reduce CPU usage)
camera.setMotionLevel( 100 );
ExternalInterface.addCallback('_snap', snap);
ExternalInterface.addCallback('_configure', configure);
ExternalInterface.addCallback('_upload', upload);
ExternalInterface.addCallback('_reset', reset);
ExternalInterface.addCallback('_capture', capture);
if (flashvars.shutter_enabled == 1) {
snd = new Sound();
snd.load( new URLRequest( flashvars.shutter_url ) );
}
jpeg_quality = 90;
ExternalInterface.call('webcam.flash_notify', 'flashLoadComplete', true);
}
else {
trace("You need a camera.");
ExternalInterface.call('webcam.flash_notify', "error", "No camera was detected.");
}
}
public function set_quality(new_quality:int) {
// set JPEG image quality
if (new_quality < 0) new_quality = 0;
if (new_quality > 100) new_quality = 100;
jpeg_quality = new_quality;
}
public function configure(panel:String = SecurityPanel.CAMERA) {
// show configure dialog inside flash movie
Security.showSettings(panel);
}
private function activityHandler(event:ActivityEvent):void {
trace("activityHandler: " + event);
}
public function capture(url, new_quality, shutter, new_stealth = 0) {
// take snapshot from camera, and upload if URL was provided
if (new_quality) set_quality(new_quality);
stealth = new_stealth;
trace("in capture(), drawing to bitmap");
if (shutter) {
channel = snd.play();
}
// take snapshot, and expose it
bmpdata = new BitmapData( Math.max(video_width, server_width), Math.max(video_height, server_height) );
bmpdata.draw( video );
if (!stealth) {
// draw snapshot on stage
bmp = new Bitmap( bmpdata );
addChild( bmp );
// stop capturing video
video.attachCamera( null );
removeChild( video );
}
// first, convert the BitmapData into a JPEG ByteArray
var ba:ByteArray;
trace("converting to jpeg");
encoder = new JPGEncoder( jpeg_quality );
ba = encoder.encode( bmpdata );
trace(version + "Encoded jpeg byte array " + ba.length);
// and then convert that into base64
trace(version + "base64 encoding jpeg");
trace(version + "Started encoder");
b64encoder = new Base64Encoder();
trace("Encoding bytes");
b64encoder.encodeBytes(ba);
trace("Retrieving string");
var encodedString:String = b64encoder.toString();
trace("String encoded byte array " + encodedString.length);
return encodedString;
}
public function snap(url, new_quality, shutter, new_stealth = 0) {
// take snapshot from camera, and upload if URL was provided
if (new_quality) set_quality(new_quality);
stealth = new_stealth;
trace("in snap(), drawing to bitmap");
if (shutter) {
channel = snd.play();
setTimeout( snap2, 10, url );
}
else snap2(url);
}
public function snap2(url) {
// take snapshot, convert to jpeg, submit to server
bmpdata = new BitmapData( Math.max(video_width, server_width), Math.max(video_height, server_height) );
bmpdata.draw( video );
if (!stealth) {
// draw snapshot on stage
bmp = new Bitmap( bmpdata );
addChild( bmp );
// stop capturing video
video.attachCamera( null );
removeChild( video );
}
// if URL was provided, upload now
if (url) upload( url );
}
public function upload(url) {
if (bmpdata) {
if ((video_width > server_width) && (video_height > server_height)) {
// resize image downward before submitting
var tmpdata = new BitmapData(server_width, server_height);
var matrix = new Matrix();
matrix.scale( server_width / video_width, server_height / video_height );
tmpdata.draw( bmpdata, matrix, null, null, null, true ); // smoothing
bmpdata = tmpdata;
} // need resize
trace("converting to jpeg");
var ba:ByteArray;
encoder = new JPGEncoder( jpeg_quality );
ba = encoder.encode( bmpdata );
trace("jpeg length: " + ba.length);
var head:URLRequestHeader = new URLRequestHeader("Accept","text/*");
var req:URLRequest = new URLRequest( url );
req.requestHeaders.push(head);
req.data = ba;
req.method = URLRequestMethod.POST;
req.contentType = "image/jpeg";
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoaded);
trace("sending post to: " + url);
try {
loader.load(req);
}
catch (error:Error) {
trace("Unable to load requested document.");
ExternalInterface.call('webcam.flash_notify', "error", "Unable to post data: " + error);
}
}
else {
ExternalInterface.call('webcam.flash_notify', "error", "Nothing to upload, must capture an image first.");
}
}
public function onLoaded(evt:Event):void {
// image upload complete
var msg = "unknown";
if (evt && evt.target && evt.target.data) msg = evt.target.data;
ExternalInterface.call('webcam.flash_notify', "success", msg);
}
public function reset() {
// reset video after taking snapshot
if (bmp) {
removeChild( bmp );
bmp = null;
bmpdata = null;
video.attachCamera(camera);
addChild(video);
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2004-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
/**
* A utility class to encode a String or ByteArray as a Base64 encoded String.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
internal class Base64Encoder
{
import flash.utils.ByteArray;
//--------------------------------------------------------------------------
//
// Static Class Variables
//
//--------------------------------------------------------------------------
/**
* Constant definition for the string "UTF-8".
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const CHARSET_UTF_8:String = "UTF-8";
/**
* The character codepoint to be inserted into the encoded output to
* denote a new line if <code>insertNewLines</code> is true.
*
* The default is <code>10</code> to represent the line feed <code>\n</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static var newLine:int = 10;
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function Base64Encoder()
{
super();
reset();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* A Boolean flag to control whether the sequence of characters specified
* for <code>Base64Encoder.newLine</code> are inserted every 76 characters
* to wrap the encoded output.
*
* The default is true.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var insertNewLines:Boolean = true;
//--------------------------------------------------------------------------
//
// Public Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function drain():String
{
var result:String = "";
for (var i:uint = 0; i < _buffers.length; i++)
{
var buffer:Array = _buffers[i] as Array;
result += String.fromCharCode.apply(null, buffer);
}
_buffers = [];
_buffers.push([]);
return result;
}
/**
* Encodes the characters of a String in Base64 and adds the result to
* an internal buffer. Subsequent calls to this method add on to the
* internal buffer. After all data have been encoded, call
* <code>toString()</code> to obtain a Base64 encoded String.
*
* @param data The String to encode.
* @param offset The character position from which to start encoding.
* @param length The number of characters to encode from the offset.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function encode(data:String, offset:uint=0, length:uint=0):void
{
if (length == 0)
length = data.length;
var currentIndex:uint = offset;
var endIndex:uint = offset + length;
if (endIndex > data.length)
endIndex = data.length;
while (currentIndex < endIndex)
{
_work[_count] = data.charCodeAt(currentIndex);
_count++;
if (_count == _work.length || endIndex - currentIndex == 1)
{
encodeBlock();
_count = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
}
currentIndex++;
}
}
/**
* Encodes the UTF-8 bytes of a String in Base64 and adds the result to an
* internal buffer. The UTF-8 information does not contain a length prefix.
* Subsequent calls to this method add on to the internal buffer. After all
* data have been encoded, call <code>toString()</code> to obtain a Base64
* encoded String.
*
* @param data The String to encode.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function encodeUTFBytes(data:String):void
{
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
bytes.position = 0;
encodeBytes(bytes);
}
/**
* Encodes a ByteArray in Base64 and adds the result to an internal buffer.
* Subsequent calls to this method add on to the internal buffer. After all
* data have been encoded, call <code>toString()</code> to obtain a
* Base64 encoded String.
*
* @param data The ByteArray to encode.
* @param offset The index from which to start encoding.
* @param length The number of bytes to encode from the offset.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function encodeBytes(data:ByteArray, offset:uint=0, length:uint=0):void
{
if (length == 0)
length = data.length;
var oldPosition:uint = data.position;
data.position = offset;
var currentIndex:uint = offset;
var endIndex:uint = offset + length;
if (endIndex > data.length)
endIndex = data.length;
while (currentIndex < endIndex)
{
_work[_count] = data[currentIndex];
_count++;
if (_count == _work.length || endIndex - currentIndex == 1)
{
encodeBlock();
_count = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
}
currentIndex++;
}
data.position = oldPosition;
}
/**
* @private
*/
public function flush():String
{
if (_count > 0)
encodeBlock();
var result:String = drain();
reset();
return result;
}
/**
* Clears all buffers and resets the encoder to its initial state.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function reset():void
{
_buffers = [];
_buffers.push([]);
_count = 0;
_line = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
}
/**
* Returns the current buffer as a Base64 encoded String. Note that
* calling this method also clears the buffer and resets the
* encoder to its initial state.
*
* @return The Base64 encoded String.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function toString():String
{
return flush();
}
//--------------------------------------------------------------------------
//
// Private Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
private function encodeBlock():void
{
var currentBuffer:Array = _buffers[_buffers.length - 1] as Array;
if (currentBuffer.length >= MAX_BUFFER_SIZE)
{
currentBuffer = [];
_buffers.push(currentBuffer);
}
currentBuffer.push(ALPHABET_CHAR_CODES[(_work[0] & 0xFF) >> 2]);
currentBuffer.push(ALPHABET_CHAR_CODES[((_work[0] & 0x03) << 4) | ((_work[1] & 0xF0) >> 4)]);
if (_count > 1)
currentBuffer.push(ALPHABET_CHAR_CODES[((_work[1] & 0x0F) << 2) | ((_work[2] & 0xC0) >> 6) ]);
else
currentBuffer.push(ESCAPE_CHAR_CODE);
if (_count > 2)
currentBuffer.push(ALPHABET_CHAR_CODES[_work[2] & 0x3F]);
else
currentBuffer.push(ESCAPE_CHAR_CODE);
if (insertNewLines)
{
if ((_line += 4) == 76)
{
currentBuffer.push(newLine);
_line = 0;
}
}
}
//--------------------------------------------------------------------------
//
// Private Variables
//
//--------------------------------------------------------------------------
/**
* An Array of buffer Arrays.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private var _buffers:Array;
private var _count:uint;
private var _line:uint;
private var _work:Array = [ 0, 0, 0 ];
/**
* This value represents a safe number of characters (i.e. arguments) that
* can be passed to String.fromCharCode.apply() without exceeding the AVM+
* stack limit.
*
* @private
*/
public static const MAX_BUFFER_SIZE:uint = 32767;
private static const ESCAPE_CHAR_CODE:Number = 61; // The '=' char
/*
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
*/
private static const ALPHABET_CHAR_CODES:Array =
[
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, 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, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 43, 47
];
}