////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;

	public class UIBase extends Sprite implements IInitModel, IStrand
	{
		public function UIBase()
		{
			super();
		}

		private var _width:Number;
		override public function get width():Number
		{
			return _width;
		}
		override public function set width(value:Number):void
		{
			if (_width != value)
			{
				_width = value;
				dispatchEvent(new Event("widthChanged"));
			}
		}
		protected function get $width():Number
		{
			return super.width;
		}

		private var _height:Number;
		override public function get height():Number
		{
			return _height;
		}
		override public function set height(value:Number):void
		{
			if (_height != value)
			{
				_height = value;
				dispatchEvent(new Event("heightChanged"));
			}
		}
		protected function get $height():Number
		{
			return super.height;
		}

		private var _model:IBeadModel;
		public function get model():IBeadModel
		{
			return _model;
		}
		public function set model(value:IBeadModel):void
		{
			if (_model != value)
			{
				addBead(value as IBead);
				dispatchEvent(new Event("modelChanged"));
			}
		}

		private var _id:String;
		public function get id():String
		{
			return _id;
		}
		public function set id(value:String):void
		{
			if (_id != value)
			{
				_id = value;
				dispatchEvent(new Event("idChanged"));
			}
		}

		// beads declared in MXML are added to the strand.
		// from AS, just call addBead()
		public var beads:Array;

		private var strand:Vector.<IBead>;
		public function addBead(bead:IBead):void
		{
			if (!strand)
				strand = new Vector.<IBead>;
			strand.push(bead);
			if (bead is IBeadModel)
				_model = bead as IBeadModel;
			bead.strand = this;
		}

		public function getBeadByType(classOrInterface:Class):IBead
		{
			for each (var bead:IBead in strand)
			{
				if (bead is classOrInterface)
					return bead;
			}
			return null;
		}

		public function removeBead(value:IBead):IBead
		{
			var n:int = strand.length;
			for (var i:int = 0; i < n; i++)
			{
				var bead:IBead = strand[i];
				if (bead == value)
				{
					strand.splice(i, 1);
					return bead;
				}
			}
			return null;
		}

		public function initModel():void
		{

		}

		public function addToParent(p:DisplayObjectContainer):void
		{
			p.addChild(this);
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;

	public class UIBase extends Sprite implements IInitModel, IStrand
	{
		public function UIBase()
		{
			super();
		}

		private var _width:Number;
		override public function get width():Number
		{
			return _width;
		}
		override public function set width(value:Number):void
		{
			if (_width != value)
			{
				_width = value;
				dispatchEvent(new Event("widthChanged"));
			}
		}
		protected function get $width():Number
		{
			return super.width;
		}

		private var _height:Number;
		override public function get height():Number
		{
			return _height;
		}
		override public function set height(value:Number):void
		{
			if (_height != value)
			{
				_height = value;
				dispatchEvent(new Event("heightChanged"));
			}
		}
		protected function get $height():Number
		{
			return super.height;
		}

		private var _model:IBeadModel;
		public function get model():IBeadModel
		{
			return _model;
		}
		public function set model(value:IBeadModel):void
		{
			if (_model != value)
			{
				addBead(value as IBead);
				dispatchEvent(new Event("modelChanged"));
			}
		}

		private var _id:String;
		public function get id():String
		{
			return _id;
		}
		public function set id(value:String):void
		{
			if (_id != value)
			{
				_id = value;
				dispatchEvent(new Event("idChanged"));
			}
		}

		// beads declared in MXML are added to the strand.
		// from AS, just call addBead()
		public var beads:Array;

		private var _beads:Vector.<IBead>;
		public function addBead(bead:IBead):void
		{
			if (!_beads)
				_beads = new Vector.<IBead>;
			_beads.push(bead);
			if (bead is IBeadModel)
				_model = bead as IBeadModel;
			bead.strand = this;
		}

		public function getBeadByType(classOrInterface:Class):IBead
		{
			for each (var bead:IBead in _beads)
			{
				if (bead is classOrInterface)
					return bead;
			}
			return null;
		}

		public function removeBead(value:IBead):IBead
		{
			var n:int = _beads.length;
			for (var i:int = 0; i < n; i++)
			{
				var bead:IBead = _beads[i];
				if (bead == value)
				{
					_beads.splice(i, 1);
					return bead;
				}
			}
			return null;
		}

		public function initModel():void
		{

		}

		public function addToParent(p:DisplayObjectContainer):void
		{
			p.addChild(this);
		}
	}
}

Change internal storage name so that beads can host other beads.

git-svn-id: 00225d326fbeb9978ee2ea3564602c0fe18eb5d2@1440062 13f79535-47bb-0310-9956-ffa450edef68


/*
 * FLINT PARTICLE SYSTEM
 * .....................
 *
 * Author: Richard Lord
 * Copyright (c) Richard Lord 2008-2011
 * http://flintparticles.org
 *
 *
 * Licence Agreement
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.flintparticles.twoD.actions
{
	import org.flintparticles.common.actions.ActionBase;
	import org.flintparticles.common.emitters.Emitter;
	import org.flintparticles.common.particles.Particle;
	import org.flintparticles.twoD.particles.Particle2D;
	import org.flintparticles.twoD.zones.Zone2D;

	import flash.geom.Point;

	[DefaultProperty("zone")]

	/**
	 * The TweenToZone action adjusts the particle's position between two
	 * locations as it ages. The start location is wherever the particle starts
	 * from, depending on the emitter and the initializers. The end position is
	 * a random point within the specified zone. The current position is relative
	 * to the particle's energy,
	 * which changes as the particle ages in accordance with the energy easing
	 * function used. This action should be used in conjunction with the Age action.
	 */

	public class TweenToZone extends ActionBase
	{
		private var _zone:Zone2D;

		/**
		 * The constructor creates a TweenToZone action for use by an emitter.
		 * To add a TweenToZone to all particles created by an emitter, use the
		 * emitter's addAction method.
		 *
		 * @see org.flintparticles.common.emitters.Emitter#addAction()
		 *
		 * @param zone The zone for the particle's position when its energy is 0.
		 */
		public function TweenToZone( zone:Zone2D )
		{
			_zone = zone;
		}

		/**
		 * The zone for the particle's position when its energy is 0.
		 */
		public function get zone():Zone2D
		{
			return _zone;
		}
		public function set zone( value:Zone2D ):void
		{
			_zone = value;
		}

		/**
		 * Calculates the current position of the particle based on it's energy.
		 *
		 *
This method is called by the emitter and need not be called by the
		 * user.

		 *
		 * @param emitter The Emitter that created the particle.
		 * @param particle The particle to be updated.
		 * @param time The duration of the frame - used for time based updates.
		 *
		 * @see org.flintparticles.common.actions.Action#update()
		 */
		override public function update( emitter:Emitter, particle:Particle, time:Number ):void
		{
			var p:Particle2D = Particle2D( particle );
			var data:TweenToZoneData;
			if( ! p.dictionary[this] )
			{
				var pt:Point = _zone.getLocation();
				data = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
				p.dictionary[this] = data;
			}
			else
			{
				data = p.dictionary[this];
			}
			p.x = data.endX + data.diffX * p.energy;
			p.y = data.endY + data.diffY * p.energy;
		}
	}
}

class TweenToZoneData
{
	public var diffX:Number;
	public var diffY:Number;
	public var endX:Number;
	public var endY:Number;

	public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
	{
		this.diffX = startX - endX;
		this.diffY = startY - endY;
		this.endX = endX;
		this.endY = endY;
	}
}

