1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
| /*
FlvEncoder (leelib.util.flvEncoder.*)
Lee Felarca
http://www.zeropointnine.com/blog
3-2011
v0.9
Creates FLV's with video and audio.
FLV spec is described here: http://www.adobe.com/devnet/f4v.html
Example usage:
var flvEncoder:FlvEncoder = new FlvEncoder(_fps, _duration);
flvEncoder.setVideoProperties(_videoWidth, _videoHeight);
flvEncoder.setAudioProperties(FlvEncoder.SAMPLERATE_44KHZ, _is16Bit, _isStereo);
flvEncoder.begin();
for (var i:int = 0; i < _numFrames; i++)
{
flvEncoder.addFrame(_myBitmaps[i], _myChunksOfAudio[i]);
}
saveOutMyFile( flvEncoder.byteArray );
Source code licensed under a Creative Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/
Some Rights Reserved.
*/
package leelib.util.flvEncoder
{
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Endian;
public class FlvEncoder
{
public static const SAMPLERATE_11KHZ:uint = 11025;
public static const SAMPLERATE_22KHZ:uint = 22050;
public static const SAMPLERATE_44KHZ:uint = 44100;
public static const BLOCK_WIDTH:int = 32;
public static const BLOCK_HEIGHT:int = 32;
private var _frameRate:Number;
private var _duration:Number;
private var _hasVideo:Boolean;
private var _frameWidth:int;
private var _frameHeight:int;
private var _hasAudio:Boolean;
private var _sampleRate:uint;
private var _is16Bit:Boolean;
private var _isStereo:Boolean;
private var _isAudioInputFloats:Boolean;
private var _videoPayloadMaker:IVideoPayload;
private var _soundPropertiesByte:uint;
private var _audioFrameSize:uint;
private var _lastTagSize:uint = 0;
private var _frameNum:int = 0;
private var _ba:ByteArray;
//
/**
* @param $framesPerSecond Dictates the framerate of FLV playback.
* @param $durationInSeconds This value is only used for the metaData.
*/
public function FlvEncoder($framesPerSecond:Number,$durationInSeconds:Number=0):void
{
_frameRate = $framesPerSecond;
_duration = $durationInSeconds;
}
/**
* Defines the video dimensions to be used in the FLV.
* setVideoProperties() must be called before calling "start()"
*
* @param $width Width of each bitmapData to be supplied in addFrame()
* @param $height Width of each bitmapData to be supplied in addFrame()
*
* @param $customVideoPayloadMakerClass
* A custom video encoder class can be specified here.
* (For example, one that is Alchemy or Pixelbender-based).
*/
public function setVideoProperties($width:int, $height:int, $customVideoPayloadMakerClass:Class=null):void
{
if (_ba) {
throw new Error("setVideoProperties() must be called before begin()");
}
if (! $customVideoPayloadMakerClass) {
_videoPayloadMaker = new VideoPayloadMaker();
}
else {
_videoPayloadMaker = new $customVideoPayloadMakerClass();
if (! _videoPayloadMaker || ! (_videoPayloadMaker is IVideoPayload)) {
throw new Error("$customVideoPayloadMakerClass is not of type IVideoPayload");
}
}
if ($width > 0 && $height > 0) {
_frameWidth = $width;
_frameHeight = $height;
_hasVideo = true;
}
}
/**
* Defines the audio properties to be used in the FLV.
* setAudioProperties() must be called before calling "start()"
*
* @param $sampleRate Should be either SAMPLERATE_11KHZ, SAMPLERATE_22KHZ, or SAMPLERATE_44KHZ
* @param $is16Bit 16-bit audio will be expected if true, 8-bit if false
* @param $isStereo Two channel of audio will be expected if true, one (mono) if false
*
* @param $dataWillBeInFloats If set to true, audio data supplied to "addFrame()" will be assumed to be
* in floating point format and will be automatically converted to
* unsigned shortints for the FLV. (PCM audio coming from either WAV files or
* from webcam microphone input is in floating point format.)
*/
public function setAudioProperties($sampleRate:uint=0, $is16Bit:Boolean=false, $isStereo:Boolean=false, $dataWillBeInFloats:Boolean=true):void
{
if (_ba) {
throw new Error("setAudioProperties() must be called before begin()");
}
if ($sampleRate != SAMPLERATE_44KHZ && $sampleRate != SAMPLERATE_22KHZ && $sampleRate != SAMPLERATE_11KHZ) {
throw new Error("Invalid samplerate value. Use supplied constants (eg, SAMPLERATE_11KHZ)");
}
_sampleRate = $sampleRate;
_is16Bit = $is16Bit;
_isStereo = $isStereo;
_isAudioInputFloats = $dataWillBeInFloats;
var n:Number = _sampleRate * (_isStereo ? 2 : 1) * (_is16Bit ? 2 : 1);
n = n / _frameRate;
if (_isAudioInputFloats) n *= 2;
_audioFrameSize = int(n);
_soundPropertiesByte = makeSoundPropertiesByte();
_hasAudio = true;
}
/**
* Must be called after setVideoProperties and/or setAudioProperties
* and before addFrame() gets called.
*
* If setAudioProperties() is not called, the FLV is assumed to be video-only.
* If setVideoProperties() is not called, the FLV is assumed to be audio-only.
*/
public function start():void
{
if (_ba) throw new Error("begin() has already been called");
if (_hasVideo==false && _hasAudio==false) throw new Error("setVideoProperties() and/or setAudioProperties() must be called first");
_ba = new ByteArray();
// create header
_ba.writeBytes( makeHeader() );
// create metadata tag
_ba.writeUnsignedInt( _lastTagSize );
_ba.writeBytes( makeMetaDataTag() );
}
/**
* @param $bitmapData Dimensions should match those supplied in setVideoProperties.
* If creating an audio-only FLV, set to null.
*
* @param $pcmAudio Audio properties (bits per sample, channels per sample, and sample-rate)
* should match those supplied in setAudioProperties.
* If creating a video-only FLV, set to null.
*/
public function addFrame($bitmapData:BitmapData, $uncompressedAudio:ByteArray):void
{
if (! _ba) throw new Error("start() must be called first");
if (! _hasVideo && $bitmapData) throw new Error("Expecting null for argument 1 because video properties were not defined via setVideoProperties()");
if (! _hasAudio && $uncompressedAudio) throw new Error("Expecting null for argument 2 because audio properties were not defined via setAudioProperties()");
if (_hasVideo && ! $bitmapData) throw new Error("Expecting value for argument 1");
if (_hasAudio && ! $uncompressedAudio) throw new Error("Expecting value for argument 2");
if ($bitmapData) {
_ba.writeUnsignedInt(_lastTagSize);
writeVideoTagTo(_ba, $bitmapData);
}
if ($uncompressedAudio) {
_ba.writeUnsignedInt(_lastTagSize);
var b:ByteArray = _isAudioInputFloats ? floatsToSignedShorts($uncompressedAudio) : $uncompressedAudio;
writeAudioTagTo(_ba, b);
}
_frameNum++;
}
/**
* This is the fully-formed FLV.
*/
public function get byteArray():ByteArray
{
return _ba;
}
/**
* Convenience property returning the expected size in bytes of the
* audio data that should be supplied in the addFrame() method.
*/
public function get audioFrameSize():uint
{
return _audioFrameSize;
}
/**
* Convenience method to convert Sound.extract data or SampleDataEvent data
* into linear PCM format used for uncompressed FLV audio .
* I.e., converts normalized floats to signed shortints.
*/
public static function floatsToSignedShorts($ba:ByteArray):ByteArray
{
var out:ByteArray = new ByteArray();
out.endian = Endian.LITTLE_ENDIAN;
$ba.position = 0;
var num:int = $ba.length / 4;
for (var i:int = 0; i < num; i++)
{
var n:Number = $ba.readFloat();
var val:int = n * 32768;
out.writeShort(val);
}
return out;
}
//
private function makeHeader():ByteArray
{
var baHeader:ByteArray = new ByteArray();
baHeader.writeByte(0x46) // 'F'
baHeader.writeByte(0x4C) // 'L'
baHeader.writeByte(0x56) // 'V'
baHeader.writeByte(0x01) // Version 1
// streams: video and/or audio
var u:uint = 0;
if (_hasVideo) u += 1;
if (_hasAudio) u += 4;
baHeader.writeByte(u);
baHeader.writeUnsignedInt(0x09) // header length
return baHeader;
}
private function makeMetaDataTag():ByteArray
{
var baTag:ByteArray = new ByteArray();
var baMetaData:ByteArray = makeMetaData();
// tag 'header'
baTag.writeByte( 18 ); // tagType = script data
writeUI24(baTag, baMetaData.length); // data size
writeUI24(baTag, 0); // timestamp should be 0 for onMetaData tag
baTag.writeByte(0); // timestamp extended
writeUI24(baTag, 0); // streamID always 0
// payload
baTag.writeBytes( baMetaData );
_lastTagSize = baTag.length;
return baTag;
}
private function makeMetaData():ByteArray
{
// onMetaData info goes in a ScriptDataObject of data type 'ECMA Array'
var b:ByteArray = new ByteArray();
// ObjectNameType (always 2)
b.writeByte(2);
// ObjectName (type SCRIPTDATASTRING):
writeUI16(b, "onMetaData".length); // StringLength
b.writeUTFBytes( "onMetaData" ); // StringData
// ObjectData (type SCRIPTDATAVALUE):
b.writeByte(8); // Type (ECMA array = 8)
b.writeUnsignedInt(7) // // Elements in array
// SCRIPTDATAVARIABLES...
if (_duration > 0) {
writeUI16(b, "duration".length);
b.writeUTFBytes("duration");
b.writeByte(0);
b.writeDouble(_duration);
}
writeUI16(b, "width".length);
b.writeUTFBytes("width");
b.writeByte(0);
b.writeDouble(_frameWidth);
writeUI16(b, "height".length);
b.writeUTFBytes("height");
b.writeByte(0);
b.writeDouble(_frameHeight);
writeUI16(b, "framerate".length);
b.writeUTFBytes("framerate");
b.writeByte(0);
b.writeDouble(_frameRate);
writeUI16(b, "videocodecid".length);
b.writeUTFBytes("videocodecid");
b.writeByte(0);
b.writeDouble(3); // 'Screen Video' = 3
writeUI16(b, "canSeekToEnd".length);
b.writeUTFBytes("canSeekToEnd");
b.writeByte(1);
b.writeByte(int(true));
var mdc:String = "FlvEncoder v0.9 Lee Felarca";
writeUI16(b, "metadatacreator".length);
b.writeUTFBytes("metadatacreator");
b.writeByte(2);
writeUI16(b, mdc.length);
b.writeUTFBytes(mdc);
// VariableEndMarker1 (type UI24 - always 9) // temps video ??
writeUI24(b, 9);
return b;
}
private function writeVideoTagTo($ba:ByteArray, $bitmapData:BitmapData):void
{
var pos:int = $ba.position;
var ba:ByteArray = _videoPayloadMaker.make($bitmapData);
var timeStamp:uint = uint(1000/_frameRate * _frameNum);
// tag 'header'
$ba.writeByte( 0x09 ); // tagType = video
writeUI24($ba, ba.length); // data size
writeUI24($ba, timeStamp); // timestamp in ms
$ba.writeByte(0); // timestamp extended, no need
writeUI24($ba, 0); // streamID always 0
// payload
$ba.writeBytes( ba );
_lastTagSize = $ba.position - pos;
ba.length = 0;
ba = null;
}
private function writeAudioTagTo($ba:ByteArray, $pcmData:ByteArray):void
{
var pos:int = $ba.position;
$ba.writeByte( 0x08 ); // TagType - 8 = audio
writeUI24($ba, $pcmData.length+1); // DataSize ("+1" for header)
var timeStamp:uint = uint(1000/_frameRate * _frameNum);
writeUI24($ba, timeStamp); // Timestamp (ms)
$ba.writeByte(0); // TimestampExtended - not using
writeUI24($ba, 0); // StreamID - always 0
// AUDIODATA
$ba.writeByte(_soundPropertiesByte); // header
$ba.writeBytes($pcmData); // real sound data
_lastTagSize = $ba.position - pos;
}
private function makeSoundPropertiesByte():uint
{
var u:uint, val:int;
// soundformat [4 bits] - only supporting linear PCM little endian == 3
u = (3 << 4);
// soundrate [2 bits]
switch(_sampleRate) {
case SAMPLERATE_11KHZ: val = 1; break;
case SAMPLERATE_22KHZ: val = 2; break;
case SAMPLERATE_44KHZ: val = 3; break;
}
u += (val << 2);
// soundsize [1 bit] - 0 = 8bit; 1 = 16bit
val = _is16Bit ? 1 : 0;
u += (val << 1);
// soundtype [1 bit] - 0 = mono; 1 = stereo
val = _isStereo ? 1 : 0;
u += (val << 0);
// trace('FlvEncoder.makeSoundPropertiesByte():', u.toString(2));
return u;
}
public static function writeUI24(stream:*, p:uint):void
{
var byte1:int = p >> 16;
var byte2:int = p >> 8 & 0xff;
var byte3:int = p & 0xff;
stream.writeByte(byte1);
stream.writeByte(byte2);
stream.writeByte(byte3);
}
public static function writeUI16(stream:*, p:uint):void
{
stream.writeByte( p >> 8 )
stream.writeByte( p & 0xff );
}
public static function writeUI4_12(stream:*, p1:uint, p2:uint):void
{
// writes a 4-bit value followed by a 12-bit value in two bytes
var byte1a:int = p1 << 4;
var byte1b:int = p2 >> 8;
var byte1:int = byte1a + byte1b;
var byte2:int = p2 & 0xff;
stream.writeByte(byte1);
stream.writeByte(byte2);
}
}
} |
Partager