/*
 * FLINT PARTICLE SYSTEM
 * .....................
 *
 * Author: Richard Lord
 * Copyright (c) Richard Lord 2008-2011
 * http://flintparticles.org
 *
 *
 * Licence Agreement
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.flintparticles.twoD.actions
{
	import org.flintparticles.common.actions.ActionBase;
	import org.flintparticles.common.emitters.Emitter;
	import org.flintparticles.common.initializers.Initializer;
	import org.flintparticles.common.particles.Particle;
	import org.flintparticles.twoD.particles.Particle2D;
	import org.flintparticles.twoD.zones.Zone2D;

	import flash.geom.Point;

	[DefaultProperty("zone")]

	/**
	 * The TweenToZone action adjusts the particle's position between two
	 * locations as it ages. The start location is wherever the particle starts
	 * from, depending on the emitter and the initializers. The end position is
	 * a random point within the specified zone. The current position is relative
	 * to the particle's energy,
	 * which changes as the particle ages in accordance with the energy easing
	 * function used. This action should be used in conjunction with the Age action.
	 */

	public class TweenToZone extends ActionBase implements Initializer
	{
		private var _zone:Zone2D;

		/**
		 * The constructor creates a TweenToZone action for use by an emitter.
		 * To add a TweenToZone to all particles created by an emitter, use the
		 * emitter's addAction method.
		 *
		 * @see org.flintparticles.common.emitters.Emitter#addAction()
		 *
		 * @param zone The zone for the particle's position when its energy is 0.
		 */
		public function TweenToZone( zone:Zone2D )
		{
			_zone = zone;
			priority = -10;
		}

		/**
		 * The zone for the particle's position when its energy is 0.
		 */
		public function get zone():Zone2D
		{
			return _zone;
		}
		public function set zone( value:Zone2D ):void
		{
			_zone = value;
		}

		/**
		 *
		 */
		override public function addedToEmitter( emitter:Emitter ):void
		{
			if( ! emitter.hasInitializer( this ) )
			{
				emitter.addInitializer( this );
			}
		}

		override public function removedFromEmitter( emitter:Emitter ):void
		{
			emitter.removeInitializer( this );
		}

		/**
		 *
		 */
		public function initialize( emitter:Emitter, particle:Particle ):void
		{
			var p:Particle2D = Particle2D( particle );
			var pt:Point = _zone.getLocation();
			var data:TweenToZoneData = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
			p.dictionary[this] = data;
		}

		/**
		 * Calculates the current position of the particle based on it's energy.
		 *
		 *
This method is called by the emitter and need not be called by the
		 * user.

		 *
		 * @param emitter The Emitter that created the particle.
		 * @param particle The particle to be updated.
		 * @param time The duration of the frame - used for time based updates.
		 *
		 * @see org.flintparticles.common.actions.Action#update()
		 */
		override public function update( emitter:Emitter, particle:Particle, time:Number ):void
		{
			var p:Particle2D = Particle2D( particle );
			if( ! p.dictionary[this] )
			{
				initialize( emitter, particle );
			}
			var data:TweenToZoneData = p.dictionary[this];
			p.x = data.endX + data.diffX * p.energy;
			p.y = data.endY + data.diffY * p.energy;
		}
	}
}

class TweenToZoneData
{
	public var diffX:Number;
	public var diffY:Number;
	public var endX:Number;
	public var endY:Number;

	public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
	{
		this.diffX = startX - endX;
		this.diffY = startY - endY;
		this.endX = endX;
		this.endY = endY;
	}
}

Modify TweenToZone to ensure it restarts each time


/**
  * LzKeyboardKernel.lzs
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic AS2
  */

// Receives keyboard events from the runtime
class LzKeyboardKernelClass
{
    function __keyboardEvent ( e, t ){
        var delta = {};
        var s, k = e.keyCode;
        var keyisdown = t == 'onkeydown';
        s = String.fromCharCode(k).toLowerCase();
        if (keyisdown) {
            // prevent duplicate onkeydown events - see LPP-7432
            if (k == __lastkeydown) return;
            __lastkeydown = k;
        } else {
            __lastkeydown = null;
        }
        delta[s] = keyisdown;
        if (this.__callback) this.__scope[this.__callback](delta, k, t);
    }

    var __callback = null;
    var __scope = null;
    var __lastkeydown = null;

    function setCallback (scope, funcname) {
        this.__scope = scope;
        this.__callback = funcname;
    }
    // Called by lz.Keys when the last focusable element was reached.
    function gotLastFocus() {
    }
} // End of LzKeyboardKernelClass

var LzKeyboardKernel = new LzKeyboardKernelClass ();

/**
  * LzKeyboardKernel.lzs
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic AS2
  */

// Receives keyboard events from the runtime
class LzKeyboardKernelClass
{
    function __keyboardEvent ( e, t ){
        var delta = {};
        var s, k = e.keyCode;
        var keyisdown = t == 'onkeydown';
        s = String.fromCharCode(k).toLowerCase();

        // prevent duplicate onkeydown events - see LPP-7432
        if (__keyState[k] == keyisdown) return;
        __keyState[k] = keyisdown;

        delta[s] = keyisdown;
        if (this.__callback) this.__scope[this.__callback](delta, k, t);
    }

    var __callback = null;
    var __scope = null;
    var __keyState:Object = {};

    function setCallback (scope, funcname) {
        this.__scope = scope;
        this.__callback = funcname;
    }
    // Called by lz.Keys when the last focusable element was reached.
    function gotLastFocus() {
    }
} // End of LzKeyboardKernelClass

var LzKeyboardKernel = new LzKeyboardKernelClass ();

Change 20081218-maxcarlson-N by maxcarlson@Bank.lan on 2008-12-18 18:19:24 PST
    in /Users/maxcarlson/openlaszlo/trunk-clean
    for http://svn.openlaszlo.org/openlaszlo/trunk

Summary: Better prevention of duplicate key events in swf9

Bugs Fixed: LPP-7432 - onkeydown event keep firing

Technical Reviewer: andre.bargull@udo.edu
QA Reviewer: promanik

Details: Use a hash to track keyboard state, to handle modifier keys accurately.

Tests: See LPP-7432

git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12194 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c


package com.kaltura.hls.m2ts
{
    import flash.utils.ByteArray;
    import flash.net.ObjectEncoding;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;

    /**
     * Responsible for emitting FLV data. Also handles AAC conversion
     * config and buffering.
     */
    public class FLVTranscoder
    {
        public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;

        public var callback:Function;

        private var lastTagSize:uint = 0;

        private var _aacConfig:ByteArray;
        private var _aacRemainder:ByteArray;
        private var _aacTimestamp:Number = 0;

        public function clear(clearAACConfig:Boolean = false):void
        {
            if(clearAACConfig)
                _aacConfig = null;
            _aacRemainder = null;
            _aacTimestamp = 0;
        }

        private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
        {
            var tag:ByteArray = new ByteArray();
            tag.position = 0;
            var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
            var cursor:uint = 0;

            if(msgLength > 0xffffff)
                return; // too big for the length field

            tag.length = FLVTags.HEADER_LENGTH + msgLength;
            tag[cursor++] = type;
            tag[cursor++] = (msgLength >> 16) & 0xff;
            tag[cursor++] = (msgLength >>  8) & 0xff;
            tag[cursor++] = (msgLength      ) & 0xff;
            tag[cursor++] = (flvts >> 16) & 0xff;
            tag[cursor++] = (flvts >>  8) & 0xff;
            tag[cursor++] = (flvts      ) & 0xff;
            tag[cursor++] = (flvts >> 24) & 0xff;
            tag[cursor++] = 0x00; // stream ID
            tag[cursor++] = 0x00;
            tag[cursor++] = 0x00;

            if(codec >= 0)
                tag[cursor++] = codec;
            if(mode >= 0)
                tag[cursor++] = mode;

            tag.position = cursor;
            tag.writeBytes(bytes, offset, length);

            cursor += length;
            msgLength += 11; // account for message header in back pointer

            tag.writeUnsignedInt(lastTagSize);

            lastTagSize = tag.length;

            // Dispatch tag.
            if(callback != null)
                callback(flvts, tag);

        }

        public function convertFLVTimestamp(pts:Number):Number
        {
            return pts / 90.0;
        }

        private static var flvGenerationBuffer:ByteArray = new ByteArray();
        private static var keyFrame:Boolean = false;
        private static var totalAppended:int = 0;

        private function naluConverter(bytes:ByteArray, cursor:uint, length:uint):void
        {
            // Check for a NALU that is keyframe type.
            var naluType:uint = bytes[cursor] & 0x1f;
            trace(naluType + " length=" + length);
            switch(naluType)
            {
                case 0x09: // "access unit delimiter"
                    switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
                    {
                        case 0:
                        case 3:
                        case 5:
                            keyFrame = true;
                            break;
                        default:
                            keyFrame = false;
                            break;
                    }
                    break;

                default:
                    // Infer keyframe state.
                    if(naluType == 5)
                        keyFrame = true;
                    else if(naluType == 1)
                        keyFrame = false;
            }

            // Append.
            flvGenerationBuffer.writeUnsignedInt(length);
            flvGenerationBuffer.writeBytes(bytes, cursor, length);
            totalAppended += length;
        }

        /**
         * Convert and amit AVC NALU data.
         */
        public function convert(unit:NALU):void
        {
            // Accumulate NALUs into buffer.
            flvGenerationBuffer.length = 3;
            flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
            flvGenerationBuffer[1] = (tsu >>  8) & 0xff;
            flvGenerationBuffer[2] = (tsu      ) & 0xff;
            flvGenerationBuffer.position = 3;

            totalAppended = 0;
            keyFrame = false;

            // Emit an AVCC and walk the NALUs.
            var avcc:ByteArray = NALUProcessor.extractAVCC(unit, naluConverter);
            if(avcc)
                sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);

            trace("Appended " + totalAppended + " bytes");

            // Finish writing and sending packet.
            var flvts:uint = convertFLVTimestamp(unit.pts);
            var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);

            var codec:uint;
            if(keyFrame)
                codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
            else
                codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;

            //trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
            sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
        }

        private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
        {
            var curPos:uint;

            if(b1.length != b2.length)
                return false;

            for(curPos = 0; curPos < b1.length; curPos++)
            {
                if(b1[curPos] != b2[curPos])
                    return false;
            }

            return true;
        }

        private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
        {
            var isNewConfig:Boolean = true;
            var audioSpecificConfig:ByteArray = new ByteArray();
            var audioObjectType:uint;

            audioSpecificConfig.length = 2;

            switch(profile)
            {
                case 0x00:
                    audioObjectType = 0x01;
                    break;
                case 0x01:
                    audioObjectType = 0x02;
                    break;
                case 0x02:
                    audioObjectType = 0x03;
                    break;
                default:
                    return;
            }

            audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
            audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);

            if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
                isNewConfig = false;

            if(!isNewConfig)
                return;

            _aacConfig = audioSpecificConfig;
            sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
        }

        /**
         * Convert and amit AAC data.
         */
        public function convertAAC(pes:PESPacket):void
        {
            var timeAccumulation:Number = 0.0;
            var limit:uint;
            var stream:ByteArray;
            var hadRemainder:Boolean = false;
            var cursor:int = 0;
            var length:int = pes.buffer.length;
            var bytes:ByteArray = pes.buffer;
            var timestamp:Number = pes.pts;

            if(_aacRemainder)
            {
                stream = _aacRemainder;
                stream.writeBytes(bytes, cursor, length);
                cursor = 0;
                length = stream.length;
                _aacRemainder = null;
                hadRemainder = true;
                timeAccumulation = _aacTimestamp - timestamp;
            }
            else
                stream = bytes;

            limit = cursor + length;

            // an AAC PES packet can contain multiple ADTS frames
            while(cursor < limit)
            {
                var remaining:uint = limit - cursor;
                var sampleRateIndex:uint;
                var sampleRate:Number = undefined;
                var profile:uint;
                var channelConfig:uint;
                var frameLength:uint;

                if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
                    break;

                // search for syncword
                if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
                {
                    cursor++;
                    continue;
                }

                frameLength  = (stream[cursor + 3] & 0x03) << 11;
                frameLength += (stream[cursor + 4]) << 3;
                frameLength += (stream[cursor + 5] >> 5) & 0x07;

                // Check for an invalid ADTS header; if so look for next syncword.
                if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
                {
                    cursor++;
                    continue;
                }

                // Skip it till next PES packet.
                if(frameLength > remaining)
                    break;

                profile = (stream[cursor + 2] >> 6) & 0x03;

                sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
                switch(sampleRateIndex)
                {
                    case 0x00:
                        sampleRate = 96000.0;
                        break;
                    case 0x01:
                        sampleRate = 88200.0;
                        break;
                    case 0x02:
                        sampleRate = 64000.0;
                        break;
                    case 0x03:
                        sampleRate = 48000.0;
                        break;
                    case 0x04:
                        sampleRate = 44100.0;
                        break;
                    case 0x05:
                        sampleRate = 32000.0;
                        break;
                    case 0x06:
                        sampleRate = 24000.0;
                        break;
                    case 0x07:
                        sampleRate = 22050.0;
                        break;
                    case 0x08:
                        sampleRate = 16000.0;
                        break;
                    case 0x09:
                        sampleRate = 12000.0;
                        break;
                    case 0x0a:
                        sampleRate = 11025.0;
                        break;
                    case 0x0b:
                        sampleRate = 8000.0;
                        break;
                    case 0x0c:
                        sampleRate = 7350.0;
                        break;
                }

                channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);

                if(sampleRate)
                {
                    var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);

                    sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
                    //trace("Sending AAC");
                    sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);

                    timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame

                    if(hadRemainder)
                    {
                        timeAccumulation = 0.0;
                        hadRemainder = false;
                    }
                }

                cursor += frameLength;
            }

            if(cursor < limit)
            {
                //trace("AAC timestamp was " + _aacTimestamp);
                _aacRemainder = new ByteArray();
                _aacRemainder.writeBytes(stream, cursor, limit - cursor);
                _aacTimestamp = timestamp + timeAccumulation;
                //trace("AAC timestamp now " + _aacTimestamp);
            }
        }

        /**
         * Convert and amit MP3 data.
         */
        public function convertMP3(pes:PESPacket):void
        {
            sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
        }

        private function generateScriptData(values:Array):ByteArray
        {
            var bytes:ByteArray = new ByteArray();
            bytes.objectEncoding = ObjectEncoding.AMF0;

            for each (var object:Object in values)
                bytes.writeObject(object);

            return bytes;
        }

        private function sendScriptDataFLVTag(flvts:uint, values:Array):void
        {
            var bytes:ByteArray = generateScriptData(values);
            sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
        }

        /**
         * Fire off a subtitle caption.
         */
        public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
        {
            //var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
            //sendScriptDataFLVTag( timeStamp * 1000, captionObject);

            // We need to strip the timestamp off of the text data
            captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);

            var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
            sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
        }

    }
}

package com.kaltura.hls.m2ts
{
    import flash.utils.ByteArray;
    import flash.net.ObjectEncoding;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;

    /**
     * Responsible for emitting FLV data. Also handles AAC conversion
     * config and buffering.
     */
    public class FLVTranscoder
    {
        public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;

        public var callback:Function;

        private var lastTagSize:uint = 0;

        private var _aacConfig:ByteArray;
        private var _aacRemainder:ByteArray;
        private var _aacTimestamp:Number = 0;

        public function clear(clearAACConfig:Boolean = false):void
        {
            if(clearAACConfig)
                _aacConfig = null;
            _aacRemainder = null;
            _aacTimestamp = 0;
        }

        private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
        {
            var tag:ByteArray = new ByteArray();
            tag.position = 0;
            var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
            var cursor:uint = 0;

            if(msgLength > 0xffffff)
                return; // too big for the length field

            tag.length = FLVTags.HEADER_LENGTH + msgLength;
            tag[cursor++] = type;
            tag[cursor++] = (msgLength >> 16) & 0xff;
            tag[cursor++] = (msgLength >>  8) & 0xff;
            tag[cursor++] = (msgLength      ) & 0xff;
            tag[cursor++] = (flvts >> 16) & 0xff;
            tag[cursor++] = (flvts >>  8) & 0xff;
            tag[cursor++] = (flvts      ) & 0xff;
            tag[cursor++] = (flvts >> 24) & 0xff;
            tag[cursor++] = 0x00; // stream ID
            tag[cursor++] = 0x00;
            tag[cursor++] = 0x00;

            if(codec >= 0)
                tag[cursor++] = codec;
            if(mode >= 0)
                tag[cursor++] = mode;

            tag.position = cursor;
            tag.writeBytes(bytes, offset, length);

            cursor += length;
            msgLength += 11; // account for message header in back pointer

            tag.writeUnsignedInt(lastTagSize);

            lastTagSize = tag.length;

            // Dispatch tag.
            if(callback != null)
                callback(flvts, tag);

        }

        public function convertFLVTimestamp(pts:Number):Number
        {
            return pts / 90.0;
        }

        private static var flvGenerationBuffer:ByteArray = new ByteArray();
        private static var keyFrame:Boolean = false;
        private static var totalAppended:int = 0;

        private function naluConverter(bytes:ByteArray, cursor:uint, length:uint):void
        {
            // Check for a NALU that is keyframe type.
            var naluType:uint = bytes[cursor] & 0x1f;
            //trace(naluType + " length=" + length);
            switch(naluType)
            {
                case 0x09: // "access unit delimiter"
                    switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
                    {
                        case 0:
                        case 3:
                        case 5:
                            keyFrame = true;
                            break;
                        default:
                            keyFrame = false;
                            break;
                    }
                    break;

                default:
                    // Infer keyframe state.
                    if(naluType == 5)
                        keyFrame = true;
                    else if(naluType == 1)
                        keyFrame = false;
            }

            // Append.
            flvGenerationBuffer.writeUnsignedInt(length);
            flvGenerationBuffer.writeBytes(bytes, cursor, length);
            totalAppended += length;
        }

        /**
         * Convert and amit AVC NALU data.
         */
        public function convert(unit:NALU):void
        {
            // Accumulate NALUs into buffer.
            flvGenerationBuffer.length = 3;
            flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
            flvGenerationBuffer[1] = (tsu >>  8) & 0xff;
            flvGenerationBuffer[2] = (tsu      ) & 0xff;
            flvGenerationBuffer.position = 3;

            totalAppended = 0;
            keyFrame = false;

            // Emit an AVCC and walk the NALUs.
            var avcc:ByteArray = NALUProcessor.extractAVCC(unit, naluConverter);
            if(avcc)
                sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);

           // trace("Appended " + totalAppended + " bytes");

            // Finish writing and sending packet.
            var flvts:uint = convertFLVTimestamp(unit.pts);
            var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);

            var codec:uint;
            if(keyFrame)
                codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
            else
                codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;

            //trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
            sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
        }

        private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
        {
            var curPos:uint;

            if(b1.length != b2.length)
                return false;

            for(curPos = 0; curPos < b1.length; curPos++)
            {
                if(b1[curPos] != b2[curPos])
                    return false;
            }

            return true;
        }

        private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
        {
            var isNewConfig:Boolean = true;
            var audioSpecificConfig:ByteArray = new ByteArray();
            var audioObjectType:uint;

            audioSpecificConfig.length = 2;

            switch(profile)
            {
                case 0x00:
                    audioObjectType = 0x01;
                    break;
                case 0x01:
                    audioObjectType = 0x02;
                    break;
                case 0x02:
                    audioObjectType = 0x03;
                    break;
                default:
                    return;
            }

            audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
            audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);

            if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
                isNewConfig = false;

            if(!isNewConfig)
                return;

            _aacConfig = audioSpecificConfig;
            sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
        }

        /**
         * Convert and amit AAC data.
         */
        public function convertAAC(pes:PESPacket):void
        {
            var timeAccumulation:Number = 0.0;
            var limit:uint;
            var stream:ByteArray;
            var hadRemainder:Boolean = false;
            var cursor:int = 0;
            var length:int = pes.buffer.length;
            var bytes:ByteArray = pes.buffer;
            var timestamp:Number = pes.pts;

            if(_aacRemainder)
            {
                stream = _aacRemainder;
                stream.writeBytes(bytes, cursor, length);
                cursor = 0;
                length = stream.length;
                _aacRemainder = null;
                hadRemainder = true;
                timeAccumulation = _aacTimestamp - timestamp;
            }
            else
                stream = bytes;

            limit = cursor + length;

            // an AAC PES packet can contain multiple ADTS frames
            while(cursor < limit)
            {
                var remaining:uint = limit - cursor;
                var sampleRateIndex:uint;
                var sampleRate:Number = undefined;
                var profile:uint;
                var channelConfig:uint;
                var frameLength:uint;

                if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
                    break;

                // search for syncword
                if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
                {
                    cursor++;
                    continue;
                }

                frameLength  = (stream[cursor + 3] & 0x03) << 11;
                frameLength += (stream[cursor + 4]) << 3;
                frameLength += (stream[cursor + 5] >> 5) & 0x07;

                // Check for an invalid ADTS header; if so look for next syncword.
                if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
                {
                    cursor++;
                    continue;
                }

                // Skip it till next PES packet.
                if(frameLength > remaining)
                    break;

                profile = (stream[cursor + 2] >> 6) & 0x03;

                sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
                switch(sampleRateIndex)
                {
                    case 0x00:
                        sampleRate = 96000.0;
                        break;
                    case 0x01:
                        sampleRate = 88200.0;
                        break;
                    case 0x02:
                        sampleRate = 64000.0;
                        break;
                    case 0x03:
                        sampleRate = 48000.0;
                        break;
                    case 0x04:
                        sampleRate = 44100.0;
                        break;
                    case 0x05:
                        sampleRate = 32000.0;
                        break;
                    case 0x06:
                        sampleRate = 24000.0;
                        break;
                    case 0x07:
                        sampleRate = 22050.0;
                        break;
                    case 0x08:
                        sampleRate = 16000.0;
                        break;
                    case 0x09:
                        sampleRate = 12000.0;
                        break;
                    case 0x0a:
                        sampleRate = 11025.0;
                        break;
                    case 0x0b:
                        sampleRate = 8000.0;
                        break;
                    case 0x0c:
                        sampleRate = 7350.0;
                        break;
                }

                channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);

                if(sampleRate)
                {
                    var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);

                    sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
                    //trace("Sending AAC");
                    sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);

                    timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame

                    if(hadRemainder)
                    {
                        timeAccumulation = 0.0;
                        hadRemainder = false;
                    }
                }

                cursor += frameLength;
            }

            if(cursor < limit)
            {
                //trace("AAC timestamp was " + _aacTimestamp);
                _aacRemainder = new ByteArray();
                _aacRemainder.writeBytes(stream, cursor, limit - cursor);
                _aacTimestamp = timestamp + timeAccumulation;
                //trace("AAC timestamp now " + _aacTimestamp);
            }
        }

        /**
         * Convert and amit MP3 data.
         */
        public function convertMP3(pes:PESPacket):void
        {
            sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
        }

        private function generateScriptData(values:Array):ByteArray
        {
            var bytes:ByteArray = new ByteArray();
            bytes.objectEncoding = ObjectEncoding.AMF0;

            for each (var object:Object in values)
                bytes.writeObject(object);

            return bytes;
        }

        private function sendScriptDataFLVTag(flvts:uint, values:Array):void
        {
            var bytes:ByteArray = generateScriptData(values);
            sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
        }

        /**
         * Fire off a subtitle caption.
         */
        public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
        {
            //var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
            //sendScriptDataFLVTag( timeStamp * 1000, captionObject);

            // We need to strip the timestamp off of the text data
            captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);

            var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
            sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
        }

    }
}

Disable some spam.

Disable some spam.


package aerys.minko.render.shader
{
	import aerys.minko.ns.minko;
	import aerys.minko.render.renderer.state.RendererState;
	import aerys.minko.render.resource.Program3DResource;
	import aerys.minko.render.resource.Texture3DResource;
	import aerys.minko.render.shader.compiler.Compiler;
	import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
	import aerys.minko.render.shader.node.INode;
	import aerys.minko.render.shader.node.leaf.AbstractParameter;
	import aerys.minko.render.shader.node.leaf.StyleParameter;
	import aerys.minko.render.shader.node.leaf.TransformParameter;
	import aerys.minko.render.shader.node.leaf.WorldParameter;
	import aerys.minko.scene.data.StyleStack;
	import aerys.minko.scene.data.TransformData;
	import aerys.minko.scene.data.ViewportData;
	import aerys.minko.type.math.Matrix3D;
	import aerys.minko.type.math.Vector4;
	import aerys.minko.type.stream.format.VertexComponent;

	import flash.geom.Vector3D;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;

	public class Shader
	{
		use namespace minko;

		protected var _resource					: Program3DResource;

		protected var _lastFrameId				: uint;
		protected var _lastStyleStackVersion	: uint;
		protected var _lastTransformVersion		: uint;

		protected var _vsConstData				: Vector.<Number>;
		protected var _fsConstData				: Vector.<Number>;
		protected var _vsParams					: Vector.<ParameterAllocation>;
		protected var _fsParams					: Vector.<ParameterAllocation>;
		protected var _samplers					: Vector.<int>;

		public function get resource() : Program3DResource
		{
			return _resource;
		}

		public static function create(outputPosition	: INode,
									  outputColor		: INode) : Shader
		{
			var compiler : Compiler = new Compiler();

			compiler.load(outputPosition, outputColor);

			return compiler.compileShader();
		}

		public function Shader(vertexShader				: ByteArray,
							   fragmentShader			: ByteArray,
							   vertexInputComponents	: Vector.<VertexComponent>,
							   vertexInputIndices		: Vector.<uint>,
							   samplers					: Vector.<int>,
							   vertexConstantData		: Vector.<Number>,
							   fragmentConstantData		: Vector.<Number>,
							   vertexParameters			: Vector.<ParameterAllocation>,
							   fragmentParameters		: Vector.<ParameterAllocation>)
		{
			_lastFrameId			= uint.MAX_VALUE;
			_lastStyleStackVersion	= uint.MAX_VALUE;
			_lastTransformVersion	= uint.MAX_VALUE;

			_vsConstData	= vertexConstantData;
			_fsConstData	= fragmentConstantData;
			_vsParams		= vertexParameters;
			_fsParams		= fragmentParameters;
			_samplers		= samplers;

			_resource 		= new Program3DResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
		}

		public function fillRenderState(state		: RendererState,
										styleStack	: StyleStack,
										local		: TransformData,
										world		: Dictionary) : Boolean
		{
			if (_lastFrameId != world[ViewportData].frameId)
			{
				_lastFrameId			= world[ViewportData].frameId;
				_lastStyleStackVersion	= uint.MAX_VALUE;
				_lastTransformVersion	= uint.MAX_VALUE;
			}

			setTextures(state, styleStack, local, world);
			setConstants(state, styleStack, local, world);

			state.shader = _resource;
			_lastStyleStackVersion	= styleStack.version;
			_lastTransformVersion	= local.version;

			return true;
		}

		protected function setTextures(state		: RendererState,
									   styleStack	: StyleStack,
								   	   transformData	: TransformData,
									   worldData	: Object) : void
		{
			var texture 		: Texture3DResource	= null;
			var samplerStyleId 	: int				= 0;
			var samplerCount 	: uint 				= _samplers.length;

			for (var i : int = 0; i < samplerCount; ++i)
			{
				samplerStyleId	= _samplers[i];
				texture			= styleStack.get(samplerStyleId) as Texture3DResource;

				state.setTextureAt(i, texture);
			}
		}

		protected function setConstants(state		: RendererState,
									    styleStack	: StyleStack,
										local		: TransformData,
										world		: Dictionary) : void
		{
			updateConstData(_vsConstData, _vsParams, styleStack, local, world);
			updateConstData(_fsConstData, _fsParams, styleStack, local, world);

			state.setVertexConstants(_vsConstData);
			state.setFragmentConstants(_fsConstData);
		}

		protected function updateConstData(constData	: Vector.<Number>,
										   paramsAllocs	: Vector.<ParameterAllocation>,
										   styleStack	: StyleStack,
										   local		: TransformData,
										   world		: Dictionary) : void
		{
			var paramLength	: int = paramsAllocs.length;

			for (var i : int = 0; i < paramLength; ++i)
			{
				var paramAlloc	: ParameterAllocation	= paramsAllocs[i];
				var param		: AbstractParameter		= paramAlloc._parameter;

				if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
					(param is TransformParameter && local.version == _lastTransformVersion))
					continue;

				var data : Object = getParameterData(param, styleStack, local, world);

				loadParameterData(paramAlloc, constData, data);
			}
		}

		private function getParameterData(param			: AbstractParameter,
										  styleStack	: StyleStack,
										  local			: TransformData,
										  world			: Dictionary) : Object
		{
			if (param is StyleParameter)
			{
				if (param._index != -1)
					return styleStack.get(param._key as int).getItem(param._index)[param._field];
				else if (param._field != null)
					return styleStack.get(param._key as int)[param._field];
				else
					return styleStack.get(param._key as int, null);
			}
			else if (param is WorldParameter)
			{
				var paramClass : Class = WorldParameter(param)._class;

				if (param._index != -1)
					return world[paramClass].getItem(param._index)[param._field];
				else if (param._field != null)
					return world[paramClass][param._field];
				else
					return world[paramClass];
			}
			else if (param is TransformParameter)
			{
				return local[param._key];
			}
			else
				throw new Error('Unknown parameter type');
		}

		private function loadParameterData(paramAlloc	: ParameterAllocation,
										   constData	: Vector.<Number>,
										   data			: Object) : void
		{
			var offset	: uint	= paramAlloc._offset;
			var size	: uint	= paramAlloc._parameter._size;

//			if (data is int)
			if (data is Number)
			{
				//var intData : int = data as int;
				var intData : Number = data as Number;

				if (size == 1)
				{
					constData[offset] = intData;
				}
				else if (size == 2)
				{
					constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
					constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
				}
				else if (size == 3)
				{
					constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
					constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
					constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
				}
				else if (size == 4)
				{
					constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
					constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
					constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
					constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
				}
			}
			/*else if (data is uint)
			{
				var uintData : uint = data as uint;

				if (size == 1)
				{
					constData[offset] = uintData;
				}
				else if (size == 2)
				{
					constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
					constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
				}
				else if (size == 3)
				{
					constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
					constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
					constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
				}
				else if (size == 4)
				{

					constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
					constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
					constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
					constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
				}
			}*/
			/*else if (data is Number)
			{
				if (size != 1)
					throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
						'defined as size=' + size + ' but only a Number was found');

				constData[offset] = data as Number;
			}*/
			else if (data is Vector4)
			{
				var vectorData : Vector3D = (data as Vector4)._vector;

				constData[offset] = vectorData.x;
				size >= 2 && (constData[int(offset + 1)] = vectorData.y);
				size >= 3 && (constData[int(offset + 2)] = vectorData.z);
				size >= 4 && (constData[int(offset + 3)] = vectorData.w);
			}
			else if (data is Matrix3D)
			{
				(data as Matrix3D).getRawData(constData, offset, true);
			}
			else if (data is Vector.<Vector4>)
			{
				var vectorVectorData		: Vector.<Vector4>	= data as Vector.<Vector4>;
				var vectorVectorDataLength	: uint				= vectorVectorData.length;

				for (var j : uint = 0; j < vectorVectorDataLength; ++j)
				{
					vectorData = vectorVectorData[j]._vector;

					constData[offset + 4 * j] = vectorData.x;
					constData[int(offset + 4 * j + 1)] = vectorData.y;
					constData[int(offset + 4 * j + 2)] = vectorData.z;
					constData[int(offset + 4 * j + 3)] = vectorData.w;
				}
			}
			else if (data is Vector.<Matrix3D>)
			{
				var matrixVectorData		: Vector.<Matrix3D>	= data as Vector.<Matrix3D>;
				var matrixVectorDataLength	: uint				= matrixVectorData.length;

				for (var i : uint = 0; i < matrixVectorDataLength; ++i)
					matrixVectorData[i].getRawData(constData, offset + i * 16, true);
			}
			else if (data == null)
			{
				throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
					'null and required by automatic shader');
			}
			else
			{
				throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
					'neither a int, a Number, a Vector4 or a Matrix3D. Unable to ' +
					'map it to a shader constant.');
			}
		}
	}
}

package aerys.minko.render.shader
{
	import aerys.minko.ns.minko;
	import aerys.minko.render.renderer.state.RendererState;
	import aerys.minko.render.resource.Program3DResource;
	import aerys.minko.render.resource.Texture3DResource;
	import aerys.minko.render.shader.compiler.Compiler;
	import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
	import aerys.minko.render.shader.node.INode;
	import aerys.minko.render.shader.node.leaf.AbstractParameter;
	import aerys.minko.render.shader.node.leaf.StyleParameter;
	import aerys.minko.render.shader.node.leaf.TransformParameter;
	import aerys.minko.render.shader.node.leaf.WorldParameter;
	import aerys.minko.scene.data.StyleStack;
	import aerys.minko.scene.data.TransformData;
	import aerys.minko.scene.data.ViewportData;
	import aerys.minko.type.math.Matrix3D;
	import aerys.minko.type.math.Vector4;
	import aerys.minko.type.stream.format.VertexComponent;

	import flash.geom.Vector3D;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;

	public class Shader
	{
		use namespace minko;

		protected var _resource					: Program3DResource;

		protected var _lastFrameId				: uint;
		protected var _lastStyleStackVersion	: uint;
		protected var _lastTransformVersion		: uint;

		protected var _vsConstData				: Vector.<Number>;
		protected var _fsConstData				: Vector.<Number>;
		protected var _vsParams					: Vector.<ParameterAllocation>;
		protected var _fsParams					: Vector.<ParameterAllocation>;
		protected var _samplers					: Vector.<int>;

		public function get resource() : Program3DResource
		{
			return _resource;
		}

		public static function create(outputPosition	: INode,
									  outputColor		: INode) : Shader
		{
			var compiler : Compiler = new Compiler();

			compiler.load(outputPosition, outputColor);

			return compiler.compileShader();
		}

		public function Shader(vertexShader				: ByteArray,
							   fragmentShader			: ByteArray,
							   vertexInputComponents	: Vector.<VertexComponent>,
							   vertexInputIndices		: Vector.<uint>,
							   samplers					: Vector.<int>,
							   vertexConstantData		: Vector.<Number>,
							   fragmentConstantData		: Vector.<Number>,
							   vertexParameters			: Vector.<ParameterAllocation>,
							   fragmentParameters		: Vector.<ParameterAllocation>)
		{
			_lastFrameId			= uint.MAX_VALUE;
			_lastStyleStackVersion	= uint.MAX_VALUE;
			_lastTransformVersion	= uint.MAX_VALUE;

			_vsConstData	= vertexConstantData;
			_fsConstData	= fragmentConstantData;
			_vsParams		= vertexParameters;
			_fsParams		= fragmentParameters;
			_samplers		= samplers;

			_resource 		= new Program3DResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
		}

		public function fillRenderState(state		: RendererState,
										styleStack	: StyleStack,
										local		: TransformData,
										world		: Dictionary) : Boolean
		{
			if (_lastFrameId != world[ViewportData].frameId)
			{
				_lastFrameId			= world[ViewportData].frameId;
				_lastStyleStackVersion	= uint.MAX_VALUE;
				_lastTransformVersion	= uint.MAX_VALUE;
			}

			setTextures(state, styleStack, local, world);
			setConstants(state, styleStack, local, world);

			state.shader = _resource;
			_lastStyleStackVersion	= styleStack.version;
			_lastTransformVersion	= local.version;

			return true;
		}

		protected function setTextures(state		: RendererState,
									   styleStack	: StyleStack,
								   	   transformData	: TransformData,
									   worldData	: Object) : void
		{
			var texture 		: Texture3DResource	= null;
			var samplerStyleId 	: int				= 0;
			var samplerCount 	: uint 				= _samplers.length;

			for (var i : int = 0; i < samplerCount; ++i)
			{
				samplerStyleId	= _samplers[i];
				texture			= styleStack.get(samplerStyleId) as Texture3DResource;

				state.setTextureAt(i, texture);
			}
		}

		protected function setConstants(state		: RendererState,
									    styleStack	: StyleStack,
										local		: TransformData,
										world		: Dictionary) : void
		{
			updateConstData(_vsConstData, _vsParams, styleStack, local, world);
			updateConstData(_fsConstData, _fsParams, styleStack, local, world);

			state.setVertexConstants(_vsConstData);
			state.setFragmentConstants(_fsConstData);
		}

		protected function updateConstData(constData	: Vector.<Number>,
										   paramsAllocs	: Vector.<ParameterAllocation>,
										   styleStack	: StyleStack,
										   local		: TransformData,
										   world		: Dictionary) : void
		{
			var paramLength	: int = paramsAllocs.length;

			for (var i : int = 0; i < paramLength; ++i)
			{
				var paramAlloc	: ParameterAllocation	= paramsAllocs[i];
				var param		: AbstractParameter		= paramAlloc._parameter;

				if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
					(param is TransformParameter && local.version == _lastTransformVersion))
					continue;

				var data : Object = getParameterData(param, styleStack, local, world);

				loadParameterData(paramAlloc, constData, data);
			}
		}

		private function getParameterData(param			: AbstractParameter,
										  styleStack	: StyleStack,
										  local			: TransformData,
										  world			: Dictionary) : Object
		{
			if (param is StyleParameter)
			{
				if (param._index != -1)
					return styleStack.get(param._key as int).getItem(param._index)[param._field];
				else if (param._field != null)
					return styleStack.get(param._key as int)[param._field];
				else
					return styleStack.get(param._key as int, null);
			}
			else if (param is WorldParameter)
			{
				var paramClass : Class = WorldParameter(param)._class;

				if (param._index != -1)
					return world[paramClass].getItem(param._index)[param._field];
				else if (param._field != null)
					return world[paramClass][param._field];
				else
					return world[paramClass];
			}
			else if (param is TransformParameter)
			{
				return local[param._key];
			}
			else
				throw new Error('Unknown parameter type');
		}

		private function loadParameterData(paramAlloc	: ParameterAllocation,
										   constData	: Vector.<Number>,
										   data			: Object) : void
		{
			var offset	: uint	= paramAlloc._offset;
			var size	: uint	= paramAlloc._parameter._size;

//			if (data is int)
			if (data is Number)
			{
				//var intData : int = data as int;
				var intData : Number = data as Number;

				if (size == 1)
				{
					constData[offset] = intData;
				}
				else if (size == 2)
				{
					constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
					constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
				}
				else if (size == 3)
				{
					constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
					constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
					constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
				}
				else if (size == 4)
				{
					constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
					constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
					constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
					constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
				}
			}
			/*else if (data is uint)
			{
				var uintData : uint = data as uint;

				if (size == 1)
				{
					constData[offset] = uintData;
				}
				else if (size == 2)
				{
					constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
					constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
				}
				else if (size == 3)
				{
					constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
					constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
					constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
				}
				else if (size == 4)
				{

					constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
					constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
					constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
					constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
				}
			}*/
			/*else if (data is Number)
			{
				if (size != 1)
					throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
						'defined as size=' + size + ' but only a Number was found');

				constData[offset] = data as Number;
			}*/
			else if (data is Vector4)
			{
				var vectorData : Vector3D = (data as Vector4)._vector;

				constData[offset] = vectorData.x;
				size >= 2 && (constData[int(offset + 1)] = vectorData.y);
				size >= 3 && (constData[int(offset + 2)] = vectorData.z);
				size >= 4 && (constData[int(offset + 3)] = vectorData.w);
			}
			else if (data is Matrix3D)
			{
				(data as Matrix3D).getRawData(constData, offset, true);
			}
			else if (data is Vector.<Vector4>)
			{
				var vectorVectorData		: Vector.<Vector4>	= data as Vector.<Vector4>;
				var vectorVectorDataLength	: uint				= vectorVectorData.length;

				for (var j : uint = 0; j < vectorVectorDataLength; ++j)
				{
					vectorData = vectorVectorData[j]._vector;

					constData[offset + 4 * j] = vectorData.x;
					constData[int(offset + 4 * j + 1)] = vectorData.y;
					constData[int(offset + 4 * j + 2)] = vectorData.z;
					constData[int(offset + 4 * j + 3)] = vectorData.w;
				}
			}
			else if (data is Vector.<Matrix3D>)
			{
				var matrixVectorData		: Vector.<Matrix3D>	= data as Vector.<Matrix3D>;
				var matrixVectorDataLength	: uint				= matrixVectorData.length;

				for (var i : uint = 0; i < matrixVectorDataLength; ++i)
					matrixVectorData[i].getRawData(constData, offset + i * 16, true);
			}
			else if (data == null)
			{
				throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
					'null and required by automatic shader');
			}
			else
			{
				throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
					'neither a int, a Number, a Vector4 or a Matrix3D. Unable to ' +
					'map it to a shader constant.');
			}
		}
	}
}

Remove useless import.

Remove useless import.


////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;

import mx.core.mx_internal;
import mx.managers.SystemManager;
import mx.utils.Platform;

use namespace mx_internal;

/**
 *  The RuntimeDPIProvider class provides the default mapping of
 *  similar device DPI values into predefined DPI classes.
 *  An Application may have its runtimeDPIProvider property set to a
 *  subclass of RuntimeDPIProvider to override Flex's default mappings.
 *  Overriding Flex's default mappings will cause changes in the Application's
 *  automatic scaling behavior.
 *
 *
Overriding Flex's default mappings is usually only necessary for devices
 *  that incorrectly report their screenDPI and for devices that may scale better
 *  in a different DPI class.

 *
 *
Flex's default mappings are:
 *

 *
160 DPI	<140 DPI

 *
160 DPI	>=140 DPI and <=200 DPI

 *
240 DPI	>=200 DPI and <=280 DPI

 *
320 DPI	>=280 DPI and <=400 DPI

 *
480 DPI	>=400 DPI and <=560 DPI

 *
640 DPI	>=640 DPI

 *

 *

 *
 *
 *
 *
Subclasses of RuntimeDPIProvider should only depend on runtime APIs
 *  and should not depend on any classes specific to the Flex framework except
 *  mx.core.DPIClassification.

 *
 *  @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
 *  @includeExample examples/RuntimeDPIProviderExample.as -noswf
 *  @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
 *
 *  @see mx.core.DPIClassification
 *  @see spark.components.Application#applicationDPI
 *
 *  @langversion 3.0
 *  @playerversion Flash 10
 *  @playerversion AIR 2.5
 *  @productversion Flex 4.5
 */
public class RuntimeDPIProvider
{

    mx_internal static const IPAD_MAX_EXTENT:int = 1024;
    mx_internal static const IPAD_RETINA_MAX_EXTENT: int = 2048;

    /**
     *  Constructor.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10
     *  @playerversion AIR 2.5
     *  @productversion Flex 4.5
     */
    public function RuntimeDPIProvider()
    {
    }

    /**
     *  Returns the runtime DPI of the current device by mapping its
     *  flash.system.Capabilities.screenDPI to one of several DPI
     *  values in mx.core.DPIClassification.
     *
     *  A number of devices can have slightly different DPI values and Flex maps these
     *  into the several DPI classes.
     *
     *  Flex uses this method to calculate the current DPI value when an Application
     *  authored for a specific DPI is adapted to the current one through scaling.
     *
     *
 Exceptions:

     *

     *
All non-retina iPads  receive 160 DPI

     *
All retina iPads  receive 320 DPI

     *

     *
     *  @param dpi The DPI value.
     *  @return The corresponding DPIClassification value.
     *                                                                               isI
     *  @see flash.system.Capabilities
     *  @see mx.core.DPIClassification
     *
     *  @langversion 3.0
     *  @playerversion Flash 10
     *  @playerversion AIR 2.5
     *  @productversion Flex 4.5
     */

    public function get runtimeDPI():Number
    {
        var isIOS:Boolean = Platform.isIOS;
        var screenDPI:Number = Capabilities.screenDPI;

        if (isIOS) // as isIPad returns false in the simulator
		{
            var root:DisplayObject = SystemManager.getSWFRoot(this);
            if (root != null )  {
                var stage:Stage = root.stage;
                if (stage != null){
                    var scX:Number = stage.fullScreenWidth;
                    var scY:Number = stage.fullScreenHeight;
                    /*  as of Dec 2013,  iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
                     cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
                     * */
                    if ((scX == IPAD_RETINA_MAX_EXTENT || scY == IPAD_RETINA_MAX_EXTENT))
                        return DPIClassification.DPI_320;
                    else if (scX == IPAD_MAX_EXTENT || scY == IPAD_MAX_EXTENT)
                        return DPIClassification.DPI_160;
                }
            }
        }

        return classifyDPI(screenDPI);
    }

    /**
     *  @private
     *  Matches the specified DPI to a DPIClassification value.
     *  A number of devices can have slightly different DPI values and classifyDPI
     *  maps these into the several DPI classes.
     *
     *  This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
     *  to calculate DPI classes.
     *
     *  @param dpi The DPI value.
     *  @return The corresponding DPIClassification value.
     */
    mx_internal static function classifyDPI(dpi:Number):Number
    {
		if (dpi <= 140)
			return DPIClassification.DPI_120;

        if (dpi <= 200)
            return DPIClassification.DPI_160;

        if (dpi <= 280)
            return DPIClassification.DPI_240;

		if (dpi <= 400)
			return DPIClassification.DPI_320;

		if (dpi <= 560)
			return DPIClassification.DPI_480;

        return DPIClassification.DPI_640;
    }
}
}

////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;

import mx.core.mx_internal;
import mx.managers.SystemManager;
import mx.utils.Platform;

use namespace mx_internal;

/**
 *  The RuntimeDPIProvider class provides the default mapping of
 *  similar device DPI values into predefined DPI classes.
 *  An Application may have its runtimeDPIProvider property set to a
 *  subclass of RuntimeDPIProvider to override Flex's default mappings.
 *  Overriding Flex's default mappings will cause changes in the Application's
 *  automatic scaling behavior.
 *
 *
Overriding Flex's default mappings is usually only necessary for devices
 *  that incorrectly report their screenDPI and for devices that may scale better
 *  in a different DPI class.

 *
 *
Flex's default mappings are:
 *

 *
160 DPI	<140 DPI

 *
160 DPI	>=140 DPI and <=200 DPI

 *
240 DPI	>=200 DPI and <=280 DPI

 *
320 DPI	>=280 DPI and <=400 DPI

 *
480 DPI	>=400 DPI and <=560 DPI

 *
640 DPI	>=640 DPI

 *

 *

 *
 *
 *
 *
Subclasses of RuntimeDPIProvider should only depend on runtime APIs
 *  and should not depend on any classes specific to the Flex framework except
 *  mx.core.DPIClassification.

 *
 *  @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
 *  @includeExample examples/RuntimeDPIProviderExample.as -noswf
 *  @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
 *
 *  @see mx.core.DPIClassification
 *  @see spark.components.Application#applicationDPI
 *
 *  @langversion 3.0
 *  @playerversion Flash 10
 *  @playerversion AIR 2.5
 *  @productversion Flex 4.5
 */
public class RuntimeDPIProvider
{

    mx_internal static const IPAD_MAX_EXTENT:int = 1024;
    mx_internal static const IPAD_RETINA_MAX_EXTENT: int = 2048;

    /**
     *  Constructor.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10
     *  @playerversion AIR 2.5
     *  @productversion Flex 4.5
     */
    public function RuntimeDPIProvider()
    {
    }

    /**
     *  Returns the runtime DPI of the current device by mapping its
     *  flash.system.Capabilities.screenDPI to one of several DPI
     *  values in mx.core.DPIClassification.
     *
     *  A number of devices can have slightly different DPI values and Flex maps these
     *  into the several DPI classes.
     *
     *  Flex uses this method to calculate the current DPI value when an Application
     *  authored for a specific DPI is adapted to the current one through scaling.
     *
     *
 Exceptions:

     *

     *
All non-retina iPads  receive 160 DPI

     *
All retina iPads  receive 320 DPI

     *

     *
     *  @param dpi The DPI value.
     *  @return The corresponding DPIClassification value.
     *                                                                               isI
     *  @see flash.system.Capabilities
     *  @see mx.core.DPIClassification
     *
     *  @langversion 3.0
     *  @playerversion Flash 10
     *  @playerversion AIR 2.5
     *  @productversion Flex 4.5
     */

    public function get runtimeDPI():Number
	{
		if (Platform.isIOS) // as isIPad returns false in the simulator
		{
			var scX:Number = Capabilities.screenResolutionX;
			var scY:Number = Capabilities.screenResolutionY;

			// Use the stage width/height only when debugging, because Capabilities reports the computer resolution
			if (Capabilities.isDebugger)
			{
				var root:DisplayObject = SystemManager.getSWFRoot(this);
				if (root && root.stage)
				{
					scX = root.stage.fullScreenWidth;
					scY = root.stage.fullScreenHeight;
				}
			}

			/*  as of Dec 2013,  iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
			cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
			* */
			if (scX == IPAD_MAX_EXTENT || scY == IPAD_MAX_EXTENT)
				return DPIClassification.DPI_160;
			else if ((scX == IPAD_RETINA_MAX_EXTENT || scY == IPAD_RETINA_MAX_EXTENT))
				return DPIClassification.DPI_320;
		}

		return classifyDPI(Capabilities.screenDPI);
	}

    /**
     *  @private
     *  Matches the specified DPI to a DPIClassification value.
     *  A number of devices can have slightly different DPI values and classifyDPI
     *  maps these into the several DPI classes.
     *
     *  This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
     *  to calculate DPI classes.
     *
     *  @param dpi The DPI value.
     *  @return The corresponding DPIClassification value.
     */
    mx_internal static function classifyDPI(dpi:Number):Number
    {
		if (dpi <= 140)
			return DPIClassification.DPI_120;

        if (dpi <= 200)
            return DPIClassification.DPI_160;

        if (dpi <= 280)
            return DPIClassification.DPI_240;

		if (dpi <= 400)
			return DPIClassification.DPI_320;

		if (dpi <= 560)
			return DPIClassification.DPI_480;

        return DPIClassification.DPI_640;
    }
}
}

Fix for https://issues.apache.org/jira/browse/FLEX-34556 (thanks to Jorn Nolles)


package com.axis.http {
  import com.axis.rtspclient.ByteArrayUtils;
  import com.axis.Logger;

  import flash.utils.ByteArray;

  public class request {

    public static function readHeaders(dataInput:*, buffer:ByteArray):* {
      dataInput.readBytes(buffer, buffer.length);

      var index:int = ByteArrayUtils.indexOf(buffer, "\r\n\r\n");
      if (index === -1) {
        /* Not a full request yet */
        return false;
      }

      var dummy:ByteArray = new ByteArray();
      buffer.readBytes(dummy, 0, index + 4);

      var parsed:Object = parse(dummy.toString());
      if (parsed.headers['content-length'] &&
          int(parsed.headers['content-length']) > buffer.bytesAvailable) {
        /* Headers parsed fine, but full body is not here yet. */
        buffer.position = 0;
        return false;
      }

      return parsed;
    }

    public static function parse(data:String):Object {
      var ret:Object = {};

      var lines:Array = data.split('\r\n');
      var statusRegex:RegExp = /^(?P<proto>[^\/]+)\/(?P<version>[^ ]+) (?P<code>[0-9]+) (?P<message>.*)$/;
      var status:Array = statusRegex.exec(lines.shift());

      if (status) {
        /* statusRegex will fail if this is multipart block (in which case these parameters are not valid) */
        ret.proto = status.proto;
        ret.version = status.version;
        ret.code = uint(status.code);
        ret.message = status.message;
      }

      ret.headers = {};
      for each (var header:String in lines) {
        if (header.length === 0) continue;

        var t:Array = header.split(':');
        var key:String = t.shift().replace(/^[\s]*(.*)[\s]*$/, '$1').toLowerCase();
        var val:String = t.join(':').replace(/^[\s]*(.*)[\s]*$/, '$1');
        parseMiddleware(key, val, ret.headers);
      }

      return ret;
    }

    private static function parseMiddleware(key:String, val:String, hdr:Object):void {
      switch (key) {
        case 'www-authenticate':
          if (!hdr['www-authenticate'])
            hdr['www-authenticate'] = {};

          if (/^basic/i.test(val)) {
            var basicRealm:RegExp = /realm=\"([^\"]+)\"/i;
            hdr['www-authenticate'].basicRealm = basicRealm.exec(val)[1];
          }

          if (/^digest/i.test(val)) {
            var params:Array = val.substr(7).split(/,\s*/);
            for each (var p:String in params) {
              var kv:Array = p.split('=');
              if (2 !== kv.length) continue;

              if (kv[0].toLowerCase() === 'realm') kv[0] = 'digestRealm';
              hdr['www-authenticate'][kv[0]] = kv[1].replace(/^"(.*)"$/, '$1');
            }
          }

          break;
        default:
          /* In the default case, just take the value as-is */
          hdr[key] = val;
      }
    }
  }
}

package com.axis.http {
  import com.axis.rtspclient.ByteArrayUtils;
  import com.axis.Logger;

  import flash.utils.ByteArray;

  public class request {

    public static function readHeaders(dataInput:*, buffer:ByteArray):* {
      dataInput.readBytes(buffer, buffer.length);

      var index:int = ByteArrayUtils.indexOf(buffer, "\r\n\r\n");
      if (index === -1) {
        /* Not a full request yet */
        return false;
      }

      var dummy:ByteArray = new ByteArray();
      buffer.readBytes(dummy, 0, index + 4);

      var parsed:Object = parse(dummy.toString());
      if (parsed.headers['content-length'] &&
          int(parsed.headers['content-length']) > buffer.bytesAvailable) {
        /* Headers parsed fine, but full body is not here yet. */
        buffer.position = 0;
        return false;
      }

      return parsed;
    }

    public static function parse(data:String):Object {
      var ret:Object = {};

      var lines:Array = data.split('\r\n');
      var statusRegex:RegExp = /^(?P<proto>[^\/]+)\/(?P<version>[^ ]+) (?P<code>[0-9]+) (?P<message>.*)$/;
      var status:Array = statusRegex.exec(lines.shift());

      if (status) {
        /* statusRegex will fail if this is multipart block (in which case these parameters are not valid) */
        ret.proto = status.proto;
        ret.version = status.version;
        ret.code = uint(status.code);
        ret.message = status.message;
      }

      ret.headers = {};
      for each (var header:String in lines) {
        if (header.length === 0) continue;

        var t:Array = header.split(':');
        var key:String = t.shift().replace(/^[\s]*(.*)[\s]*$/, '$1').toLowerCase();
        var val:String = t.join(':').replace(/^[\s]*(.*)[\s]*$/, '$1');
        parseMiddleware(key, val, ret.headers);
      }

      return ret;
    }

    private static function parseMiddleware(key:String, val:String, hdr:Object):void {
      switch (key) {
        case 'www-authenticate':
          if (!hdr['www-authenticate'])
            hdr['www-authenticate'] = {};

          if (/^basic/i.test(val)) {
            var basicRealm:RegExp = /realm="([^"]*)"/i;
            hdr['www-authenticate'].basicRealm = basicRealm.exec(val)[1];
          }

          if (/^digest/i.test(val)) {
            var params:Array = val.substr(7).split(/,\s*/);
            for each (var p:String in params) {
              var kv:Array = p.split('=');
              if (2 !== kv.length) continue;

              if (kv[0].toLowerCase() === 'realm') kv[0] = 'digestRealm';
              hdr['www-authenticate'][kv[0]] = kv[1].replace(/^"(.*)"$/, '$1');
            }
          }

          break;
        default:
          /* In the default case, just take the value as-is */
          hdr[key] = val;
      }
    }
  }
}

Correct regex. Also value might be empty


package aerys.minko.type
{
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.ui.Mouse;

	public final class MouseManager
	{
		private var _x					: Number			= 0.;
		private var _y					: Number			= 0.;

		private var _leftButtonDown		: Boolean			= false;
		private var _middleButtonDown	: Boolean			= false;
		private var _rightButtonDown	: Boolean			= false;

		private var _mouseDown			: Signal			= new Signal("mouseDown");
		private var _mouseUp			: Signal			= new Signal("mouseUp");

		private var _cursors			: Vector.<String>	= new <String>[];

		public function get x() : Number
		{
			return _x;
		}

		public function get y() : Number
		{
			return _y;
		}

		public function get leftButtonDown() : Boolean
		{
			return _leftButtonDown;
		}

		public function get middleButtonDown() : Boolean
		{
			return _middleButtonDown;
		}

		public function get rightButtonDown() : Boolean
		{
			return _rightButtonDown;
		}

		public function get cursor() : String
		{
			return Mouse.cursor;
		}

		public function get mouseDown() : Signal
		{
			return _mouseDown;
		}

		public function get mouseUp() : Signal
		{
			return _mouseUp;
		}

		public function bind(dispatcher : IEventDispatcher) : void
		{
			dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
			dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);

			if (MouseEvent.RIGHT_CLICK != null)
			{
				dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
				dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
			}

			if (MouseEvent.MIDDLE_CLICK != null)
			{
				dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
				dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
			}
		}

		public function unbind(dispatcher : IEventDispatcher) : void
		{
			dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
			dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);

			if (MouseEvent.RIGHT_CLICK != null)
			{
				dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
				dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
			}

			if (MouseEvent.MIDDLE_CLICK != null)
			{
				dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
				dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
			}
		}

		private function mouseMoveHandler(event : MouseEvent) : void
		{
			_x = event.localX;
			_y = event.localY;
		}

		private function mouseLeftDownHandler(event : MouseEvent) : void
		{
			_leftButtonDown = true;
			_mouseDown.execute();
		}

		private function mouseLeftUpHandler(event : MouseEvent) : void
		{
			_leftButtonDown = false;
			_mouseUp.execute();
		}

		private function mouseMiddleDownHandler(event : MouseEvent) : void
		{
			_rightButtonDown = true;
		}

		private function mouseMiddleUpHandler(event : MouseEvent) : void
		{
			_rightButtonDown = false;
		}

		private function mouseRightDownHandler(event : MouseEvent) : void
		{
			_rightButtonDown = true;
		}

		private function mouseRightUpHandler(event : MouseEvent) : void
		{
			_rightButtonDown = false;
		}

		public function pushCursor(cursor : String) : MouseManager
		{
			_cursors.push(Mouse.cursor);
			Mouse.cursor = cursor;

			return this;
		}

		public function popCursor() : MouseManager
		{
			Mouse.cursor = _cursors.pop();

			return this;
		}
	}
}

package aerys.minko.type
{
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.ui.Mouse;

	public final class MouseManager
	{
		private var _x					: Number			= 0.;
		private var _y					: Number			= 0.;

		private var _leftButtonDown		: Boolean			= false;
		private var _middleButtonDown	: Boolean			= false;
		private var _rightButtonDown	: Boolean			= false;

		private var _mouseDown			: Signal			= new Signal("mouseDown");
		private var _mouseUp			: Signal			= new Signal("mouseUp");

		private var _cursors			: Vector.<String>	= new <String>[];

		public function get x() : Number
		{
			return _x;
		}

		public function get y() : Number
		{
			return _y;
		}

		public function get leftButtonDown() : Boolean
		{
			return _leftButtonDown;
		}

		public function get middleButtonDown() : Boolean
		{
			return _middleButtonDown;
		}

		public function get rightButtonDown() : Boolean
		{
			return _rightButtonDown;
		}

		public function get cursor() : String
		{
			return Mouse.cursor;
		}

		public function get mouseDown() : Signal
		{
			return _mouseDown;
		}

		public function get mouseUp() : Signal
		{
			return _mouseUp;
		}

		public function bind(dispatcher : IEventDispatcher) : void
		{
			dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
			dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);

			if (MouseEvent.RIGHT_CLICK != null)
			{
				dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
				dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
			}

			if (MouseEvent.MIDDLE_CLICK != null)
			{
				dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
				dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
			}
		}

		public function unbind(dispatcher : IEventDispatcher) : void
		{
			dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
			dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);

			if (MouseEvent.RIGHT_CLICK != null)
			{
				dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
				dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
			}

			if (MouseEvent.MIDDLE_CLICK != null)
			{
				dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
				dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
			}
		}

		private function mouseMoveHandler(event : MouseEvent) : void
		{
			_x = event.localX;
			_y = event.localY;
		}

		private function mouseLeftDownHandler(event : MouseEvent) : void
		{
			_leftButtonDown = true;
			_mouseDown.execute();
		}

		private function mouseLeftUpHandler(event : MouseEvent) : void
		{
			_leftButtonDown = false;
			_mouseUp.execute();
		}

		private function mouseMiddleDownHandler(event : MouseEvent) : void
		{
			_middleButtonDown = true;
		}

		private function mouseMiddleUpHandler(event : MouseEvent) : void
		{
			_middleButtonDown = false;
		}

		private function mouseRightDownHandler(event : MouseEvent) : void
		{
			_rightButtonDown = true;
		}

		private function mouseRightUpHandler(event : MouseEvent) : void
		{
			_rightButtonDown = false;
		}

		public function pushCursor(cursor : String) : MouseManager
		{
			_cursors.push(Mouse.cursor);
			Mouse.cursor = cursor;

			return this;
		}

		public function popCursor() : MouseManager
		{
			Mouse.cursor = _cursors.pop();

			return this;
		}
	}
}

Update src/aerys/minko/type/MouseManager.as

Fixed bug in middle mouse button handler.