Brought up to date with the private repository (feea4c7)

This commit is contained in:
S committed 2026-10-14 20:57:33 +03:00
1 parent 1aa738d692
commit 1b1df1ae48
7925 files changed
+2617237 -20

No files matched your search

@@ -0,0 +1,64 @@
package org.osmf.net
{
public class DynamicStreamingItem
{
private var _bitrate:Number;
private var _stream:String;
private var _width:int;
private var _height:int;
public function DynamicStreamingItem(streamName:String, bitrate:Number, width:int = -1, height:int = -1)
{
super();
this._stream = streamName;
this._bitrate = bitrate;
this._width = width;
this._height = height;
}
public function get streamName() : String
{
return this._stream;
}
public function set streamName(value:String) : void
{
this._stream = value;
}
public function get bitrate() : Number
{
return this._bitrate;
}
public function set bitrate(value:Number) : void
{
this._bitrate = value;
}
public function get width() : int
{
return this._width;
}
public function set width(value:int) : void
{
this._width = value;
}
public function get height() : int
{
return this._height;
}
public function set height(value:int) : void
{
this._height = value;
}
}
}
@@ -0,0 +1,82 @@
package org.osmf.net
{
import org.osmf.utils.OSMFStrings;
public class DynamicStreamingResource extends StreamingURLResource
{
private var _streamItems:Vector.<DynamicStreamingItem>;
private var _initialIndex:int;
public function DynamicStreamingResource(host:String, streamType:String = null)
{
super(host,streamType);
this._initialIndex = 0;
}
public function get host() : String
{
return url;
}
public function get streamItems() : Vector.<DynamicStreamingItem>
{
if(this._streamItems == null)
{
this._streamItems = new Vector.<DynamicStreamingItem>();
}
return this._streamItems;
}
public function set streamItems(value:Vector.<DynamicStreamingItem>) : void
{
this._streamItems = value;
if(value != null)
{
value.sort(this.compareStreamItems);
}
}
public function get initialIndex() : int
{
return this._initialIndex;
}
public function set initialIndex(value:int) : void
{
if(this._streamItems == null || value >= this._streamItems.length)
{
throw new RangeError(OSMFStrings.getString(OSMFStrings.INVALID_PARAM));
}
this._initialIndex = value;
}
internal function indexFromName(name:String) : int
{
for(var i:int = 0; i < this._streamItems.length; i++)
{
if(this._streamItems[i].streamName.indexOf(name) == 0 || this._streamItems[i].streamName.indexOf("mp4:" + name) == 0)
{
return i;
}
}
return -1;
}
private function compareStreamItems(a:DynamicStreamingItem, b:DynamicStreamingItem) : Number
{
var result:Number = -1;
if(a.bitrate == b.bitrate)
{
result = 0;
}
else if(a.bitrate > b.bitrate)
{
result = 1;
}
return result;
}
}
}
@@ -0,0 +1,38 @@
package org.osmf.net
{
internal class FMSHost
{
private var _host:String;
private var _port:String;
public function FMSHost(host:String, port:String = "1935")
{
super();
this._host = host;
this._port = port;
}
public function get host() : String
{
return this._host;
}
public function set host(value:String) : void
{
this._host = value;
}
public function get port() : String
{
return this._port;
}
public function set port(value:String) : void
{
this._port = value;
}
}
}
@@ -0,0 +1,265 @@
package org.osmf.net
{
import org.osmf.utils.URL;
[ExcludeClass]
public class FMSURL extends URL
{
private static const APPNAME_START_INDEX:uint = 0;
private static const INSTANCENAME_START_INDEX:uint = 2;
private static const STREAMNAME_START_INDEX:uint = 4;
private static const DEFAULT_INSTANCE_NAME:String = "_definst_";
public static const MP4_STREAM:String = "mp4";
public static const MP3_STREAM:String = "mp3";
public static const ID3_STREAM:String = "id3";
public static const QUERY_STRING_STREAM:String = "streamName";
public static const QUERY_STRING_STREAMTYPE:String = "streamType";
private var _useInstance:Boolean;
private var _appName:String;
private var _instanceName:String;
private var _streamName:String;
private var _fileFormat:String;
private var _origins:Vector.<FMSHost>;
private var _edges:Vector.<FMSHost>;
public function FMSURL(url:String, useInstance:Boolean = false)
{
super(url);
this._useInstance = useInstance;
this._appName = "";
this._instanceName = "";
this._streamName = "";
this._fileFormat = "";
this.parsePath();
this.parseQuery();
}
public function get useInstance() : Boolean
{
return this._useInstance;
}
public function get appName() : String
{
return this._appName;
}
public function get instanceName() : String
{
return this._instanceName;
}
public function get streamName() : String
{
return this._streamName;
}
public function get fileFormat() : String
{
return this._fileFormat;
}
public function get edges() : Vector.<FMSHost>
{
return this._edges;
}
public function get origins() : Vector.<FMSHost>
{
return this._origins;
}
private function parsePath() : void
{
var definstPattern:RegExp = null;
var streamStartNdx:uint = 0;
var i:int = 0;
if(path == null || path.length == 0)
{
this._streamName = getParamValue(QUERY_STRING_STREAM);
this._fileFormat = getParamValue(QUERY_STRING_STREAMTYPE);
return;
}
var pattern:RegExp = /(\/)/;
var result:Array = path.split(pattern);
if(result != null)
{
this._appName = result[APPNAME_START_INDEX];
this._instanceName = "";
this._streamName = "";
definstPattern = new RegExp("^.*/" + DEFAULT_INSTANCE_NAME,"i");
if(path.search(definstPattern) > -1)
{
this._useInstance = true;
}
streamStartNdx = STREAMNAME_START_INDEX;
if(this._useInstance)
{
this._instanceName = result[INSTANCENAME_START_INDEX];
}
else
{
streamStartNdx = INSTANCENAME_START_INDEX;
}
for(i = int(streamStartNdx); i < result.length; i++)
{
this._streamName += result[i];
}
if(this._streamName == null || this._streamName == "")
{
this._streamName = getParamValue(QUERY_STRING_STREAM);
}
if(this._streamName.search(/^mp4:/i) > -1)
{
this._fileFormat = MP4_STREAM;
}
else if(this._streamName.search(/^mp3:/i) > -1)
{
this._fileFormat = MP3_STREAM;
}
else if(this._streamName.search(/^id3:/i) > -1)
{
this._fileFormat = ID3_STREAM;
}
if(this._fileFormat == null || this._fileFormat == "")
{
this._fileFormat = getParamValue(QUERY_STRING_STREAMTYPE);
}
}
var mp4PrefixStart:int = this._streamName.indexOf("/mp4:");
var mp3PrefixStart:int = this._streamName.indexOf("/mp3:");
var id3PrefixStart:int = this._streamName.indexOf("/id3:");
var prefixStart:int = -1;
if(mp4PrefixStart > 0)
{
prefixStart = mp4PrefixStart;
}
else if(mp3PrefixStart > 0)
{
prefixStart = mp3PrefixStart;
}
else if(id3PrefixStart > 0)
{
prefixStart = id3PrefixStart;
}
if(this.useInstance && prefixStart > 0)
{
this._instanceName += "/";
this._instanceName += this._streamName.substr(0,prefixStart);
this._streamName = this.streamName.substr(prefixStart + 1);
}
}
private function parseQuery() : void
{
var tempIndex:int = 0;
var tempNdex:int = 0;
var tempFMSURL:FMSURL = null;
if(query == null || query.length == 0 || query.search(/:\//) == -1)
{
return;
}
var edgeOriginURIs:Array = query.split("?");
for(var ndx:int = 0; ndx < edgeOriginURIs.length; ndx++)
{
tempIndex = int(edgeOriginURIs[ndx].toString().search(/:\//));
if(tempIndex == -1)
{
edgeOriginURIs.splice(ndx,1);
}
}
var hasEdge:Boolean = false;
var originIndex:int = 0;
if(edgeOriginURIs.length >= 2)
{
hasEdge = true;
originIndex = edgeOriginURIs.length - 1;
}
var tempSN:String = "";
var tempPN:String = "";
var colonIndex:int = 0;
var slashIndex:int = 0;
var startIndex:int = 0;
var endIndex:int = 0;
for(var i:int = 0; i < edgeOriginURIs.length; i++)
{
tempNdex = int(edgeOriginURIs[i].toString().search(/:\//));
startIndex = tempNdex + 2;
if(edgeOriginURIs[i].charAt(startIndex) == "/")
{
startIndex++;
}
colonIndex = int(edgeOriginURIs[i].indexOf(":",startIndex));
slashIndex = int(edgeOriginURIs[i].indexOf("/",startIndex));
if(slashIndex < 0 && colonIndex < 0)
{
tempSN = edgeOriginURIs[i].slice(startIndex);
}
else if(colonIndex >= 0 && colonIndex < slashIndex)
{
endIndex = colonIndex;
tempSN = edgeOriginURIs[i].slice(startIndex,endIndex);
startIndex = endIndex + 1;
endIndex = slashIndex;
tempPN = edgeOriginURIs[i].slice(startIndex,endIndex);
}
else if(edgeOriginURIs[i].indexOf("://") != -1)
{
endIndex = slashIndex;
tempSN = edgeOriginURIs[i].slice(startIndex,endIndex);
}
else
{
endIndex = int(edgeOriginURIs[i].indexOf("/"));
tempSN = "localhost";
}
if(i == originIndex)
{
if(this._origins == null)
{
this._origins = new Vector.<FMSHost>();
}
this._origins.push(new FMSHost(tempSN,tempPN));
tempFMSURL = new FMSURL(edgeOriginURIs[i],this._useInstance);
if(this._appName == "")
{
this._appName = tempFMSURL.appName;
}
if(this._useInstance && this._instanceName == "")
{
this._instanceName = tempFMSURL.instanceName;
}
if(this._streamName == "")
{
this._streamName = tempFMSURL.streamName;
}
}
else if(edgeOriginURIs[i] != query && hasEdge)
{
if(this._edges == null)
{
this._edges = new Vector.<FMSHost>();
}
this._edges.push(new FMSHost(tempSN,tempPN));
}
}
}
}
}
@@ -0,0 +1,20 @@
package org.osmf.net
{
import org.osmf.traits.TimeTrait;
[ExcludeClass]
public class ModifiableTimeTrait extends TimeTrait
{
public function ModifiableTimeTrait(duration:Number = NaN)
{
super(duration);
}
public function set duration(value:Number) : void
{
super.setDuration(value);
}
}
}
@@ -0,0 +1,70 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetGroup;
import flash.net.NetStream;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
public class MulticastNetLoader extends NetLoader
{
public function MulticastNetLoader(factory:NetConnectionFactoryBase = null)
{
var newFactory:NetConnectionFactory = null;
if(factory == null)
{
newFactory = new NetConnectionFactory();
newFactory.timeout = 60000;
}
super(factory != null ? factory : newFactory);
}
override public function canHandleResource(resource:MediaResourceBase) : Boolean
{
var rs:MulticastResource = resource as MulticastResource;
return rs != null && rs.groupspec != null && rs.groupspec.length > 0 && rs.streamName != null && rs.streamName.length > 0;
}
override protected function createNetStream(connection:NetConnection, resource:URLResource) : NetStream
{
var rs:MulticastResource = resource as MulticastResource;
return new NetStream(connection,rs.groupspec);
}
private function doProcessCreationComplete(connection:NetConnection, loadTrait:LoadTrait, factory:NetConnectionFactoryBase = null) : void
{
super.processCreationComplete(connection,loadTrait,factory);
}
override protected function processCreationComplete(connection:NetConnection, loadTrait:LoadTrait, factory:NetConnectionFactoryBase = null) : void
{
var netLoadTrait:NetStreamLoadTrait = null;
var netGroup:NetGroup = null;
var onNetStatus:Function = null;
onNetStatus = function(event:NetStatusEvent):void
{
switch(event.info.code)
{
case "NetGroup.Connect.Success":
connection.removeEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
netLoadTrait.netGroup = netGroup;
doProcessCreationComplete(connection,loadTrait,factory);
break;
case "NetGroup.Connect.Failed":
case "NetGroup.Connect.Rejected":
connection.removeEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
updateLoadTrait(loadTrait,LoadState.LOAD_ERROR);
}
};
netLoadTrait = loadTrait as NetStreamLoadTrait;
var multicastResource:MulticastResource = netLoadTrait.resource as MulticastResource;
connection.addEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
netGroup = new NetGroup(connection,multicastResource.groupspec);
}
}
}
@@ -0,0 +1,40 @@
package org.osmf.net
{
import flash.utils.ByteArray;
public class MulticastResource extends StreamingURLResource
{
private var _groupspec:String;
private var _streamName:String;
public function MulticastResource(url:String, groupspec:String = null, streamName:String = null, connectionArguments:Vector.<Object> = null, urlIncludesFMSApplicationInstance:Boolean = false, drmContentData:ByteArray = null)
{
super(url,StreamType.LIVE,NaN,NaN,connectionArguments,urlIncludesFMSApplicationInstance,drmContentData);
this._groupspec = groupspec;
this._streamName = streamName;
}
public function get groupspec() : String
{
return this._groupspec;
}
public function set groupspec(value:String) : void
{
this._groupspec = value;
}
public function get streamName() : String
{
return this._streamName;
}
public function set streamName(value:String) : void
{
this._streamName = value;
}
}
}
@@ -0,0 +1,117 @@
package org.osmf.net
{
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
use namespace flash_proxy;
public dynamic class NetClient extends Proxy
{
private var handlers:Dictionary = new Dictionary();
public function NetClient()
{
super();
}
public function addHandler(name:String, handler:Function, priority:int = 0) : void
{
var inserted:Boolean = false;
var i:int = 0;
var handlerWithPriority:Object = null;
var handlersForName:Array = this.handlers.hasOwnProperty(name) ? this.handlers[name] : (this.handlers[name] = []);
if(handlersForName.indexOf(handler) == -1)
{
inserted = false;
priority = Math.max(0,priority);
if(priority > 0)
{
for(i = 0; i < handlersForName.length; i++)
{
handlerWithPriority = handlersForName[i];
if(handlerWithPriority.priority < priority)
{
handlersForName.splice(i,0,{
"handler":handler,
"priority":priority
});
inserted = true;
break;
}
}
}
if(!inserted)
{
handlersForName.push({
"handler":handler,
"priority":priority
});
}
}
}
public function removeHandler(name:String, handler:Function) : void
{
var handlersForName:Array = null;
var i:int = 0;
var handlerWithPriority:Object = null;
if(this.handlers.hasOwnProperty(name))
{
handlersForName = this.handlers[name];
for(i = 0; i < handlersForName.length; i++)
{
handlerWithPriority = handlersForName[i];
if(handlerWithPriority.handler == handler)
{
handlersForName.splice(i,1);
break;
}
}
}
}
override flash_proxy function callProperty(methodName:*, ... args) : *
{
return this.invokeHandlers(methodName,args);
}
override flash_proxy function getProperty(name:*) : *
{
var result:* = undefined;
if(this.handlers.hasOwnProperty(name))
{
result = function():*
{
return invokeHandlers(arguments.callee.name,arguments);
};
result.name = name;
}
return result;
}
override flash_proxy function hasProperty(name:*) : Boolean
{
return this.handlers.hasOwnProperty(name);
}
private function invokeHandlers(name:String, args:Array) : *
{
var result:Array = null;
var handlersForName:Array = null;
var handler:Object = null;
if(this.handlers.hasOwnProperty(name))
{
result = [];
handlersForName = this.handlers[name];
for each(handler in handlersForName)
{
result.push(handler.handler.apply(null,args));
}
}
return result;
}
}
}
@@ -0,0 +1,25 @@
package org.osmf.net
{
[ExcludeClass]
public final class NetConnectionCodes
{
public static const CONNECT_CLOSED:String = "NetConnection.Connect.Closed";
public static const CONNECT_FAILED:String = "NetConnection.Connect.Failed";
public static const CONNECT_SUCCESS:String = "NetConnection.Connect.Success";
public static const CONNECT_REJECTED:String = "NetConnection.Connect.Rejected";
public static const CONNECT_INVALIDAPP:String = "NetConnection.Connect.InvalidApp";
public static const CONNECT_IDLE_TIME_OUT:String = "NetConnection.Connect.IdleTimeOut";
public function NetConnectionCodes()
{
super();
}
}
}
@@ -0,0 +1,291 @@
package org.osmf.net
{
import flash.net.NetConnection;
import flash.utils.Dictionary;
import org.osmf.events.NetConnectionFactoryEvent;
import org.osmf.media.URLResource;
import org.osmf.utils.URL;
public class NetConnectionFactory extends NetConnectionFactoryBase
{
private static const DEFAULT_TIMEOUT:Number = 10000;
private static const DEFAULT_PORTS:String = "1935,443,80";
private static const DEFAULT_PROTOCOLS_FOR_RTMP:String = "rtmp,rtmpt,rtmps";
private static const DEFAULT_PROTOCOLS_FOR_RTMPE:String = "rtmpe,rtmpte";
private static const DEFAULT_CONNECTION_ATTEMPT_INTERVAL:Number = 200;
private static const PROTOCOL_RTMP:String = "rtmp";
private static const PROTOCOL_RTMPS:String = "rtmps";
private static const PROTOCOL_RTMPT:String = "rtmpt";
private static const PROTOCOL_RTMPE:String = "rtmpe";
private static const PROTOCOL_RTMPTE:String = "rtmpte";
private static const PROTOCOL_HTTP:String = "http";
private static const PROTOCOL_HTTPS:String = "https";
private static const PROTOCOL_FILE:String = "file";
private static const PROTOCOL_EMPTY:String = "";
private static const MP3_EXTENSION:String = ".mp3";
private var shareNetConnections:Boolean;
private var negotiator:NetNegotiator;
private var connectionDictionary:Dictionary;
private var keyDictionary:Dictionary;
private var pendingDictionary:Dictionary;
private var _connectionAttemptInterval:Number = 200;
private var _timeout:Number = 10000;
public function NetConnectionFactory(shareNetConnections:Boolean = true)
{
super();
this.shareNetConnections = shareNetConnections;
}
public function get timeout() : Number
{
return this._timeout;
}
public function set timeout(value:Number) : void
{
this._timeout = value;
}
public function get connectionAttemptInterval() : Number
{
return this._connectionAttemptInterval;
}
public function set connectionAttemptInterval(value:Number) : void
{
this._connectionAttemptInterval = value;
}
override public function create(resource:URLResource) : void
{
var sharedConnection:SharedConnection;
var connectionsUnderway:Vector.<URLResource>;
var key:String = null;
var pendingConnections:Vector.<URLResource> = null;
var urlIncludesFMSApplicationInstance:Boolean = false;
var netConnectionURLs:Vector.<String> = null;
var netConnections:Vector.<NetConnection> = null;
var j:int = 0;
var negotiator:NetNegotiator = null;
var onConnected:Function = null;
var onConnectionFailed:Function = null;
key = this.createNetConnectionKey(resource);
if(this.connectionDictionary == null)
{
this.connectionDictionary = new Dictionary();
this.keyDictionary = new Dictionary();
this.pendingDictionary = new Dictionary();
}
sharedConnection = this.connectionDictionary[key] as SharedConnection;
connectionsUnderway = this.pendingDictionary[key] as Vector.<URLResource>;
if(sharedConnection != null && this.shareNetConnections)
{
++sharedConnection.count;
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_COMPLETE,false,false,sharedConnection.netConnection,resource));
}
else if(connectionsUnderway != null)
{
connectionsUnderway.push(resource);
}
else
{
onConnected = function(event:NetConnectionFactoryEvent):void
{
var pendingEvent:NetConnectionFactoryEvent = null;
var pendingResource:URLResource = null;
var alreadyShared:SharedConnection = null;
var obj:SharedConnection = null;
negotiator.removeEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,onConnected);
negotiator.removeEventListener(NetConnectionFactoryEvent.CREATION_ERROR,onConnectionFailed);
var pendingEvents:Vector.<NetConnectionFactoryEvent> = new Vector.<NetConnectionFactoryEvent>();
var pendingConnections:Vector.<URLResource> = pendingDictionary[key];
for(var i:Number = 0; i < pendingConnections.length; i++)
{
pendingResource = pendingConnections[i] as URLResource;
if(shareNetConnections)
{
alreadyShared = connectionDictionary[key] as SharedConnection;
if(alreadyShared != null)
{
++alreadyShared.count;
}
else
{
obj = new SharedConnection();
obj.count = 1;
obj.netConnection = event.netConnection;
connectionDictionary[key] = obj;
keyDictionary[obj.netConnection] = key;
}
}
pendingEvents.push(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_COMPLETE,false,false,event.netConnection,pendingResource));
}
delete pendingDictionary[key];
for each(pendingEvent in pendingEvents)
{
dispatchEvent(pendingEvent);
}
};
onConnectionFailed = function(event:NetConnectionFactoryEvent):void
{
var pendingResource:URLResource = null;
negotiator.removeEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,onConnected);
negotiator.removeEventListener(NetConnectionFactoryEvent.CREATION_ERROR,onConnectionFailed);
var pendingConnections:Vector.<URLResource> = pendingDictionary[key];
for each(pendingResource in pendingConnections)
{
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_ERROR,false,false,null,pendingResource,event.mediaError));
}
delete pendingDictionary[key];
};
pendingConnections = new Vector.<URLResource>();
pendingConnections.push(resource);
this.pendingDictionary[key] = pendingConnections;
urlIncludesFMSApplicationInstance = resource is StreamingURLResource ? StreamingURLResource(resource).urlIncludesFMSApplicationInstance : false;
netConnectionURLs = this.createNetConnectionURLs(resource.url,urlIncludesFMSApplicationInstance);
netConnections = new Vector.<NetConnection>();
for(j = 0; j < netConnectionURLs.length; j++)
{
netConnections.push(this.createNetConnection());
}
negotiator = new NetNegotiator(this._connectionAttemptInterval,this._timeout);
negotiator.addEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,onConnected);
negotiator.addEventListener(NetConnectionFactoryEvent.CREATION_ERROR,onConnectionFailed);
negotiator.createNetConnection(resource,netConnectionURLs,netConnections);
}
}
override public function closeNetConnection(netConnection:NetConnection) : void
{
var key:String = null;
var obj:SharedConnection = null;
if(this.shareNetConnections)
{
key = this.keyDictionary[netConnection] as String;
if(key != null)
{
obj = this.connectionDictionary[key] as SharedConnection;
--obj.count;
if(obj.count == 0)
{
netConnection.close();
delete this.connectionDictionary[key];
delete this.keyDictionary[netConnection];
}
}
}
else
{
super.closeNetConnection(netConnection);
}
}
protected function createNetConnectionKey(resource:URLResource) : String
{
var fmsURL:FMSURL = new FMSURL(resource.url);
return fmsURL.protocol + fmsURL.host + fmsURL.port + fmsURL.appName + fmsURL.instanceName;
}
protected function createNetConnection() : NetConnection
{
return new NetConnection();
}
protected function createNetConnectionURLs(url:String, urlIncludesFMSApplicationInstance:Boolean = false) : Vector.<String>
{
var portProtocol:PortProtocol = null;
var urls:Vector.<String> = new Vector.<String>();
var portProtocols:Vector.<PortProtocol> = this.buildPortProtocolSequence(url);
for each(portProtocol in portProtocols)
{
urls.push(this.buildConnectionAddress(url,urlIncludesFMSApplicationInstance,portProtocol));
}
return urls;
}
private function buildPortProtocolSequence(url:String) : Vector.<PortProtocol>
{
var j:int = 0;
var attempt:PortProtocol = null;
var portProtocols:Vector.<PortProtocol> = new Vector.<PortProtocol>();
var theURL:URL = new URL(url);
var allowedPorts:String = theURL.port == "" ? DEFAULT_PORTS : theURL.port;
var allowedProtocols:String = "";
switch(theURL.protocol)
{
case PROTOCOL_RTMP:
allowedProtocols = DEFAULT_PROTOCOLS_FOR_RTMP;
break;
case PROTOCOL_RTMPE:
allowedProtocols = DEFAULT_PROTOCOLS_FOR_RTMPE;
break;
case PROTOCOL_RTMPS:
case PROTOCOL_RTMPT:
case PROTOCOL_RTMPTE:
allowedProtocols = theURL.protocol;
}
var portArray:Array = allowedPorts.split(",");
var protocolArray:Array = allowedProtocols.split(",");
for(var i:int = 0; i < protocolArray.length; i++)
{
for(j = 0; j < portArray.length; j++)
{
attempt = new PortProtocol();
attempt.protocol = protocolArray[i];
attempt.port = portArray[j];
portProtocols.push(attempt);
}
}
return portProtocols;
}
private function buildConnectionAddress(url:String, urlIncludesFMSApplicationInstance:Boolean, portProtocol:PortProtocol) : String
{
var fmsURL:FMSURL = new FMSURL(url,urlIncludesFMSApplicationInstance);
var addr:String = portProtocol.protocol + "://" + fmsURL.host + ":" + portProtocol.port + "/" + fmsURL.appName + (fmsURL.useInstance ? "/" + fmsURL.instanceName : "");
if(fmsURL.query != null && fmsURL.query != "")
{
addr += "?" + fmsURL.query;
}
return addr;
}
}
}
import flash.net.NetConnection;
class SharedConnection
{
public var count:Number;
public var netConnection:NetConnection;
public function SharedConnection()
{
super();
}
}
@@ -0,0 +1,30 @@
package org.osmf.net
{
import flash.errors.IllegalOperationError;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import org.osmf.media.URLResource;
import org.osmf.utils.OSMFStrings;
[Event(name="creationError",type="org.osmf.events.NetConnectionFactoryEvent")]
[Event(name="creationComplete",type="org.osmf.events.NetConnectionFactoryEvent")]
public class NetConnectionFactoryBase extends EventDispatcher
{
public function NetConnectionFactoryBase()
{
super();
}
public function create(resource:URLResource) : void
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.FUNCTION_MUST_BE_OVERRIDDEN));
}
public function closeNetConnection(netConnection:NetConnection) : void
{
netConnection.close();
}
}
}
@@ -0,0 +1,526 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import flash.net.NetStreamPlayTransitions;
import flash.utils.Dictionary;
import flash.utils.Timer;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.events.MediaErrorEvent;
import org.osmf.events.NetConnectionFactoryEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaType;
import org.osmf.media.MediaTypeUtil;
import org.osmf.media.URLResource;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
import org.osmf.utils.OSMFStrings;
import org.osmf.utils.URL;
public class NetLoader extends LoaderBase
{
private static const PROTOCOL_RTMP:String = "rtmp";
private static const PROTOCOL_RTMPS:String = "rtmps";
private static const PROTOCOL_RTMPT:String = "rtmpt";
private static const PROTOCOL_RTMPE:String = "rtmpe";
private static const PROTOCOL_RTMPTE:String = "rtmpte";
private static const PROTOCOL_RTMFP:String = "rtmfp";
private static const PROTOCOL_HTTP:String = "http";
private static const PROTOCOL_HTTPS:String = "https";
private static const PROTOCOL_FILE:String = "file";
private static const PROTOCOL_EMPTY:String = "";
private static const MEDIA_TYPES_SUPPORTED:Vector.<String> = Vector.<String>([MediaType.VIDEO]);
private static const MIME_TYPES_SUPPORTED:Vector.<String> = Vector.<String>(["video/x-flv","video/x-f4v","video/mp4","video/mp4v-es","video/x-m4v","video/3gpp","video/3gpp2","video/quicktime"]);
private static const STREAM_RECONNECT_TIMEOUT:Number = 120000;
private static const STREAM_RECONNECT_TIMER_INTERVAL:int = 1000;
private var netConnectionFactory:NetConnectionFactoryBase;
private var pendingLoads:Dictionary = new Dictionary();
private var oldConnectionURLs:Dictionary = new Dictionary();
private var _reconnectStreams:Boolean = true;
private var _reconnectTimeout:Number;
public function NetLoader(factory:NetConnectionFactoryBase = null)
{
super();
this._reconnectTimeout = STREAM_RECONNECT_TIMEOUT;
this.netConnectionFactory = factory || new NetConnectionFactory();
this.netConnectionFactory.addEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,this.onCreationComplete);
this.netConnectionFactory.addEventListener(NetConnectionFactoryEvent.CREATION_ERROR,this.onCreationError);
}
override public function canHandleResource(resource:MediaResourceBase) : Boolean
{
var rt:int = MediaTypeUtil.checkMetadataMatchWithResource(resource,MEDIA_TYPES_SUPPORTED,MIME_TYPES_SUPPORTED);
if(rt != MediaTypeUtil.METADATA_MATCH_UNKNOWN)
{
return rt == MediaTypeUtil.METADATA_MATCH_FOUND;
}
var res:URLResource = resource as URLResource;
var extensionPattern:RegExp = /.flv$|.f4v$|.mov$|.mp4$|.mp4v$|.m4v$|.3gp$|.3gpp2$|.3g2$/i;
var url:URL = res != null ? new URL(res.url) : null;
if(url == null || url.rawUrl == null || url.rawUrl.length <= 0)
{
return false;
}
if(url.protocol == "")
{
return extensionPattern.test(url.path);
}
if(NetStreamUtils.isRTMPStream(url.rawUrl))
{
return true;
}
if(url.protocol.search(/file$|http$|https$/i) != -1)
{
return url.path == null || url.path.length <= 0 || url.path.indexOf(".") == -1 || extensionPattern.test(url.path);
}
return false;
}
protected function createNetStream(connection:NetConnection, resource:URLResource) : NetStream
{
var ns:NetStream = new NetStream(connection);
var streamingResource:StreamingURLResource = resource as StreamingURLResource;
if(streamingResource != null && streamingResource.streamType == StreamType.LIVE && ns.bufferTime == 0)
{
ns.bufferTime = 0.1;
}
return ns;
}
protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource) : NetStreamSwitchManagerBase
{
return null;
}
protected function processFinishLoading(loadTrait:NetStreamLoadTrait) : void
{
updateLoadTrait(loadTrait,LoadState.READY);
}
override protected function executeLoad(loadTrait:LoadTrait) : void
{
updateLoadTrait(loadTrait,LoadState.LOADING);
var url:URL = new URL((loadTrait.resource as URLResource).url);
switch(url.protocol)
{
case PROTOCOL_RTMP:
case PROTOCOL_RTMPS:
case PROTOCOL_RTMPT:
case PROTOCOL_RTMPE:
case PROTOCOL_RTMPTE:
case PROTOCOL_RTMFP:
this.startLoadingRTMP(loadTrait);
break;
case PROTOCOL_HTTP:
case PROTOCOL_HTTPS:
case PROTOCOL_FILE:
case PROTOCOL_EMPTY:
this.startLoadingHTTP(loadTrait);
break;
default:
updateLoadTrait(loadTrait,LoadState.LOAD_ERROR);
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR,false,false,new MediaError(MediaErrorCodes.URL_SCHEME_INVALID)));
}
}
override protected function executeUnload(loadTrait:LoadTrait) : void
{
var netLoadTrait:NetStreamLoadTrait = loadTrait as NetStreamLoadTrait;
updateLoadTrait(loadTrait,LoadState.UNLOADING);
netLoadTrait.netStream.close();
if(netLoadTrait.netConnectionFactory != null)
{
netLoadTrait.netConnectionFactory.closeNetConnection(netLoadTrait.connection);
}
else
{
netLoadTrait.connection.close();
}
delete this.oldConnectionURLs[loadTrait.resource];
updateLoadTrait(loadTrait,LoadState.UNINITIALIZED);
}
private function finishLoading(connection:NetConnection, loadTrait:LoadTrait, factory:NetConnectionFactoryBase = null) : void
{
var netStream:NetStream = null;
var netLoadTrait:NetStreamLoadTrait = loadTrait as NetStreamLoadTrait;
if(netLoadTrait != null)
{
netLoadTrait.connection = connection;
netStream = this.createNetStream(connection,netLoadTrait.resource as URLResource);
netStream.client = new NetClient();
netLoadTrait.netStream = netStream;
netLoadTrait.switchManager = this.createNetStreamSwitchManager(connection,netStream,netLoadTrait.resource as DynamicStreamingResource);
netLoadTrait.netConnectionFactory = factory;
if(this._reconnectStreams && netLoadTrait.resource is URLResource && this.supportsStreamReconnect(netLoadTrait.resource as URLResource))
{
this.setupStreamReconnect(netLoadTrait);
}
this.processFinishLoading(loadTrait as NetStreamLoadTrait);
}
}
private function supportsStreamReconnect(resource:URLResource) : Boolean
{
var fmsVersion:String = null;
var versionParts:Array = null;
var majorVersion:int = 0;
var minorVersion:int = 0;
var subMinorVersion:int = 0;
var result:Boolean = true;
if(NetStreamUtils.isRTMPStream(resource.url))
{
fmsVersion = resource.getMetadataValue(MetadataNamespaces.FMS_SERVER_VERSION_METADATA) as String;
if(fmsVersion != null && fmsVersion.length > 0)
{
versionParts = fmsVersion.split(",");
if(versionParts.length >= 3)
{
majorVersion = int(versionParts[0]);
minorVersion = int(versionParts[1]);
subMinorVersion = int(versionParts[2]);
if(majorVersion < 3 || majorVersion == 3 && minorVersion < 5 || majorVersion == 3 && minorVersion == 5 && subMinorVersion < 3)
{
result = false;
}
}
}
}
else
{
result = false;
}
return result;
}
private function startLoadingRTMP(loadTrait:LoadTrait) : void
{
this.addPendingLoad(loadTrait);
this.netConnectionFactory.create(loadTrait.resource as URLResource);
}
private function onCreationComplete(event:NetConnectionFactoryEvent) : void
{
this.processCreationComplete(event.netConnection,this.findAndRemovePendingLoad(event.resource),event.currentTarget as NetConnectionFactoryBase);
}
protected function processCreationComplete(connection:NetConnection, loadTrait:LoadTrait, factory:NetConnectionFactoryBase = null) : void
{
this.finishLoading(connection,loadTrait,factory);
}
private function onCreationError(event:NetConnectionFactoryEvent) : void
{
var loadTrait:LoadTrait = this.findAndRemovePendingLoad(event.resource);
if(loadTrait != null)
{
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR,false,false,event.mediaError));
updateLoadTrait(loadTrait,LoadState.LOAD_ERROR);
}
}
private function startLoadingHTTP(loadTrait:LoadTrait) : void
{
var connection:NetConnection = new NetConnection();
connection.client = new NetClient();
connection.connect(null);
this.finishLoading(connection,loadTrait);
}
private function addPendingLoad(loadTrait:LoadTrait) : void
{
if(this.pendingLoads[loadTrait.resource] == null)
{
this.pendingLoads[loadTrait.resource] = [loadTrait];
}
else
{
this.pendingLoads[loadTrait.resource].push(loadTrait);
}
}
private function findAndRemovePendingLoad(resource:URLResource) : LoadTrait
{
var i:int = 0;
var loadTrait:LoadTrait = null;
var pendingLoadsArray:Array = this.pendingLoads[resource];
if(pendingLoadsArray != null)
{
if(pendingLoadsArray.length == 1)
{
loadTrait = pendingLoadsArray[0] as LoadTrait;
delete this.pendingLoads[resource];
}
else
{
for(i = 0; i < pendingLoadsArray.length; i++)
{
loadTrait = pendingLoadsArray[i];
if(loadTrait.resource == resource)
{
pendingLoadsArray.splice(i,1);
break;
}
}
}
}
return loadTrait;
}
public function get reconnectTimeout() : Number
{
return this._reconnectTimeout;
}
public function set reconnectTimeout(value:Number) : void
{
if(value < 0)
{
throw new ArgumentError(OSMFStrings.getString(OSMFStrings.INVALID_PARAM));
}
this._reconnectTimeout = value;
}
protected function setReconnectStreams(value:Boolean) : void
{
this._reconnectStreams = value;
}
public function get reconnectStreams() : Boolean
{
return this._reconnectStreams;
}
protected function createReconnectNetConnection() : NetConnection
{
return new NetConnection();
}
protected function reconnect(netConnection:NetConnection, resource:URLResource) : void
{
var connectionURL:String = this.oldConnectionURLs[resource] as String;
if(connectionURL != null && connectionURL.length > 0 && netConnection != null)
{
netConnection.connect(connectionURL);
}
}
protected function reconnectStream(loadTrait:NetStreamLoadTrait) : void
{
var nsPlayOptions:NetStreamPlayOptions = new NetStreamPlayOptions();
loadTrait.netStream.attach(loadTrait.connection);
nsPlayOptions.transition = NetStreamPlayTransitions.RESUME;
var resource:URLResource = loadTrait.resource as URLResource;
var urlIncludesFMSApplicationInstance:Boolean = resource as StreamingURLResource != null ? (resource as StreamingURLResource).urlIncludesFMSApplicationInstance : false;
var streamName:String = NetStreamUtils.getStreamNameFromURL(resource.url,urlIncludesFMSApplicationInstance);
nsPlayOptions.streamName = streamName;
loadTrait.netStream.play2(nsPlayOptions);
}
private function setupStreamReconnect(loadTrait:NetStreamLoadTrait) : void
{
var netConnection:NetConnection = null;
var reconnectTimer:Timer = null;
var timeoutTimer:Timer = null;
var streamIsPaused:Boolean = false;
var bufferIsEmpty:Boolean = false;
var reconnectHasTimedOut:Boolean = false;
var fmsIdleTimeoutReached:Boolean = false;
var onNetStatus:Function = null;
var onTimeoutTimer:Function = null;
var onReconnectTimer:Function = null;
var setupReconnectTimer:Function = function(add:Boolean = true):void
{
if(add)
{
reconnectTimer.addEventListener(TimerEvent.TIMER_COMPLETE,onReconnectTimer);
}
else
{
reconnectTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,onReconnectTimer);
reconnectTimer = null;
}
};
var setupTimeoutTimer:Function = function(add:Boolean = true):void
{
if(add)
{
if(_reconnectTimeout > 0)
{
timeoutTimer = new Timer(_reconnectTimeout,1);
timeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE,onTimeoutTimer);
}
}
else if(timeoutTimer != null)
{
timeoutTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,onTimeoutTimer);
timeoutTimer = null;
}
};
var setupNetConnectionListeners:Function = function(add:Boolean = true):void
{
if(add)
{
netConnection.addEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
}
else
{
netConnection.removeEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
}
};
var setupNetStreamListeners:Function = function(add:Boolean = true):void
{
if(loadTrait.netStream != null)
{
if(add)
{
loadTrait.netStream.addEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
}
else
{
loadTrait.netStream.removeEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
}
}
};
onNetStatus = function(event:NetStatusEvent):void
{
var oldConnection:NetConnection = null;
switch(event.info.code)
{
case NetConnectionCodes.CONNECT_SUCCESS:
oldConnection = loadTrait.connection;
loadTrait.connection = netConnection;
oldConnectionURLs[loadTrait.resource] = netConnection.uri;
if(timeoutTimer != null)
{
timeoutTimer.stop();
}
reconnectStream(loadTrait);
if(loadTrait.netConnectionFactory != null)
{
loadTrait.netConnectionFactory.closeNetConnection(oldConnection);
}
else
{
oldConnection.close();
}
break;
case NetConnectionCodes.CONNECT_IDLE_TIME_OUT:
fmsIdleTimeoutReached = true;
break;
case NetConnectionCodes.CONNECT_CLOSED:
case NetConnectionCodes.CONNECT_FAILED:
if(loadTrait.loadState == LoadState.READY && !reconnectHasTimedOut && !fmsIdleTimeoutReached)
{
reconnectTimer.start();
if(bufferIsEmpty || loadTrait.netStream.bufferLength == 0 || streamIsPaused)
{
if(timeoutTimer != null)
{
timeoutTimer.start();
}
else
{
reconnectHasTimedOut = true;
setupReconnectTimer(false);
setupNetConnectionListeners(false);
setupNetStreamListeners(false);
setupTimeoutTimer(false);
}
}
}
else
{
setupReconnectTimer(false);
setupNetConnectionListeners(false);
setupNetStreamListeners(false);
setupTimeoutTimer(false);
}
break;
case NetStreamCodes.NETSTREAM_PAUSE_NOTIFY:
streamIsPaused = true;
break;
case NetStreamCodes.NETSTREAM_UNPAUSE_NOTIFY:
streamIsPaused = false;
break;
case NetStreamCodes.NETSTREAM_BUFFER_EMPTY:
if(!netConnection.connected)
{
if(timeoutTimer != null)
{
timeoutTimer.start();
}
else
{
reconnectHasTimedOut = true;
}
}
else
{
bufferIsEmpty = true;
}
break;
case NetStreamCodes.NETSTREAM_BUFFER_FULL:
bufferIsEmpty = false;
}
};
onTimeoutTimer = function(event:TimerEvent):void
{
reconnectHasTimedOut = true;
};
onReconnectTimer = function(event:TimerEvent):void
{
if(reconnectHasTimedOut)
{
return;
}
if(netConnection === loadTrait.connection)
{
setupNetConnectionListeners(false);
netConnection = createReconnectNetConnection();
netConnection.client = new NetClient();
setupNetConnectionListeners();
}
reconnect(netConnection,loadTrait.resource as URLResource);
};
netConnection = loadTrait.connection;
reconnectTimer = new Timer(STREAM_RECONNECT_TIMER_INTERVAL,1);
this.oldConnectionURLs[loadTrait.resource] = netConnection.uri;
streamIsPaused = false;
bufferIsEmpty = false;
reconnectHasTimedOut = false;
fmsIdleTimeoutReached = false;
setupNetConnectionListeners();
setupNetStreamListeners();
setupReconnectTimer();
setupTimeoutTimer();
}
}
}
@@ -0,0 +1,228 @@
package org.osmf.net
{
import flash.errors.IOError;
import flash.events.AsyncErrorEvent;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.utils.Timer;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.events.NetConnectionFactoryEvent;
import org.osmf.media.URLResource;
import org.osmf.metadata.MetadataNamespaces;
[Event(name="creationError",type="org.osmf.events.NetConnectionFactoryEvent")]
[Event(name="creationComplete",type="org.osmf.events.NetConnectionFactoryEvent")]
internal class NetNegotiator extends EventDispatcher
{
private var resource:URLResource;
private var netConnectionURLs:Vector.<String>;
private var netConnections:Vector.<NetConnection>;
private var netConnectionArguments:Vector.<Object>;
private var failedConnectionCount:int;
private var timeOutTimer:Timer;
private var connectionTimer:Timer;
private var attemptIndex:int;
private var mediaError:MediaError;
private var connectionAttemptInterval:Number;
private var _timeout:Number;
public function NetNegotiator(connectionAttemptInterval:Number, timeout:Number = 10000)
{
super();
this.connectionAttemptInterval = connectionAttemptInterval;
this._timeout = timeout;
}
public function get timeout() : Number
{
return this._timeout;
}
public function set timeout(value:Number) : void
{
this._timeout = value;
}
public function createNetConnection(resource:URLResource, netConnectionURLs:Vector.<String>, netConnections:Vector.<NetConnection>) : void
{
this.resource = resource;
this.netConnectionURLs = netConnectionURLs;
this.netConnections = netConnections;
var streamingResource:StreamingURLResource = resource as StreamingURLResource;
if(streamingResource != null && streamingResource.connectionArguments != null && streamingResource.connectionArguments.length > 0)
{
this.netConnectionArguments = streamingResource.connectionArguments;
}
this.initializeConnectionAttempts();
this.tryToConnect(null);
}
private function initializeConnectionAttempts() : void
{
this.timeOutTimer = new Timer(this._timeout,1);
this.timeOutTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.masterTimeout);
this.timeOutTimer.start();
this.connectionTimer = new Timer(this.connectionAttemptInterval);
this.connectionTimer.addEventListener(TimerEvent.TIMER,this.tryToConnect);
this.connectionTimer.start();
this.failedConnectionCount = 0;
this.attemptIndex = 0;
}
private function tryToConnect(evt:TimerEvent) : void
{
var rs:MulticastResource = null;
var host:String = null;
var args:Array = null;
var arg:Object = null;
this.netConnections[this.attemptIndex].addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus,false,0,true);
this.netConnections[this.attemptIndex].addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.onNetSecurityError,false,0,true);
this.netConnections[this.attemptIndex].addEventListener(AsyncErrorEvent.ASYNC_ERROR,this.onAsyncError,false,0,true);
this.netConnections[this.attemptIndex].client = new NetClient();
try
{
rs = this.resource as MulticastResource;
if(rs != null && rs.groupspec != null && rs.groupspec.length > 0)
{
NetConnection(this.netConnections[this.attemptIndex]).connect(rs.url);
}
else
{
host = this.netConnectionURLs[this.attemptIndex];
args = [host];
if(this.netConnectionArguments != null)
{
for each(arg in this.netConnectionArguments)
{
args.push(arg);
}
}
NetConnection(this.netConnections[this.attemptIndex]).connect.apply(this.netConnections[this.attemptIndex],args);
}
++this.attemptIndex;
if(this.attemptIndex >= this.netConnectionURLs.length)
{
this.connectionTimer.stop();
}
}
catch(ioError:IOError)
{
handleFailedConnectionSession(new MediaError(MediaErrorCodes.IO_ERROR,ioError.message),netConnectionURLs[attemptIndex]);
}
catch(argumentError:ArgumentError)
{
handleFailedConnectionSession(new MediaError(MediaErrorCodes.ARGUMENT_ERROR,argumentError.message),netConnectionURLs[attemptIndex]);
}
catch(securityError:SecurityError)
{
handleFailedConnectionSession(new MediaError(MediaErrorCodes.SECURITY_ERROR,securityError.message),netConnectionURLs[attemptIndex]);
}
}
private function onNetStatus(event:NetStatusEvent) : void
{
var index:int = 0;
var tempTimer:Timer = null;
var onTempTimer:Function = null;
switch(event.info.code)
{
case NetConnectionCodes.CONNECT_INVALIDAPP:
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.NETCONNECTION_APPLICATION_INVALID,event.info.description),NetConnection(event.target).uri);
break;
case NetConnectionCodes.CONNECT_REJECTED:
if(event.info.hasOwnProperty("ex") && event.info.ex.code == 302)
{
onTempTimer = function(event:TimerEvent):void
{
tempTimer.removeEventListener(TimerEvent.TIMER,onTempTimer);
tempTimer.stop();
tryToConnect(null);
};
index = this.netConnections.indexOf(event.target as NetConnection);
this.netConnectionURLs[index] = event.info.ex.redirect;
this.attemptIndex = index;
tempTimer = new Timer(100,1);
tempTimer.addEventListener(TimerEvent.TIMER,onTempTimer);
tempTimer.start();
}
else
{
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.NETCONNECTION_REJECTED,event.info.description),NetConnection(event.target).uri);
}
break;
case NetConnectionCodes.CONNECT_FAILED:
++this.failedConnectionCount;
if(this.failedConnectionCount >= this.netConnectionURLs.length)
{
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.NETCONNECTION_FAILED),NetConnection(event.target).uri);
}
break;
case NetConnectionCodes.CONNECT_SUCCESS:
if(event.info.hasOwnProperty("data") && Boolean(event.info.data.hasOwnProperty("version")))
{
this.resource.addMetadataValue(MetadataNamespaces.FMS_SERVER_VERSION_METADATA,event.info.data.version);
}
this.shutDownUnsuccessfulConnections();
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_COMPLETE,false,false,event.currentTarget as NetConnection,this.resource));
break;
case "NetStream.Publish.Start":
}
}
private function shutDownUnsuccessfulConnections() : void
{
var nc:NetConnection = null;
this.timeOutTimer.stop();
this.connectionTimer.stop();
for(var i:int = 0; i < this.netConnections.length; i++)
{
nc = this.netConnections[i];
if(!nc.connected)
{
nc.removeEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
nc.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,this.onNetSecurityError);
nc.removeEventListener(AsyncErrorEvent.ASYNC_ERROR,this.onAsyncError);
nc.close();
delete this.netConnections[i];
}
}
}
private function handleFailedConnectionSession(mediaError:MediaError, url:String) : void
{
this.shutDownUnsuccessfulConnections();
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_ERROR,false,false,null,this.resource,mediaError));
}
private function onNetSecurityError(event:SecurityErrorEvent) : void
{
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.SECURITY_ERROR,event.text),NetConnection(event.target).uri);
}
private function onAsyncError(event:AsyncErrorEvent) : void
{
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.ASYNC_ERROR,event.text),NetConnection(event.target).uri);
}
private function masterTimeout(event:TimerEvent) : void
{
this.handleFailedConnectionSession(new MediaError(MediaErrorCodes.NETCONNECTION_TIMEOUT,"" + this._timeout),"");
}
}
}
@@ -0,0 +1,41 @@
package org.osmf.net
{
import flash.media.SoundTransform;
import flash.net.NetStream;
import org.osmf.traits.AudioTrait;
[ExcludeClass]
public class NetStreamAudioTrait extends AudioTrait
{
private var netStream:NetStream;
public function NetStreamAudioTrait(netStream:NetStream)
{
super();
this.netStream = netStream;
}
override protected function volumeChangeStart(newVolume:Number) : void
{
var soundTransform:SoundTransform = this.netStream.soundTransform;
soundTransform.volume = muted ? 0 : newVolume;
this.netStream.soundTransform = soundTransform;
}
override protected function mutedChangeStart(newMuted:Boolean) : void
{
var soundTransform:SoundTransform = this.netStream.soundTransform;
soundTransform.volume = newMuted ? 0 : volume;
this.netStream.soundTransform = soundTransform;
}
override protected function panChangeStart(newPan:Number) : void
{
var soundTransform:SoundTransform = this.netStream.soundTransform;
soundTransform.pan = newPan;
this.netStream.soundTransform = soundTransform;
}
}
}
@@ -0,0 +1,63 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetStream;
import flash.utils.Timer;
import org.osmf.traits.BufferTrait;
[ExcludeClass]
public class NetStreamBufferTrait extends BufferTrait
{
private var netStream:NetStream;
private var changeBufferLengthTimer:Timer;
public function NetStreamBufferTrait(netStream:NetStream)
{
super();
this.netStream = netStream;
bufferTime = netStream.bufferTime;
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus,false,0,true);
this.changeBufferLengthTimer = new Timer(250);
this.changeBufferLengthTimer.addEventListener(TimerEvent.TIMER,this.onChangeBufferLength,false,0,true);
this.changeBufferLengthTimer.start();
}
override public function get bufferLength() : Number
{
return this.netStream.bufferLength;
}
override protected function bufferTimeChangeStart(newTime:Number) : void
{
this.netStream.bufferTime = newTime;
}
private function onChangeBufferLength(t:TimerEvent) : void
{
setBufferLength(this.netStream.bufferLength);
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_START:
case NetStreamCodes.NETSTREAM_BUFFER_EMPTY:
bufferTime = this.netStream.bufferTime;
setBuffering(true);
if(this.netStream.bufferTime == 0)
{
setBuffering(false);
}
break;
case NetStreamCodes.NETSTREAM_BUFFER_FLUSH:
case NetStreamCodes.NETSTREAM_BUFFER_FULL:
setBuffering(false);
}
}
}
}
@@ -0,0 +1,65 @@
package org.osmf.net
{
[ExcludeClass]
public final class NetStreamCodes
{
public static const NETSTREAM_BUFFER_EMPTY:String = "NetStream.Buffer.Empty";
public static const NETSTREAM_BUFFER_FULL:String = "NetStream.Buffer.Full";
public static const NETSTREAM_BUFFER_FLUSH:String = "NetStream.Buffer.Flush";
public static const NETSTREAM_FAILED:String = "NetStream.Failed";
public static const NETSTREAM_PLAY_START:String = "NetStream.Play.Start";
public static const NETSTREAM_PLAY_STOP:String = "NetStream.Play.Stop";
public static const NETSTREAM_PLAY_FAILED:String = "NetStream.Play.Failed";
public static const NETSTREAM_PLAY_STREAMNOTFOUND:String = "NetStream.Play.StreamNotFound";
public static const NETSTREAM_PLAY_RESET:String = "NetStream.Play.Reset";
public static const NETSTREAM_PLAY_INSUFFICIENTBW:String = "NetStream.Play.InsufficientBW";
public static const NETSTREAM_PLAY_FILESTRUCTUREINVALID:String = "NetStream.Play.FileStructureInvalid";
public static const NETSTREAM_PLAY_NOSUPPORTEDTRACKFOUND:String = "NetStream.Play.NoSupportedTrackFound";
public static const NETSTREAM_PLAY_TRANSITION:String = "NetStream.Play.Transition";
public static const NETSTREAM_PAUSE_NOTIFY:String = "NetStream.Pause.Notify";
public static const NETSTREAM_PLAY_PUBLISH_NOTIFY:String = "NetStream.Play.PublishNotify";
public static const NETSTREAM_PLAY_UNPUBLISH_NOTIFY:String = "NetStream.Play.UnpublishNotify";
public static const NETSTREAM_UNPAUSE_NOTIFY:String = "NetStream.Unpause.Notify";
public static const NETSTREAM_SEEK_FAILED:String = "NetStream.Seek.Failed";
public static const NETSTREAM_SEEK_INVALIDTIME:String = "NetStream.Seek.InvalidTime";
public static const NETSTREAM_SEEK_NOTIFY:String = "NetStream.Seek.Notify";
public static const NETSTREAM_PLAY_COMPLETE:String = "NetStream.Play.Complete";
public static const NETSTREAM_PLAY_TRANSITION_COMPLETE:String = "NetStream.Play.TransitionComplete";
public static const ON_META_DATA:String = "onMetaData";
public static const ON_CUE_POINT:String = "onCuePoint";
public static const ON_PLAY_STATUS:String = "onPlayStatus";
public static const NETSTREAM_DRM_UPDATE:String = "DRM.UpdateNeeded";
public function NetStreamCodes()
{
super();
}
}
}
@@ -0,0 +1,63 @@
package org.osmf.net
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.media.Video;
import flash.net.NetStream;
import org.osmf.traits.DisplayObjectTrait;
[ExcludeClass]
public class NetStreamDisplayObjectTrait extends DisplayObjectTrait
{
private var netStream:NetStream;
public function NetStreamDisplayObjectTrait(netStream:NetStream, view:DisplayObject, mediaWidth:Number = 0, mediaHeight:Number = 0)
{
super(view,mediaWidth,mediaHeight);
this.netStream = netStream;
NetClient(netStream.client).addHandler(NetStreamCodes.ON_META_DATA,this.onMetaData);
if(view is Video)
{
view.addEventListener(Event.ADDED_TO_STAGE,this.onStage);
}
}
private function onStage(event:Event) : void
{
displayObject.removeEventListener(Event.ADDED_TO_STAGE,this.onStage);
displayObject.addEventListener(Event.ENTER_FRAME,this.onFrame);
}
private function onFrame(event:Event) : void
{
if(Video(displayObject).videoWidth != 0 && Video(displayObject).videoHeight != 0)
{
if(Video(displayObject).videoWidth != mediaWidth && Video(displayObject).videoHeight != mediaHeight)
{
this.newMediaSize(Video(displayObject).videoWidth,Video(displayObject).videoHeight);
}
displayObject.removeEventListener(Event.ENTER_FRAME,this.onFrame);
}
}
private function onMetaData(info:Object) : void
{
if(!isNaN(info.width) && !isNaN(info.height) && (info.width != mediaWidth || info.height != mediaHeight))
{
this.newMediaSize(info.width,info.height);
}
}
private function newMediaSize(width:Number, height:Number) : void
{
if(displayObject.width == 0 && displayObject.height == 0)
{
displayObject.width = width;
displayObject.height = height;
}
setMediaSize(width,height);
}
}
}
@@ -0,0 +1,98 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.net.NetStream;
import org.osmf.traits.DynamicStreamTrait;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
public class NetStreamDynamicStreamTrait extends DynamicStreamTrait
{
private var netStream:NetStream;
private var switchManager:NetStreamSwitchManagerBase;
private var inSetSwitching:Boolean;
private var dsResource:DynamicStreamingResource;
private var indexToSwitchTo:int;
public function NetStreamDynamicStreamTrait(netStream:NetStream, switchManager:NetStreamSwitchManagerBase, dsResource:DynamicStreamingResource)
{
super(switchManager.autoSwitch,switchManager.currentIndex,dsResource.streamItems.length);
this.netStream = netStream;
this.switchManager = switchManager;
this.dsResource = dsResource;
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
NetClient(netStream.client).addHandler(NetStreamCodes.ON_PLAY_STATUS,this.onPlayStatus);
}
override public function dispose() : void
{
this.netStream = null;
this.switchManager = null;
}
override public function getBitrateForIndex(index:int) : Number
{
if(index > numDynamicStreams - 1 || index < 0)
{
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
return this.dsResource.streamItems[index].bitrate;
}
override protected function switchingChangeStart(newSwitching:Boolean, index:int) : void
{
if(newSwitching && !this.inSetSwitching)
{
this.indexToSwitchTo = index;
}
}
override protected function switchingChangeEnd(index:int) : void
{
super.switchingChangeEnd(index);
if(switching && !this.inSetSwitching)
{
this.switchManager.switchTo(this.indexToSwitchTo);
}
}
override protected function autoSwitchChangeStart(value:Boolean) : void
{
this.switchManager.autoSwitch = value;
}
override protected function maxAllowedIndexChangeStart(value:int) : void
{
this.switchManager.maxAllowedIndex = value;
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_TRANSITION:
this.inSetSwitching = true;
setSwitching(true,this.dsResource.indexFromName(event.info.details));
this.inSetSwitching = false;
break;
case NetStreamCodes.NETSTREAM_PLAY_FAILED:
setSwitching(false,currentIndex);
}
}
private function onPlayStatus(event:Object) : void
{
switch(event.code)
{
case NetStreamCodes.NETSTREAM_PLAY_TRANSITION_COMPLETE:
setSwitching(false,this.switchManager.currentIndex);
}
}
}
}
@@ -0,0 +1,142 @@
package org.osmf.net
{
import flash.errors.IllegalOperationError;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetGroup;
import flash.net.NetStream;
import flash.utils.Dictionary;
import org.osmf.events.LoadEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
import org.osmf.traits.MediaTraitBase;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
public class NetStreamLoadTrait extends LoadTrait
{
private var _connection:NetConnection;
private var _switchManager:NetStreamSwitchManagerBase;
private var traits:Dictionary = new Dictionary();
private var _netConnectionFactory:NetConnectionFactoryBase;
private var isStreamingResource:Boolean;
private var _netStream:NetStream;
private var _netGroup:NetGroup;
public function NetStreamLoadTrait(loader:LoaderBase, resource:MediaResourceBase)
{
super(loader,resource);
this.isStreamingResource = NetStreamUtils.isStreamingResource(resource);
}
public function get connection() : NetConnection
{
return this._connection;
}
public function set connection(value:NetConnection) : void
{
this._connection = value;
}
public function get netStream() : NetStream
{
return this._netStream;
}
public function set netStream(value:NetStream) : void
{
this._netStream = value;
}
public function get switchManager() : NetStreamSwitchManagerBase
{
return this._switchManager;
}
public function set switchManager(value:NetStreamSwitchManagerBase) : void
{
this._switchManager = value;
}
public function setTrait(trait:MediaTraitBase) : void
{
if(trait == null)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.NULL_PARAM));
}
this.traits[trait.traitType] = trait;
}
public function getTrait(traitType:String) : MediaTraitBase
{
return this.traits[traitType];
}
public function get netConnectionFactory() : NetConnectionFactoryBase
{
return this._netConnectionFactory;
}
public function set netConnectionFactory(value:NetConnectionFactoryBase) : void
{
this._netConnectionFactory = value;
}
override protected function loadStateChangeStart(newState:String) : void
{
if(newState == LoadState.READY)
{
if(!this.isStreamingResource && (this.netStream.bytesTotal <= 0 || this.netStream.bytesTotal == uint.MAX_VALUE))
{
this.netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
}
}
else if(newState == LoadState.UNINITIALIZED)
{
this.netStream = null;
dispatchEvent(new LoadEvent(LoadEvent.BYTES_LOADED_CHANGE,false,false,null,this.bytesLoaded));
dispatchEvent(new LoadEvent(LoadEvent.BYTES_TOTAL_CHANGE,false,false,null,this.bytesTotal));
}
}
override public function get bytesLoaded() : Number
{
return this.isStreamingResource ? NaN : (this.netStream != null ? this.netStream.bytesLoaded : NaN);
}
override public function get bytesTotal() : Number
{
return this.isStreamingResource ? NaN : (this.netStream != null ? this.netStream.bytesTotal : NaN);
}
private function onNetStatus(event:NetStatusEvent) : void
{
if(this.netStream != null && this.netStream.bytesTotal > 0)
{
dispatchEvent(new LoadEvent(LoadEvent.BYTES_TOTAL_CHANGE,false,false,null,this.netStream.bytesTotal));
this.netStream.removeEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
}
}
public function get netGroup() : NetGroup
{
return this._netGroup;
}
public function set netGroup(value:NetGroup) : void
{
this._netGroup = value;
}
}
}
@@ -0,0 +1,176 @@
package org.osmf.net
{
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetStream;
import flash.utils.Timer;
public class NetStreamMetricsBase extends EventDispatcher
{
private static const DEFAULT_UPDATE_INTERVAL:Number = 100;
private static const DEFAULT_AVG_FRAMERATE_SAMPLE_SIZE:Number = 50;
private var _netStream:NetStream;
private var _resource:DynamicStreamingResource;
private var _currentIndex:int;
private var _maxAllowedIndex:int;
private var _timer:Timer;
private var _averageDroppedFPSArray:Array;
private var _averageDroppedFPS:Number;
private var _droppedFPS:Number;
private var _lastFrameDropValue:Number;
private var _lastFrameDropCounter:Number;
private var _maxFPS:Number;
public function NetStreamMetricsBase(netStream:NetStream)
{
super();
this._netStream = netStream;
this._droppedFPS = 0;
this._lastFrameDropCounter = 0;
this._lastFrameDropValue = 0;
this._maxFPS = 0;
this._averageDroppedFPSArray = new Array();
this._timer = new Timer(DEFAULT_UPDATE_INTERVAL);
this._timer.addEventListener(TimerEvent.TIMER,this.onTimerEvent);
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatusEvent);
}
public function get resource() : DynamicStreamingResource
{
return this._resource;
}
public function set resource(value:DynamicStreamingResource) : void
{
this._resource = value;
this._maxAllowedIndex = value != null ? int(value.streamItems.length - 1) : 0;
}
public function get netStream() : NetStream
{
return this._netStream;
}
public function get currentIndex() : int
{
return this._currentIndex;
}
public function set currentIndex(value:int) : void
{
this._currentIndex = value;
}
public function get maxAllowedIndex() : int
{
return this._maxAllowedIndex;
}
public function set maxAllowedIndex(value:int) : void
{
this._maxAllowedIndex = value;
}
public function get updateInterval() : Number
{
return this._timer.delay;
}
public function set updateInterval(value:Number) : void
{
this._timer.delay = value;
if(value <= 0)
{
this._timer.stop();
}
}
public function get maxFPS() : Number
{
return this._maxFPS;
}
public function get droppedFPS() : Number
{
return this._droppedFPS;
}
public function get averageDroppedFPS() : Number
{
return this._averageDroppedFPS;
}
protected function calculateMetrics() : void
{
var totalDroppedFrameRate:Number = NaN;
var f:uint = 0;
try
{
this._maxFPS = this.netStream.currentFPS > this._maxFPS ? this.netStream.currentFPS : this._maxFPS;
if(this._timer.currentCount - this._lastFrameDropCounter > 1000 / this._timer.delay)
{
this._droppedFPS = (this.netStream.info.droppedFrames - this._lastFrameDropValue) / ((this._timer.currentCount - this._lastFrameDropCounter) * this._timer.delay / 1000);
this._lastFrameDropCounter = this._timer.currentCount;
this._lastFrameDropValue = this.netStream.info.droppedFrames;
}
this._averageDroppedFPSArray.unshift(this._droppedFPS);
if(this._averageDroppedFPSArray.length > DEFAULT_AVG_FRAMERATE_SAMPLE_SIZE)
{
this._averageDroppedFPSArray.pop();
}
totalDroppedFrameRate = 0;
for(f = 0; f < this._averageDroppedFPSArray.length; f++)
{
totalDroppedFrameRate += this._averageDroppedFPSArray[f];
}
this._averageDroppedFPS = this._averageDroppedFPSArray.length < DEFAULT_AVG_FRAMERATE_SAMPLE_SIZE ? 0 : totalDroppedFrameRate / this._averageDroppedFPSArray.length;
}
catch(error:Error)
{
throw error;
}
}
private function onNetStatusEvent(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_START:
if(!this._timer.running && this.updateInterval > 0)
{
this._timer.start();
}
break;
case NetStreamCodes.NETSTREAM_PLAY_STOP:
this._timer.stop();
}
}
private function onTimerEvent(event:TimerEvent) : void
{
if(isNaN(this.netStream.time))
{
this._timer.stop();
}
else
{
this.calculateMetrics();
}
}
}
}
@@ -0,0 +1,172 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import flash.net.NetStreamPlayTransitions;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.events.MediaErrorEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.traits.PlayState;
import org.osmf.traits.PlayTrait;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
public class NetStreamPlayTrait extends PlayTrait
{
private static const NETCONNECTION_FAILURE_ERROR_CODE:int = 2154;
private var streamStarted:Boolean;
private var netStream:NetStream;
private var netConnection:NetConnection;
private var urlResource:URLResource;
private var multicastResource:MulticastResource;
private var reconnectStreams:Boolean;
public function NetStreamPlayTrait(netStream:NetStream, resource:MediaResourceBase, reconnectStreams:Boolean, netConnection:NetConnection)
{
super();
if(netStream == null)
{
throw new ArgumentError(OSMFStrings.getString(OSMFStrings.NULL_PARAM));
}
this.netStream = netStream;
this.netConnection = netConnection;
this.urlResource = resource as URLResource;
this.multicastResource = resource as MulticastResource;
this.reconnectStreams = reconnectStreams;
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus,false,1,true);
NetClient(netStream.client).addHandler(NetStreamCodes.ON_PLAY_STATUS,this.onPlayStatus,1);
}
override protected function playStateChangeStart(newPlayState:String) : void
{
var playArgs:Object = null;
var streamingResource:StreamingURLResource = null;
var urlIncludesFMSApplicationInstance:Boolean = false;
var streamName:String = null;
var startTime:Number = NaN;
var len:Number = NaN;
var dsResource:DynamicStreamingResource = null;
var nso:NetStreamPlayOptions = null;
if(newPlayState == PlayState.PLAYING)
{
if(this.streamStarted)
{
if(this.multicastResource != null)
{
this.netStream.play(this.multicastResource.streamName,-1,-1);
}
else
{
this.netStream.resume();
}
}
else if(this.urlResource != null)
{
streamingResource = this.urlResource as StreamingURLResource;
urlIncludesFMSApplicationInstance = Boolean(streamingResource) ? streamingResource.urlIncludesFMSApplicationInstance : false;
streamName = NetStreamUtils.getStreamNameFromURL(this.urlResource.url,urlIncludesFMSApplicationInstance);
playArgs = NetStreamUtils.getPlayArgsForResource(this.urlResource);
startTime = Number(playArgs.start);
len = Number(playArgs.len);
dsResource = this.urlResource as DynamicStreamingResource;
if(dsResource != null)
{
nso = new NetStreamPlayOptions();
nso.start = startTime;
nso.len = len;
nso.streamName = dsResource.streamItems[dsResource.initialIndex].streamName;
nso.transition = NetStreamPlayTransitions.RESET;
this.doPlay2(nso);
}
else if(this.reconnectStreams && streamingResource != null && NetStreamUtils.isRTMPStream(streamingResource.url))
{
nso = new NetStreamPlayOptions();
nso.start = startTime;
nso.len = len;
nso.transition = NetStreamPlayTransitions.RESET;
nso.streamName = streamName;
this.doPlay2(nso);
}
else if(this.multicastResource != null && this.multicastResource.groupspec != null && this.multicastResource.groupspec.length > 0)
{
this.doPlay(this.multicastResource.streamName,startTime,len);
}
else
{
this.doPlay(streamName,startTime,len);
}
}
}
else if(this.multicastResource != null)
{
this.netStream.play(false);
}
else
{
this.netStream.pause();
}
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_FAILED:
case NetStreamCodes.NETSTREAM_PLAY_FILESTRUCTUREINVALID:
case NetStreamCodes.NETSTREAM_PLAY_STREAMNOTFOUND:
case NetStreamCodes.NETSTREAM_PLAY_NOSUPPORTEDTRACKFOUND:
case NetStreamCodes.NETSTREAM_FAILED:
this.netStream.pause();
this.streamStarted = false;
break;
case NetStreamCodes.NETSTREAM_PLAY_STOP:
if(this.urlResource != null && NetStreamUtils.isStreamingResource(this.urlResource) == false)
{
stop();
}
}
}
private function onPlayStatus(event:Object) : void
{
switch(event.code)
{
case NetStreamCodes.NETSTREAM_PLAY_COMPLETE:
stop();
}
}
private function doPlay(... args) : void
{
try
{
this.netStream.play.apply(this,args);
this.streamStarted = true;
}
catch(error:Error)
{
streamStarted = false;
stop();
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR,false,false,new MediaError(MediaErrorCodes.NETSTREAM_PLAY_FAILED)));
}
}
private function doPlay2(nspo:NetStreamPlayOptions) : void
{
this.netStream.play2(nspo);
this.streamStarted = true;
}
}
}
@@ -0,0 +1,142 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.media.Video;
import flash.net.NetStream;
import flash.utils.Timer;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.SeekTrait;
import org.osmf.traits.TimeTrait;
[ExcludeClass]
public class NetStreamSeekTrait extends SeekTrait
{
private var video:Video;
private var loadTrait:LoadTrait;
private var audioDelay:Number = 0;
private var seekBugTimer:Timer;
private var netStream:NetStream;
private var expectedTime:Number;
private var previousTime:Number;
private var suppressSeekNotifyEvent:Boolean = false;
public function NetStreamSeekTrait(temporal:TimeTrait, loadTrait:LoadTrait, netStream:NetStream, video:Video = null)
{
super(temporal);
this.netStream = netStream;
this.video = video;
this.loadTrait = loadTrait;
NetClient(netStream.client).addHandler(NetStreamCodes.ON_META_DATA,this.onMetaData);
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
this.seekBugTimer = new Timer(10,100);
this.seekBugTimer.addEventListener(TimerEvent.TIMER,this.onSeekBugTimer,false,0,true);
this.seekBugTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.onSeekBugTimerDone,false,0,true);
}
override public function canSeekTo(time:Number) : Boolean
{
var maxSeekTime:Number = NaN;
var result:Boolean = super.canSeekTo(time);
if(result && !isNaN(this.loadTrait.bytesTotal) && this.loadTrait.bytesTotal > 0)
{
maxSeekTime = timeTrait.duration * Number(this.loadTrait.bytesLoaded / this.loadTrait.bytesTotal);
result = time <= maxSeekTime;
}
return result;
}
override protected function seekingChangeStart(newSeeking:Boolean, time:Number) : void
{
if(newSeeking)
{
this.suppressSeekNotifyEvent = false;
this.previousTime = this.netStream.time - this.audioDelay;
this.expectedTime = time;
this.netStream.seek(time + this.audioDelay);
if(this.previousTime == this.expectedTime)
{
this.seekBugTimer.start();
this.suppressSeekNotifyEvent = true;
}
}
}
override protected function seekingChangeEnd(time:Number) : void
{
var nsTimeTrait:NetStreamTimeTrait = null;
super.seekingChangeEnd(time);
if(seeking == true && this.video != null)
{
nsTimeTrait = timeTrait as NetStreamTimeTrait;
if(nsTimeTrait != null && nsTimeTrait.currentTime + nsTimeTrait.audioDelay >= nsTimeTrait.duration)
{
this.video.clear();
}
}
}
private function onMetaData(value:Object) : void
{
this.audioDelay = value.hasOwnProperty("audiodelay") ? Number(value.audiodelay) : 0;
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_SEEK_NOTIFY:
this.runSeekBugTimer();
break;
case NetStreamCodes.NETSTREAM_SEEK_INVALIDTIME:
case NetStreamCodes.NETSTREAM_SEEK_FAILED:
setSeeking(false,this.previousTime);
break;
case NetStreamCodes.NETSTREAM_PLAY_START:
case NetStreamCodes.NETSTREAM_PLAY_RESET:
case NetStreamCodes.NETSTREAM_PAUSE_NOTIFY:
case NetStreamCodes.NETSTREAM_PLAY_STOP:
case NetStreamCodes.NETSTREAM_UNPAUSE_NOTIFY:
if(seeking && this.seekBugTimer.running == false)
{
this.runSeekBugTimer();
}
}
}
private function runSeekBugTimer() : void
{
if(this.suppressSeekNotifyEvent == false)
{
this.seekBugTimer.start();
}
else
{
this.suppressSeekNotifyEvent = false;
}
}
private function onSeekBugTimer(event:TimerEvent) : void
{
if(this.previousTime != this.netStream.time - this.audioDelay || this.previousTime == this.expectedTime)
{
this.onSeekBugTimerDone(null);
}
}
private function onSeekBugTimerDone(event:TimerEvent) : void
{
this.seekBugTimer.reset();
setSeeking(false,this.expectedTime);
}
}
}
@@ -0,0 +1,313 @@
package org.osmf.net
{
import flash.errors.IllegalOperationError;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import flash.net.NetStreamPlayTransitions;
import flash.utils.Dictionary;
import flash.utils.Timer;
import flash.utils.getTimer;
import org.osmf.utils.OSMFStrings;
public class NetStreamSwitchManager extends NetStreamSwitchManagerBase
{
private static const RULE_CHECK_INTERVAL:Number = 500;
private static const DEFAULT_MAX_UP_SWITCHES_PER_STREAM_ITEM:int = 3;
private static const DEFAULT_WAIT_DURATION_AFTER_DOWN_SWITCH:int = 30000;
private static const DEFAULT_CLEAR_FAILED_COUNTS_INTERVAL:Number = 300000;
private var netStream:NetStream;
private var dsResource:DynamicStreamingResource;
private var switchingRules:Vector.<SwitchingRuleBase>;
private var metrics:NetStreamMetricsBase;
private var checkRulesTimer:Timer;
private var clearFailedCountsTimer:Timer;
private var actualIndex:int = -1;
private var oldStreamName:String;
private var switching:Boolean;
private var _currentIndex:int;
private var lastTransitionIndex:int = -1;
private var connection:NetConnection;
private var dsiFailedCounts:Vector.<int>;
private var failedDSI:Dictionary;
private var _bandwidthLimit:Number = 0;
public function NetStreamSwitchManager(connection:NetConnection, netStream:NetStream, resource:DynamicStreamingResource, metrics:NetStreamMetricsBase, switchingRules:Vector.<SwitchingRuleBase>)
{
super();
this.connection = connection;
this.netStream = netStream;
this.dsResource = resource;
this.metrics = metrics;
this.switchingRules = switchingRules || new Vector.<SwitchingRuleBase>();
this._currentIndex = Math.max(0,Math.min(this.maxAllowedIndex,this.dsResource.initialIndex));
this.checkRulesTimer = new Timer(RULE_CHECK_INTERVAL);
this.checkRulesTimer.addEventListener(TimerEvent.TIMER,this.checkRules);
this.failedDSI = new Dictionary();
this._bandwidthLimit = 1.4 * resource.streamItems[resource.streamItems.length - 1].bitrate * 1000 / 8;
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
NetClient(netStream.client).addHandler(NetStreamCodes.ON_PLAY_STATUS,this.onPlayStatus,int.MAX_VALUE);
}
override public function set autoSwitch(value:Boolean) : void
{
super.autoSwitch = value;
if(autoSwitch)
{
this.checkRulesTimer.start();
}
else
{
this.checkRulesTimer.stop();
}
}
override public function get currentIndex() : uint
{
return this._currentIndex;
}
override public function get maxAllowedIndex() : int
{
var count:int = this.dsResource.streamItems.length - 1;
return count < super.maxAllowedIndex ? count : super.maxAllowedIndex;
}
override public function set maxAllowedIndex(value:int) : void
{
if(value > this.dsResource.streamItems.length)
{
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
super.maxAllowedIndex = value;
this.metrics.maxAllowedIndex = value;
}
override public function switchTo(index:int) : void
{
if(!autoSwitch)
{
if(index < 0 || index > this.maxAllowedIndex)
{
throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX));
}
if(this.actualIndex == -1)
{
this.prepareForSwitching();
}
this.executeSwitch(index);
return;
}
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_STREAM_NOT_IN_MANUAL_MODE));
}
protected function canAutoSwitchNow(newIndex:int) : Boolean
{
var current:int = 0;
if(this.dsiFailedCounts[newIndex] >= 1)
{
current = getTimer();
if(current - this.failedDSI[newIndex] < DEFAULT_WAIT_DURATION_AFTER_DOWN_SWITCH)
{
return false;
}
}
else if(this.dsiFailedCounts[newIndex] > DEFAULT_MAX_UP_SWITCHES_PER_STREAM_ITEM)
{
return false;
}
return true;
}
final protected function get bandwidthLimit() : Number
{
return this._bandwidthLimit;
}
final protected function set bandwidthLimit(value:Number) : void
{
this._bandwidthLimit = value;
}
private function executeSwitch(targetIndex:int) : void
{
var nso:NetStreamPlayOptions = new NetStreamPlayOptions();
var playArgs:Object = NetStreamUtils.getPlayArgsForResource(this.dsResource);
nso.start = playArgs.start;
nso.len = playArgs.len;
nso.streamName = this.dsResource.streamItems[targetIndex].streamName;
var sn:String = this.oldStreamName;
if(sn != null && sn.indexOf("?") >= 0)
{
nso.oldStreamName = sn.substr(0,sn.indexOf("?"));
}
else
{
nso.oldStreamName = this.oldStreamName;
}
nso.transition = NetStreamPlayTransitions.SWITCH;
this.switching = true;
this.netStream.play2(nso);
this.oldStreamName = this.dsResource.streamItems[targetIndex].streamName;
if(targetIndex < this.actualIndex && autoSwitch)
{
this.incrementDSIFailedCount(this.actualIndex);
this.failedDSI[this.actualIndex] = getTimer();
}
}
private function checkRules(event:TimerEvent) : void
{
var n:int = 0;
if(this.switchingRules == null || this.switching)
{
return;
}
var newIndex:int = int.MAX_VALUE;
for(var i:int = 0; i < this.switchingRules.length; i++)
{
n = this.switchingRules[i].getNewIndex();
if(n != -1 && n < newIndex)
{
newIndex = n;
}
}
if(newIndex != -1 && newIndex != int.MAX_VALUE && newIndex != this.actualIndex)
{
newIndex = Math.min(newIndex,this.maxAllowedIndex);
}
if(newIndex != -1 && newIndex != int.MAX_VALUE && newIndex != this.actualIndex && !this.switching && newIndex <= this.maxAllowedIndex && this.canAutoSwitchNow(newIndex))
{
this.executeSwitch(newIndex);
}
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_START:
if(this.actualIndex == -1)
{
this.prepareForSwitching();
}
else if(autoSwitch && this.checkRulesTimer.running == false)
{
this.checkRulesTimer.start();
}
break;
case NetStreamCodes.NETSTREAM_PLAY_TRANSITION:
this.switching = false;
this.actualIndex = this.dsResource.indexFromName(event.info.details);
this.metrics.currentIndex = this.actualIndex;
this.lastTransitionIndex = this.actualIndex;
break;
case NetStreamCodes.NETSTREAM_PLAY_FAILED:
this.switching = false;
break;
case NetStreamCodes.NETSTREAM_SEEK_NOTIFY:
this.switching = false;
if(this.lastTransitionIndex >= 0)
{
this._currentIndex = this.lastTransitionIndex;
}
break;
case NetStreamCodes.NETSTREAM_PLAY_STOP:
this.checkRulesTimer.stop();
}
}
private function onPlayStatus(info:Object) : void
{
switch(info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_TRANSITION_COMPLETE:
if(this.lastTransitionIndex >= 0)
{
this._currentIndex = this.lastTransitionIndex;
this.lastTransitionIndex = -1;
}
}
}
private function prepareForSwitching() : void
{
this.initDSIFailedCounts();
this.metrics.resource = this.dsResource;
this.actualIndex = 0;
this.lastTransitionIndex = -1;
if(this.dsResource.initialIndex >= 0 && this.dsResource.initialIndex < this.dsResource.streamItems.length)
{
this.actualIndex = this.dsResource.initialIndex;
}
if(autoSwitch)
{
this.checkRulesTimer.start();
}
this.setThrottleLimits(this.dsResource.streamItems.length - 1);
this.metrics.currentIndex = this.actualIndex;
}
private function initDSIFailedCounts() : void
{
if(this.dsiFailedCounts != null)
{
this.dsiFailedCounts.length = 0;
this.dsiFailedCounts = null;
}
this.dsiFailedCounts = new Vector.<int>();
for(var i:int = 0; i < this.dsResource.streamItems.length; i++)
{
this.dsiFailedCounts.push(0);
}
}
private function incrementDSIFailedCount(index:int) : void
{
++this.dsiFailedCounts[index];
if(this.dsiFailedCounts[index] > DEFAULT_MAX_UP_SWITCHES_PER_STREAM_ITEM)
{
if(this.clearFailedCountsTimer == null)
{
this.clearFailedCountsTimer = new Timer(DEFAULT_CLEAR_FAILED_COUNTS_INTERVAL,1);
this.clearFailedCountsTimer.addEventListener(TimerEvent.TIMER,this.clearFailedCounts);
}
this.clearFailedCountsTimer.start();
}
}
private function clearFailedCounts(event:TimerEvent) : void
{
this.clearFailedCountsTimer.removeEventListener(TimerEvent.TIMER,this.clearFailedCounts);
this.clearFailedCountsTimer = null;
this.initDSIFailedCounts();
}
private function setThrottleLimits(index:int) : void
{
this.connection.call("setBandwidthLimit",null,this._bandwidthLimit,this._bandwidthLimit);
}
}
}
@@ -0,0 +1,49 @@
package org.osmf.net
{
import flash.events.EventDispatcher;
public class NetStreamSwitchManagerBase extends EventDispatcher
{
private var _autoSwitch:Boolean;
private var _maxAllowedIndex:int;
public function NetStreamSwitchManagerBase()
{
super();
this._autoSwitch = true;
this._maxAllowedIndex = int.MAX_VALUE;
}
public function get autoSwitch() : Boolean
{
return this._autoSwitch;
}
public function set autoSwitch(value:Boolean) : void
{
this._autoSwitch = value;
}
public function get currentIndex() : uint
{
return 0;
}
public function get maxAllowedIndex() : int
{
return this._maxAllowedIndex;
}
public function set maxAllowedIndex(value:int) : void
{
this._maxAllowedIndex = value;
}
public function switchTo(index:int) : void
{
}
}
}
@@ -0,0 +1,107 @@
package org.osmf.net
{
import flash.events.NetStatusEvent;
import flash.net.NetStream;
import org.osmf.media.MediaResourceBase;
import org.osmf.traits.TimeTrait;
[ExcludeClass]
public class NetStreamTimeTrait extends TimeTrait
{
private var durationOffset:Number = 0;
private var _audioDelay:Number = 0;
private var netStream:NetStream;
private var resource:MediaResourceBase;
private var multicast:Boolean = false;
public function NetStreamTimeTrait(netStream:NetStream, resource:MediaResourceBase, defaultDuration:Number = NaN)
{
super();
this.netStream = netStream;
NetClient(netStream.client).addHandler(NetStreamCodes.ON_META_DATA,this.onMetaData);
NetClient(netStream.client).addHandler(NetStreamCodes.ON_PLAY_STATUS,this.onPlayStatus);
netStream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus,false,0,true);
this.resource = resource;
if(isNaN(defaultDuration) == false)
{
setDuration(defaultDuration);
}
var streamResource:MulticastResource = resource as MulticastResource;
if(streamResource != null && streamResource.groupspec != null && streamResource.groupspec.length > 0)
{
this.multicast = true;
setDuration(Number.MAX_VALUE);
}
}
override public function get currentTime() : Number
{
if(this.multicast)
{
return 0;
}
if(this.durationOffset == duration - (this.netStream.time - this._audioDelay))
{
return this.netStream.time - this._audioDelay + this.durationOffset;
}
return this.netStream.time - this._audioDelay;
}
private function onMetaData(value:Object) : void
{
var playArgs:Object = NetStreamUtils.getPlayArgsForResource(this.resource);
this._audioDelay = value.hasOwnProperty("audiodelay") ? Number(value.audiodelay) : 0;
var subclipStartTime:Number = Math.max(0,playArgs.start);
var subclipDuration:Number = Number(playArgs.len);
if(subclipDuration == NetStreamUtils.PLAY_LEN_ARG_ALL)
{
subclipDuration = Number.MAX_VALUE;
}
setDuration(Math.min(value.duration - this._audioDelay - subclipStartTime,subclipDuration));
}
private function onPlayStatus(event:Object) : void
{
switch(event.code)
{
case NetStreamCodes.NETSTREAM_PLAY_COMPLETE:
this.signalComplete();
}
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_STOP:
if(NetStreamUtils.isStreamingResource(this.resource) == false)
{
this.signalComplete();
}
break;
case NetStreamCodes.NETSTREAM_PLAY_UNPUBLISH_NOTIFY:
this.signalComplete();
}
}
override protected function signalComplete() : void
{
if(this.netStream.time - this._audioDelay != duration)
{
this.durationOffset = duration - (this.netStream.time - this._audioDelay);
}
super.signalComplete();
}
internal function get audioDelay() : Number
{
return this._audioDelay;
}
}
}
@@ -0,0 +1,134 @@
package org.osmf.net
{
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.utils.URL;
[ExcludeClass]
public class NetStreamUtils
{
public static const PLAY_START_ARG_ANY:int = -2;
public static const PLAY_START_ARG_LIVE:int = -1;
public static const PLAY_START_ARG_RECORDED:int = 0;
public static const PLAY_LEN_ARG_ALL:int = -1;
public function NetStreamUtils()
{
super();
}
public static function getStreamNameFromURL(url:String, urlIncludesFMSApplicationInstance:Boolean = false) : String
{
var fmsURL:FMSURL = null;
var streamName:String = "";
if(url != null)
{
if(isRTMPStream(url))
{
fmsURL = new FMSURL(url,urlIncludesFMSApplicationInstance);
streamName = fmsURL.streamName;
if(fmsURL.query != null && fmsURL.query != "")
{
streamName += "?" + fmsURL.query;
}
}
else
{
streamName = url;
}
}
return streamName;
}
public static function isStreamingResource(resource:MediaResourceBase) : Boolean
{
var urlResource:URLResource = null;
var result:Boolean = false;
if(resource != null)
{
urlResource = resource as URLResource;
if(urlResource != null)
{
result = NetStreamUtils.isRTMPStream(urlResource.url);
if(result == false)
{
result = urlResource.getMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA) != null;
}
}
}
return result;
}
public static function isRTMPStream(url:String) : Boolean
{
var theURL:URL = null;
var protocol:String = null;
var result:Boolean = false;
if(url != null)
{
theURL = new URL(url);
protocol = theURL.protocol;
if(protocol != null && protocol.length > 0)
{
result = protocol.search(/^rtmp$|rtmp[tse]$|rtmpte$/i) != -1;
}
}
return result;
}
public static function getStreamType(resource:MediaResourceBase) : String
{
var streamType:String = StreamType.RECORDED;
var streamingURLResource:StreamingURLResource = resource as StreamingURLResource;
if(streamingURLResource != null)
{
streamType = streamingURLResource.streamType;
}
return streamType;
}
public static function getPlayArgsForResource(resource:MediaResourceBase) : Object
{
var streamingResource:StreamingURLResource = null;
var startArg:Number = PLAY_START_ARG_ANY;
var lenArg:Number = PLAY_LEN_ARG_ALL;
switch(getStreamType(resource))
{
case StreamType.LIVE_OR_RECORDED:
startArg = PLAY_START_ARG_ANY;
break;
case StreamType.LIVE:
startArg = PLAY_START_ARG_LIVE;
break;
case StreamType.RECORDED:
startArg = PLAY_START_ARG_RECORDED;
}
if(startArg != PLAY_START_ARG_LIVE && resource != null)
{
streamingResource = resource as StreamingURLResource;
if(streamingResource != null && isStreamingResource(streamingResource))
{
if(!isNaN(streamingResource.clipStartTime))
{
startArg = streamingResource.clipStartTime;
}
if(!isNaN(streamingResource.clipEndTime))
{
startArg = Math.max(0,startArg);
lenArg = Math.max(0,streamingResource.clipEndTime - startArg);
}
}
}
return {
"start":startArg,
"len":lenArg
};
}
}
}
@@ -0,0 +1,37 @@
package org.osmf.net
{
[ExcludeClass]
public class PortProtocol
{
private var _port:int;
private var _protocol:String;
public function PortProtocol()
{
super();
}
public function get port() : int
{
return this._port;
}
public function set port(value:int) : void
{
this._port = value;
}
public function get protocol() : String
{
return this._protocol;
}
public function set protocol(value:String) : void
{
this._protocol = value;
}
}
}
@@ -0,0 +1,20 @@
package org.osmf.net
{
public final class StreamType
{
public static const LIVE:String = "live";
public static const RECORDED:String = "recorded";
public static const LIVE_OR_RECORDED:String = "liveOrRecorded";
public static const DVR:String = "dvr";
public function StreamType()
{
super();
}
}
}
@@ -0,0 +1,93 @@
package org.osmf.net
{
import flash.utils.ByteArray;
import org.osmf.media.URLResource;
public class StreamingURLResource extends URLResource
{
private var _streamType:String;
private var _clipStartTime:Number;
private var _clipEndTime:Number;
private var _connectionArguments:Vector.<Object>;
private var _drmContentData:ByteArray;
private var _urlIncludesFMSApplicationInstance:Boolean = false;
public function StreamingURLResource(url:String, streamType:String = null, clipStartTime:Number = NaN, clipEndTime:Number = NaN, connectionArguments:Vector.<Object> = null, urlIncludesFMSApplicationInstance:Boolean = false, drmContentData:ByteArray = null)
{
this._streamType = streamType || StreamType.RECORDED;
this._clipStartTime = clipStartTime;
this._clipEndTime = clipEndTime;
this._urlIncludesFMSApplicationInstance = urlIncludesFMSApplicationInstance;
this._drmContentData = drmContentData;
this._connectionArguments = connectionArguments;
super(url);
}
public function get streamType() : String
{
return this._streamType;
}
public function set streamType(value:String) : void
{
this._streamType = value;
}
public function get clipStartTime() : Number
{
return this._clipStartTime;
}
public function set clipStartTime(value:Number) : void
{
this._clipStartTime = value;
}
public function get clipEndTime() : Number
{
return this._clipEndTime;
}
public function set clipEndTime(value:Number) : void
{
this._clipEndTime = value;
}
public function get connectionArguments() : Vector.<Object>
{
return this._connectionArguments;
}
public function set connectionArguments(value:Vector.<Object>) : void
{
this._connectionArguments = value;
}
public function get drmContentData() : ByteArray
{
return this._drmContentData;
}
public function set drmContentData(value:ByteArray) : void
{
this._drmContentData = value;
}
public function get urlIncludesFMSApplicationInstance() : Boolean
{
return this._urlIncludesFMSApplicationInstance;
}
public function set urlIncludesFMSApplicationInstance(value:Boolean) : void
{
this._urlIncludesFMSApplicationInstance = value;
}
}
}
@@ -0,0 +1,25 @@
package org.osmf.net
{
public class SwitchingRuleBase
{
private var _metrics:NetStreamMetricsBase;
public function SwitchingRuleBase(metrics:NetStreamMetricsBase)
{
super();
this._metrics = metrics;
}
public function getNewIndex() : int
{
return -1;
}
protected function get metrics() : NetStreamMetricsBase
{
return this._metrics;
}
}
}
@@ -0,0 +1,297 @@
package org.osmf.net.drm
{
import flash.errors.IllegalOperationError;
import flash.events.DRMAuthenticationCompleteEvent;
import flash.events.DRMAuthenticationErrorEvent;
import flash.events.DRMErrorEvent;
import flash.events.DRMStatusEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.StatusEvent;
import flash.net.drm.DRMContentData;
import flash.net.drm.DRMManager;
import flash.net.drm.DRMVoucher;
import flash.net.drm.LoadVoucherSetting;
import flash.system.SystemUpdater;
import flash.system.SystemUpdaterType;
import flash.utils.ByteArray;
import org.osmf.events.DRMEvent;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.traits.DRMState;
import org.osmf.utils.OSMFStrings;
[Event(name="drmStateChange",type="org.osmf.events.DRMEvent")]
[ExcludeClass]
internal class DRMServices extends EventDispatcher
{
private static var updater:SystemUpdater;
private static const DRM_AUTHENTICATION_FAILED:int = 3301;
private static const DRM_NEEDS_AUTHENTICATION:int = 3330;
private static const DRM_CONTENT_NOT_YET_VALID:int = 3331;
private var _drmState:String = "uninitialized";
private var lastToken:ByteArray;
private var drmContentData:DRMContentData;
private var voucher:DRMVoucher;
private var drmManager:DRMManager;
public function DRMServices()
{
super();
this.drmManager = DRMManager.getDRMManager();
}
public function get drmState() : String
{
return this._drmState;
}
public function set drmMetadata(value:Object) : void
{
var onComplete:Function = null;
this.lastToken = null;
if(value is DRMContentData)
{
this.drmContentData = value as DRMContentData;
this.retrieveVoucher();
}
else
{
try
{
this.drmContentData = new DRMContentData(value as ByteArray);
this.retrieveVoucher();
}
catch(argError:ArgumentError)
{
updateDRMState(DRMState.AUTHENTICATION_ERROR,new MediaError(argError.errorID,"DRMContentData invalid"));
}
catch(error:IllegalOperationError)
{
onComplete = function(event:Event):void
{
updater.removeEventListener(Event.COMPLETE,onComplete);
drmMetadata = value;
};
update(SystemUpdaterType.DRM);
updater.addEventListener(Event.COMPLETE,onComplete);
}
}
}
public function get drmMetadata() : Object
{
return this.drmContentData;
}
public function authenticate(username:String = null, password:String = null) : void
{
if(this.drmContentData == null)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.DRM_METADATA_NOT_SET));
}
this.drmManager.addEventListener(DRMAuthenticationErrorEvent.AUTHENTICATION_ERROR,this.authError);
this.drmManager.addEventListener(DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETE,this.authComplete);
if(password == null && username == null)
{
this.retrieveVoucher();
}
else
{
this.drmManager.authenticate(this.drmContentData.serverURL,this.drmContentData.domain,username,password);
}
}
public function authenticateWithToken(token:Object) : void
{
if(this.drmContentData == null)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.DRM_METADATA_NOT_SET));
}
this.drmManager.setAuthenticationToken(this.drmContentData.serverURL,this.drmContentData.domain,token as ByteArray);
this.retrieveVoucher();
}
public function get startDate() : Date
{
if(this.voucher != null)
{
return Boolean(this.voucher.playbackTimeWindow) ? this.voucher.playbackTimeWindow.startDate : this.voucher.voucherStartDate;
}
return null;
}
public function get endDate() : Date
{
if(this.voucher != null)
{
return Boolean(this.voucher.playbackTimeWindow) ? this.voucher.playbackTimeWindow.endDate : this.voucher.voucherEndDate;
}
return null;
}
public function get period() : Number
{
if(this.voucher != null)
{
return Boolean(this.voucher.playbackTimeWindow) ? this.voucher.playbackTimeWindow.period : (Boolean(this.voucher.voucherEndDate) && Boolean(this.voucher.voucherStartDate) ? (this.voucher.voucherEndDate.time - this.voucher.voucherStartDate.time) / 1000 : 0);
}
return NaN;
}
public function inlineDRMFailed(error:MediaError) : void
{
this.updateDRMState(DRMState.AUTHENTICATION_ERROR,error);
}
public function inlineOnVoucher(event:DRMStatusEvent) : void
{
this.drmContentData = event.contentData;
this.onVoucherLoaded(event);
}
public function update(type:String) : SystemUpdater
{
this.updateDRMState(DRMState.DRM_SYSTEM_UPDATING);
if(updater == null)
{
updater = new SystemUpdater();
this.toggleErrorListeners(updater,true);
updater.update(type);
}
else
{
this.toggleErrorListeners(updater,true);
}
return updater;
}
private function retrieveVoucher() : void
{
this.updateDRMState(DRMState.AUTHENTICATING);
this.drmManager.addEventListener(DRMErrorEvent.DRM_ERROR,this.onDRMError);
this.drmManager.addEventListener(DRMStatusEvent.DRM_STATUS,this.onVoucherLoaded);
this.drmManager.loadVoucher(this.drmContentData,LoadVoucherSetting.ALLOW_SERVER);
}
private function onVoucherLoaded(event:DRMStatusEvent) : void
{
var now:Date = null;
if(event.contentData == this.drmContentData)
{
now = new Date();
if(Boolean(event.voucher) && ((event.voucher.voucherEndDate == null || event.voucher.voucherEndDate.time >= now.time) && (event.voucher.voucherStartDate == null || event.voucher.voucherStartDate.time <= now.time)))
{
this.voucher = event.voucher;
this.removeEventListeners();
if(this.voucher.playbackTimeWindow == null)
{
this.updateDRMState(DRMState.AUTHENTICATION_COMPLETE,null,this.voucher.voucherStartDate,this.voucher.voucherEndDate,this.period,this.lastToken);
}
else
{
this.updateDRMState(DRMState.AUTHENTICATION_COMPLETE,null,this.voucher.playbackTimeWindow.startDate,this.voucher.playbackTimeWindow.endDate,this.voucher.playbackTimeWindow.period,this.lastToken);
}
}
else
{
this.forceRefreshVoucher();
}
}
}
private function forceRefreshVoucher() : void
{
this.drmManager.loadVoucher(this.drmContentData,LoadVoucherSetting.FORCE_REFRESH);
}
private function onDRMError(event:DRMErrorEvent) : void
{
if(event.contentData == this.drmContentData)
{
switch(event.errorID)
{
case DRM_CONTENT_NOT_YET_VALID:
this.forceRefreshVoucher();
break;
case DRM_NEEDS_AUTHENTICATION:
this.updateDRMState(DRMState.AUTHENTICATION_NEEDED,null,null,null,0,null,event.contentData.serverURL);
break;
default:
this.removeEventListeners();
this.updateDRMState(DRMState.AUTHENTICATION_ERROR,new MediaError(event.errorID,event.text));
}
}
}
private function removeEventListeners() : void
{
this.drmManager.removeEventListener(DRMErrorEvent.DRM_ERROR,this.onDRMError);
this.drmManager.removeEventListener(DRMStatusEvent.DRM_STATUS,this.onVoucherLoaded);
}
private function authComplete(event:DRMAuthenticationCompleteEvent) : void
{
this.drmManager.removeEventListener(DRMAuthenticationErrorEvent.AUTHENTICATION_ERROR,this.authError);
this.drmManager.removeEventListener(DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETE,this.authComplete);
this.lastToken = event.token;
this.retrieveVoucher();
}
private function authError(event:DRMAuthenticationErrorEvent) : void
{
this.drmManager.removeEventListener(DRMAuthenticationErrorEvent.AUTHENTICATION_ERROR,this.authError);
this.drmManager.removeEventListener(DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETE,this.authComplete);
this.updateDRMState(DRMState.AUTHENTICATION_ERROR,new MediaError(event.errorID,event.toString()));
}
private function toggleErrorListeners(updater:SystemUpdater, on:Boolean) : void
{
if(on)
{
updater.addEventListener(Event.COMPLETE,this.onUpdateComplete);
updater.addEventListener(Event.CANCEL,this.onUpdateComplete);
updater.addEventListener(IOErrorEvent.IO_ERROR,this.onUpdateError);
updater.addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.onUpdateError);
updater.addEventListener(StatusEvent.STATUS,this.onUpdateError);
}
else
{
updater.removeEventListener(Event.COMPLETE,this.onUpdateComplete);
updater.removeEventListener(Event.CANCEL,this.onUpdateComplete);
updater.removeEventListener(IOErrorEvent.IO_ERROR,this.onUpdateError);
updater.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,this.onUpdateError);
updater.removeEventListener(StatusEvent.STATUS,this.onUpdateError);
}
}
private function onUpdateComplete(event:Event) : void
{
this.toggleErrorListeners(updater,false);
}
private function onUpdateError(event:Event) : void
{
this.toggleErrorListeners(updater,false);
this.updateDRMState(DRMState.AUTHENTICATION_ERROR,new MediaError(MediaErrorCodes.DRM_SYSTEM_UPDATE_ERROR,event.toString()));
}
private function updateDRMState(newState:String, error:MediaError = null, start:Date = null, end:Date = null, period:Number = 0, token:Object = null, prompt:String = null) : void
{
this._drmState = newState;
dispatchEvent(new DRMEvent(DRMEvent.DRM_STATE_CHANGE,newState,false,false,start,end,period,prompt,token,error));
}
}
}
@@ -0,0 +1,69 @@
package org.osmf.net.drm
{
import flash.events.DRMStatusEvent;
import flash.system.SystemUpdater;
import org.osmf.events.DRMEvent;
import org.osmf.events.MediaError;
import org.osmf.traits.DRMTrait;
[ExcludeClass]
public class NetStreamDRMTrait extends DRMTrait
{
private var drmServices:DRMServices = new DRMServices();
public function NetStreamDRMTrait()
{
super();
this.drmServices.addEventListener(DRMEvent.DRM_STATE_CHANGE,this.onStateChange);
}
public function set drmMetadata(value:Object) : void
{
if(value != this.drmServices.drmMetadata)
{
this.drmServices.drmMetadata = value;
}
}
public function get drmMetadata() : Object
{
return this.drmServices.drmMetadata;
}
public function update(type:String) : SystemUpdater
{
return this.drmServices.update(type);
}
override public function authenticate(username:String = null, password:String = null) : void
{
this.drmServices.authenticate(username,password);
}
override public function authenticateWithToken(token:Object) : void
{
this.drmServices.authenticateWithToken(token);
}
public function inlineDRMFailed(error:MediaError) : void
{
this.drmServices.inlineDRMFailed(error);
}
public function inlineOnVoucher(event:DRMStatusEvent) : void
{
this.drmServices.inlineOnVoucher(event);
}
private function onStateChange(event:DRMEvent) : void
{
setPeriod(event.period);
setStartDate(event.startDate);
setEndDate(event.endDate);
setDrmState(event.drmState);
dispatchEvent(new DRMEvent(DRMEvent.DRM_STATE_CHANGE,drmState,false,false,startDate,endDate,period,event.serverURL,event.token,event.mediaError));
}
}
}
@@ -0,0 +1,33 @@
package org.osmf.net.dvr
{
[ExcludeClass]
public class DVRCastConstants
{
public static const RPC_GET_STREAM_INFO:String = "DVRGetStreamInfo";
public static const RPC_SUBSCRIBE:String = "DVRSubscribe";
public static const RPC_UNSUBSCRIBE:String = "DVRUnsubscribe";
public static const RESULT_GET_STREAM_INFO_SUCCESS:String = "NetStream.DVRStreamInfo.Success";
public static const RESULT_GET_STREAM_INFO_RETRY:String = "NetStream.DVRStreamInfo.Retry";
public static const STREAM_INFO_KEY:String = "http://www.osmf.org/dvrCast/1.0/streamInfo";
public static const RECORDING_INFO_KEY:String = "http://www.osmf.org/dvrCast/1.0/recordingInfo";
public static const STREAM_INFO_UPDATE_DELAY:Number = 3000;
public static const LOCAL_DURATION_UPDATE_INTERVAL:Number = 500;
public static const LIVE_POSITION_SEEK_DELAY:Number = 1.5;
public function DVRCastConstants()
{
super();
}
}
}
@@ -0,0 +1,86 @@
package org.osmf.net.dvr
{
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Timer;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.events.MediaErrorEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.traits.DVRTrait;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
internal class DVRCastDVRTrait extends DVRTrait
{
private var connection:NetConnection;
private var stream:NetStream;
private var streamInfo:DVRCastStreamInfo;
private var recordingInfo:DVRCastRecordingInfo;
private var streamInfoUpdateTimer:Timer;
private var streamInfoRetriever:DVRCastStreamInfoRetriever;
private var offset:Number;
public function DVRCastDVRTrait(connection:NetConnection, stream:NetStream, resource:MediaResourceBase)
{
if(connection != null && stream != null)
{
this.stream = stream;
this.streamInfo = resource.getMetadataValue(DVRCastConstants.STREAM_INFO_KEY) as DVRCastStreamInfo;
this.recordingInfo = resource.getMetadataValue(DVRCastConstants.RECORDING_INFO_KEY) as DVRCastRecordingInfo;
this.streamInfoRetriever = new DVRCastStreamInfoRetriever(connection,this.streamInfo.streamName);
this.streamInfoRetriever.addEventListener(Event.COMPLETE,this.onStreamInfoRetrieverComplete);
this.streamInfoUpdateTimer = new Timer(DVRCastConstants.STREAM_INFO_UPDATE_DELAY);
this.streamInfoUpdateTimer.addEventListener(TimerEvent.TIMER,this.onStreamInfoUpdateTimer);
this.streamInfoUpdateTimer.start();
super(this.streamInfo.isRecording);
this.updateProperties();
return;
}
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.NULL_PARAM));
}
override protected function isRecordingChangeStart(value:Boolean) : void
{
if(value)
{
this.recordingInfo.startDuration = this.streamInfo.currentLength;
this.recordingInfo.startTime = new Date();
}
}
private function updateProperties() : void
{
setIsRecording(this.streamInfo.isRecording);
}
private function onStreamInfoUpdateTimer(event:TimerEvent) : void
{
this.streamInfoRetriever.retrieve();
}
private function onStreamInfoRetrieverComplete(event:Event) : void
{
if(this.streamInfoRetriever.streamInfo != null)
{
this.streamInfo.readFromDVRCastStreamInfo(this.streamInfoRetriever.streamInfo);
this.updateProperties();
}
else
{
dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR,false,false,new MediaError(MediaErrorCodes.DVRCAST_STREAM_INFO_RETRIEVAL_FAILED)));
}
}
}
}
@@ -0,0 +1,153 @@
package org.osmf.net.dvr
{
import flash.events.Event;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.utils.Dictionary;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorCodes;
import org.osmf.events.NetConnectionFactoryEvent;
import org.osmf.media.URLResource;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.NetConnectionFactory;
import org.osmf.net.NetConnectionFactoryBase;
import org.osmf.net.NetStreamUtils;
import org.osmf.net.StreamingURLResource;
[ExcludeClass]
public class DVRCastNetConnectionFactory extends NetConnectionFactoryBase
{
private var innerFactory:NetConnectionFactoryBase;
private var subscribedStreams:Dictionary = new Dictionary();
public function DVRCastNetConnectionFactory(factory:NetConnectionFactoryBase = null)
{
this.innerFactory = factory || new NetConnectionFactory();
this.innerFactory.addEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,this.onCreationComplete);
this.innerFactory.addEventListener(NetConnectionFactoryEvent.CREATION_ERROR,this.onCreationError);
super();
}
override public function create(resource:URLResource) : void
{
this.innerFactory.create(resource);
}
override public function closeNetConnection(netConnection:NetConnection) : void
{
var streamName:String = this.subscribedStreams[netConnection];
if(streamName != null)
{
netConnection.call(DVRCastConstants.RPC_UNSUBSCRIBE,null,streamName);
delete this.subscribedStreams[netConnection];
}
this.innerFactory.closeNetConnection(netConnection);
}
private function onCreationComplete(event:NetConnectionFactoryEvent) : void
{
var urlIncludesFMSApplicationInstance:Boolean;
var dynamicResource:DynamicStreamingResource;
var responder:Responder;
var urlResource:URLResource = null;
var netConnection:NetConnection = null;
var streamNames:Vector.<String> = null;
var totalRpcSubscribeInvocation:int = 0;
var streamingResource:StreamingURLResource = null;
var onStreamSubscriptionResult:Function = null;
var onStreamInfoRetrieverComplete:Function = null;
var onServerCallError:Function = null;
var items:Vector.<DynamicStreamingItem> = null;
var i:int = 0;
onStreamSubscriptionResult = function(result:Object):void
{
var streamInfoRetriever:DVRCastStreamInfoRetriever = null;
--totalRpcSubscribeInvocation;
if(totalRpcSubscribeInvocation <= 0)
{
streamInfoRetriever = new DVRCastStreamInfoRetriever(netConnection,streamNames[0]);
streamInfoRetriever.addEventListener(Event.COMPLETE,onStreamInfoRetrieverComplete);
streamInfoRetriever.retrieve();
}
};
onStreamInfoRetrieverComplete = function(event:Event):void
{
var recordingInfo:DVRCastRecordingInfo = null;
var streamInfoRetriever:DVRCastStreamInfoRetriever = event.target as DVRCastStreamInfoRetriever;
removeEventListener(NetConnectionFactoryEvent.CREATION_COMPLETE,onCreationComplete);
if(streamInfoRetriever.streamInfo != null)
{
if(streamInfoRetriever.streamInfo.offline == true)
{
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_ERROR,false,false,netConnection,urlResource,new MediaError(MediaErrorCodes.DVRCAST_CONTENT_OFFLINE)));
for(i = 0; i < streamNames.length; ++i)
{
netConnection.call(DVRCastConstants.RPC_UNSUBSCRIBE,null,streamNames[i]);
}
netConnection = null;
}
else
{
recordingInfo = new DVRCastRecordingInfo();
recordingInfo.startDuration = streamInfoRetriever.streamInfo.currentLength;
recordingInfo.startOffset = calculateOffset(streamInfoRetriever.streamInfo);
recordingInfo.startTime = new Date();
streamingResource.addMetadataValue(DVRCastConstants.STREAM_INFO_KEY,streamInfoRetriever.streamInfo);
streamingResource.addMetadataValue(DVRCastConstants.RECORDING_INFO_KEY,recordingInfo);
subscribedStreams[netConnection] = streamNames[0];
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_COMPLETE,false,false,netConnection,urlResource));
}
}
else
{
onServerCallError(streamInfoRetriever.error);
}
};
onServerCallError = function(error:Object):void
{
dispatchEvent(new NetConnectionFactoryEvent(NetConnectionFactoryEvent.CREATION_ERROR,false,false,netConnection,urlResource,new MediaError(MediaErrorCodes.DVRCAST_SUBSCRIBE_FAILED,Boolean(error) ? error.message : "")));
};
urlResource = event.resource as URLResource;
netConnection = event.netConnection;
streamNames = new Vector.<String>();
totalRpcSubscribeInvocation = 0;
event.stopImmediatePropagation();
streamingResource = urlResource as StreamingURLResource;
urlIncludesFMSApplicationInstance = Boolean(streamingResource) ? streamingResource.urlIncludesFMSApplicationInstance : false;
dynamicResource = streamingResource as DynamicStreamingResource;
if(dynamicResource != null)
{
items = dynamicResource.streamItems;
totalRpcSubscribeInvocation = int(items.length);
for(i = 0; i < items.length; i++)
{
streamNames.push(items[i].streamName);
}
}
else
{
totalRpcSubscribeInvocation = 1;
streamNames.push(NetStreamUtils.getStreamNameFromURL(urlResource.url,urlIncludesFMSApplicationInstance));
}
responder = new TestableResponder(onStreamSubscriptionResult,onServerCallError);
for(i = 0; i < streamNames.length; i++)
{
event.netConnection.call(DVRCastConstants.RPC_SUBSCRIBE,responder,streamNames[i]);
}
}
private function onCreationError(event:NetConnectionFactoryEvent) : void
{
dispatchEvent(event.clone());
}
private function calculateOffset(streamInfo:DVRCastStreamInfo) : Number
{
return DVRUtils.calculateOffset(streamInfo.beginOffset,streamInfo.endOffset,streamInfo.currentLength);
}
}
}
@@ -0,0 +1,54 @@
package org.osmf.net.dvr
{
import flash.net.NetConnection;
import flash.net.NetStream;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.net.NetStreamUtils;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingURLResource;
import org.osmf.net.rtmpstreaming.RTMPDynamicStreamingNetLoader;
import org.osmf.traits.LoadState;
public class DVRCastNetLoader extends RTMPDynamicStreamingNetLoader
{
public function DVRCastNetLoader(factory:DVRCastNetConnectionFactory = null)
{
if(factory == null)
{
factory = new DVRCastNetConnectionFactory();
}
super(factory);
}
override public function canHandleResource(resource:MediaResourceBase) : Boolean
{
var result:Boolean = false;
var streamingURLResource:StreamingURLResource = null;
if(super.canHandleResource(resource))
{
streamingURLResource = resource as StreamingURLResource;
if(streamingURLResource != null)
{
result = streamingURLResource.streamType == StreamType.DVR && NetStreamUtils.isRTMPStream(streamingURLResource.url);
}
}
return result;
}
override protected function createNetStream(connection:NetConnection, resource:URLResource) : NetStream
{
return new DVRCastNetStream(connection,resource);
}
override protected function processFinishLoading(loadTrait:NetStreamLoadTrait) : void
{
loadTrait.setTrait(new DVRCastDVRTrait(loadTrait.connection,loadTrait.netStream,loadTrait.resource));
loadTrait.setTrait(new DVRCastTimeTrait(loadTrait.connection,loadTrait.netStream,loadTrait.resource));
updateLoadTrait(loadTrait,LoadState.READY);
}
}
}
@@ -0,0 +1,36 @@
package org.osmf.net.dvr
{
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import org.osmf.media.MediaResourceBase;
[ExcludeClass]
public class DVRCastNetStream extends NetStream
{
private var recordingInfo:DVRCastRecordingInfo;
public function DVRCastNetStream(connection:NetConnection, resource:MediaResourceBase)
{
super(connection);
this.recordingInfo = resource.getMetadataValue(DVRCastConstants.RECORDING_INFO_KEY) as DVRCastRecordingInfo;
}
override public function play(... arguments) : void
{
super.play(arguments[0],this.recordingInfo.startOffset,-1);
}
override public function play2(param:NetStreamPlayOptions) : void
{
if(Boolean(param))
{
param.start = this.recordingInfo.startOffset;
param.len = -1;
}
super.play2(param);
}
}
}
@@ -0,0 +1,19 @@
package org.osmf.net.dvr
{
[ExcludeClass]
public class DVRCastRecordingInfo
{
public var startTime:Date = null;
public var startDuration:Number;
public var startOffset:Number;
public function DVRCastRecordingInfo()
{
super();
}
}
}
@@ -0,0 +1,88 @@
package org.osmf.net.dvr
{
import flash.errors.IllegalOperationError;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
public class DVRCastStreamInfo
{
public var callTime:Date;
public var offline:Boolean;
public var beginOffset:Number;
public var endOffset:Number;
public var recordingStart:Date;
public var recordingEnd:Date;
public var isRecording:Boolean;
public var streamName:String;
public var lastUpdate:Date;
public var currentLength:Number;
public var maxLength:Number;
public function DVRCastStreamInfo(value:Object)
{
super();
this.readFromDynamicObject(value);
}
public function readFromDynamicObject(value:Object) : void
{
try
{
this.callTime = value.callTime;
this.offline = value.offline;
this.beginOffset = value.begOffset;
this.endOffset = value.endOffset;
this.recordingStart = value.startRec;
this.recordingEnd = value.stopRec;
this.isRecording = value.isRec;
this.streamName = value.streamName;
this.lastUpdate = value.lastUpdate;
this.currentLength = value.currLen;
this.maxLength = value.maxLen;
}
catch(e:Error)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.INVALID_PARAM));
}
}
public function readFromDVRCastStreamInfo(value:DVRCastStreamInfo) : void
{
try
{
this.callTime = value.callTime;
this.offline = value.offline;
this.beginOffset = value.beginOffset;
this.endOffset = value.endOffset;
this.recordingStart = value.recordingStart;
this.recordingEnd = value.recordingEnd;
this.isRecording = value.isRecording;
this.streamName = value.streamName;
this.lastUpdate = value.lastUpdate;
this.currentLength = value.currentLength;
this.maxLength = value.maxLength;
}
catch(e:Error)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.INVALID_PARAM));
}
}
public function toString() : String
{
return "callTime: " + this.callTime + "\noffline: " + this.offline + "\nbeginOffset: " + this.beginOffset + "\nendOffset: " + this.endOffset + "\nrecordingStart: " + this.recordingStart + "\nrecordingEnd: " + this.recordingEnd + "\nisRecording: " + this.isRecording + "\nstreamName: " + this.streamName + "\nlastUpdate: " + this.lastUpdate + "\ncurrentLength: " + this.currentLength + "\nmaxLength: " + this.maxLength;
}
}
}
@@ -0,0 +1,117 @@
package org.osmf.net.dvr
{
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.utils.Timer;
import org.osmf.utils.OSMFStrings;
[Event(name="complete",type="flash.events.Event")]
[ExcludeClass]
internal class DVRCastStreamInfoRetriever extends EventDispatcher
{
private var connection:NetConnection;
private var streamName:String;
private var retries:Number;
private var timer:Timer;
private var _streamInfo:DVRCastStreamInfo;
private var _error:Object;
public function DVRCastStreamInfoRetriever(connection:NetConnection, streamName:String)
{
super();
if(connection == null || streamName == null)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.NULL_PARAM));
}
this.connection = connection;
this.streamName = streamName;
}
public function get streamInfo() : DVRCastStreamInfo
{
return this._streamInfo;
}
public function get error() : Object
{
return this._error;
}
public function retrieve(retries:int = 5, timeOut:Number = 3) : void
{
if(isNaN(this.retries))
{
retries ||= 1;
this._streamInfo = null;
this._error = this._error = {"message":OSMFStrings.getString(OSMFStrings.DVR_MAXIMUM_RPC_ATTEMPTS).replace("%i",retries)};
this.retries = retries;
this.timer = new Timer(timeOut * 1000,1);
this.getStreamInfo();
}
}
private function getStreamInfo() : void
{
var responder:Responder = new TestableResponder(this.onGetStreamInfoResult,this.onServerCallError);
--this.retries;
this.connection.call(DVRCastConstants.RPC_GET_STREAM_INFO,responder,this.streamName);
}
private function onGetStreamInfoResult(result:Object) : void
{
if(Boolean(result) && result.code == DVRCastConstants.RESULT_GET_STREAM_INFO_SUCCESS)
{
this._error = null;
this._streamInfo = new DVRCastStreamInfo(result.data);
this.complete();
}
else if(Boolean(result) && result.code == DVRCastConstants.RESULT_GET_STREAM_INFO_RETRY)
{
if(this.retries != 0)
{
this.timer.addEventListener(TimerEvent.TIMER_COMPLETE,this.onTimerComplete);
this.timer.start();
}
else
{
this.complete();
}
}
else
{
this._error = {"message":OSMFStrings.getString(OSMFStrings.DVR_UNEXPECTED_SERVER_RESPONSE) + result.code};
this.complete();
}
}
private function onServerCallError(error:Object) : void
{
this._error = error;
this.complete();
}
private function onTimerComplete(event:TimerEvent) : void
{
this.timer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.onTimerComplete);
this.getStreamInfo();
}
private function complete() : void
{
this.retries = NaN;
this.timer = null;
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
@@ -0,0 +1,86 @@
package org.osmf.net.dvr
{
import flash.errors.IllegalOperationError;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Timer;
import org.osmf.events.TimeEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.traits.TimeTrait;
import org.osmf.utils.OSMFStrings;
[ExcludeClass]
internal class DVRCastTimeTrait extends TimeTrait
{
private var durationUpdateTimer:Timer;
private var oldDuration:Number;
private var stream:NetStream;
private var streamInfo:DVRCastStreamInfo;
private var recordingInfo:DVRCastRecordingInfo;
public function DVRCastTimeTrait(connection:NetConnection, stream:NetStream, resource:MediaResourceBase)
{
super(NaN);
if(connection == null || stream == null)
{
throw new IllegalOperationError(OSMFStrings.getString(OSMFStrings.NULL_PARAM));
}
this.stream = stream;
stream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
this.durationUpdateTimer = new Timer(DVRCastConstants.LOCAL_DURATION_UPDATE_INTERVAL);
this.durationUpdateTimer.addEventListener(TimerEvent.TIMER,this.onDurationUpdateTimer);
this.durationUpdateTimer.start();
this.streamInfo = resource.getMetadataValue(DVRCastConstants.STREAM_INFO_KEY) as DVRCastStreamInfo;
this.recordingInfo = resource.getMetadataValue(DVRCastConstants.RECORDING_INFO_KEY) as DVRCastRecordingInfo;
}
override public function get duration() : Number
{
var result:Number = NaN;
if(this.streamInfo.isRecording)
{
result = this.recordingInfo.startDuration - this.recordingInfo.startOffset + (new Date().time - this.recordingInfo.startTime.time) / 1000;
}
else
{
result = this.streamInfo.currentLength - this.recordingInfo.startOffset;
}
return isNaN(result) ? NaN : Math.max(0,result);
}
override public function get currentTime() : Number
{
return this.stream.time;
}
private function onDurationUpdateTimer(event:TimerEvent) : void
{
var newDuration:Number = this.duration;
if(newDuration != this.oldDuration)
{
this.oldDuration = newDuration;
dispatchEvent(new TimeEvent(TimeEvent.DURATION_CHANGE,false,false,newDuration));
}
}
private function onNetStatus(event:NetStatusEvent) : void
{
if(event.info.code == "NetStream.Play.Stop")
{
if(Boolean(this.durationUpdateTimer))
{
this.durationUpdateTimer.stop();
}
signalComplete();
}
}
}
}
@@ -0,0 +1,34 @@
package org.osmf.net.dvr
{
[ExcludeClass]
public class DVRUtils
{
public function DVRUtils()
{
super();
}
public static function calculateOffset(beginOffset:Number, endOffset:Number, currentDuration:Number) : Number
{
var offset:Number = 0;
if(endOffset != 0)
{
if(currentDuration > endOffset)
{
offset = currentDuration - endOffset;
}
else
{
offset = Math.min(beginOffset,currentDuration);
}
}
else if(beginOffset != 0)
{
offset = Math.min(beginOffset,currentDuration);
}
return offset;
}
}
}
@@ -0,0 +1,31 @@
package org.osmf.net.dvr
{
import flash.net.Responder;
[ExcludeClass]
internal class TestableResponder extends Responder
{
private var _result:Function;
private var _status:Function;
public function TestableResponder(result:Function, status:Function = null)
{
this._result = result;
this._status = status;
super(result,status);
}
internal function get result() : Function
{
return this._result;
}
internal function get status() : Function
{
return this._status;
}
}
}
@@ -0,0 +1,73 @@
package org.osmf.net.httpstreaming
{
import org.osmf.net.SwitchingRuleBase;
[ExcludeClass]
public class DownloadRatioRule extends SwitchingRuleBase
{
private var aggressiveUpswitch:Boolean = false;
public function DownloadRatioRule(metrics:HTTPNetStreamMetrics, aggressiveUpswitch:Boolean = true)
{
super(metrics);
this.aggressiveUpswitch = aggressiveUpswitch;
}
override public function getNewIndex() : int
{
var switchRatio:Number = NaN;
var proposedIndex:int = -1;
if(this.httpMetrics.downloadRatio < 1)
{
if(this.httpMetrics.currentIndex > 0)
{
switchRatio = this.getSwitchRatio(this.httpMetrics.currentIndex - 1);
if(this.httpMetrics.downloadRatio < switchRatio)
{
proposedIndex = 0;
}
else
{
proposedIndex = this.httpMetrics.currentIndex - 1;
}
}
}
else if(this.httpMetrics.currentIndex < this.httpMetrics.maxAllowedIndex)
{
switchRatio = this.getSwitchRatio(this.httpMetrics.currentIndex + 1);
if(this.httpMetrics.downloadRatio >= switchRatio)
{
if(this.httpMetrics.downloadRatio > 100 || !this.aggressiveUpswitch)
{
proposedIndex = this.httpMetrics.currentIndex + 1;
}
else
{
while(++proposedIndex < this.httpMetrics.maxAllowedIndex + 1)
{
switchRatio = this.getSwitchRatio(proposedIndex);
if(this.httpMetrics.downloadRatio < switchRatio)
{
break;
}
}
proposedIndex--;
}
}
}
return proposedIndex;
}
private function getSwitchRatio(index:int) : Number
{
return this.httpMetrics.getBitrateForIndex(index) / this.httpMetrics.getBitrateForIndex(metrics.currentIndex);
}
private function get httpMetrics() : HTTPNetStreamMetrics
{
return metrics as HTTPNetStreamMetrics;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,28 @@
package org.osmf.net.httpstreaming
{
import org.osmf.net.NetStreamMetricsBase;
[ExcludeClass]
public class HTTPNetStreamMetrics extends NetStreamMetricsBase
{
private var httpNetStream:HTTPNetStream;
public function HTTPNetStreamMetrics(netStream:HTTPNetStream)
{
super(netStream);
this.httpNetStream = netStream;
}
public function get downloadRatio() : Number
{
return this.httpNetStream.downloadRatio;
}
public function getBitrateForIndex(index:int) : Number
{
return this.resource.streamItems[index].bitrate;
}
}
}
@@ -0,0 +1,52 @@
package org.osmf.net.httpstreaming
{
import flash.net.URLRequest;
[ExcludeClass]
public class HTTPStreamRequest
{
private var _urlRequest:URLRequest;
private var _quality:int;
private var _truncateAt:Number;
private var _retryAfter:Number;
private var _unpublishNotify:Boolean;
public function HTTPStreamRequest(url:String = null, quality:int = -1, truncateAt:Number = -1, retryAfter:Number = -1, unpublishNotify:Boolean = false)
{
super();
if(Boolean(url))
{
this._urlRequest = new URLRequest(HTTPStreamingUtils.normalizeURL(url));
}
else
{
this._urlRequest = null;
}
this._quality = quality;
this._truncateAt = truncateAt;
this._retryAfter = retryAfter;
this._unpublishNotify = unpublishNotify;
}
public function get urlRequest() : URLRequest
{
return this._urlRequest;
}
public function get retryAfter() : Number
{
return this._retryAfter;
}
public function get unpublishNotify() : Boolean
{
return this._unpublishNotify;
}
}
}
@@ -0,0 +1,45 @@
package org.osmf.net.httpstreaming
{
import flash.errors.IllegalOperationError;
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
[ExcludeClass]
[Event(name="notifyTimeBias",type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
[Event(name="notifySegmentDuration",type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
public class HTTPStreamingFileHandlerBase extends EventDispatcher
{
public function HTTPStreamingFileHandlerBase()
{
super();
}
public function beginProcessFile(seek:Boolean, seekTime:Number) : void
{
throw new IllegalOperationError("The beginProcessFile() method must be overridden by HttpStreamingFileHandlerBase\'s derived class.");
}
public function get inputBytesNeeded() : Number
{
throw new IllegalOperationError("The inputBytesNeeded() method must be overridden by HttpStreamingFileHandlerBase\'s derived class.");
}
public function processFileSegment(input:IDataInput) : ByteArray
{
throw new IllegalOperationError("The processFileSegment() method must be overridden by HttpStreamingFileHandlerBase\'s derived class.");
}
public function endProcessFile(input:IDataInput) : ByteArray
{
throw new IllegalOperationError("The endProcessFile() method must be overridden by HttpStreamingFileHandlerBase\'s derived class.");
}
public function flushFileSegment(input:IDataInput) : ByteArray
{
throw new IllegalOperationError("The flushFileSegment() method must be overridden by HttpStreamingFileHandlerBase\'s derived class.");
}
}
}
@@ -0,0 +1,47 @@
package org.osmf.net.httpstreaming
{
import flash.errors.IllegalOperationError;
import flash.events.EventDispatcher;
[ExcludeClass]
[Event(name="DVRStreamInfo",type="org.osmf.events.DVRStreamInfoEvent")]
[Event(name="notifyError",type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="requestLoadIndex",type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyTotalDuration",type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyRates",type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
[Event(name="notifyIndexReady",type="org.osmf.events.HTTPStreamingFileIndexHandlerEvent")]
public class HTTPStreamingIndexHandlerBase extends EventDispatcher
{
public function HTTPStreamingIndexHandlerBase()
{
super();
}
public function initialize(indexInfo:Object) : void
{
throw new IllegalOperationError("The initialize() method must be overridden by the derived class.");
}
public function processIndexData(data:*, indexContext:Object) : void
{
throw new IllegalOperationError("The processIndexData() method must be overridden by the derived class.");
}
public function getFileForTime(time:Number, quality:int) : HTTPStreamRequest
{
throw new IllegalOperationError("The getFileForTime() method must be overridden by the derived class.");
}
public function getNextFile(quality:int) : HTTPStreamRequest
{
throw new IllegalOperationError("The getNextFile() method must be overridden by the derived class.");
}
public function dvrGetStreamInfo(indexInfo:Object) : void
{
throw new IllegalOperationError("The dvrGetStreamInfo() method must be overridden by the derived class.");
}
}
}
@@ -0,0 +1,13 @@
package org.osmf.net.httpstreaming
{
[ExcludeClass]
public class HTTPStreamingIndexInfoBase
{
public function HTTPStreamingIndexInfoBase()
{
super();
}
}
}
@@ -0,0 +1,95 @@
package org.osmf.net.httpstreaming
{
import flash.net.NetConnection;
import flash.net.NetStream;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.NetLoader;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.net.NetStreamSwitchManager;
import org.osmf.net.NetStreamSwitchManagerBase;
import org.osmf.net.SwitchingRuleBase;
import org.osmf.net.httpstreaming.dvr.DVRInfo;
import org.osmf.net.httpstreaming.dvr.HTTPStreamingDVRCastDVRTrait;
import org.osmf.net.httpstreaming.dvr.HTTPStreamingDVRCastTimeTrait;
import org.osmf.net.httpstreaming.f4f.HTTPStreamingF4FFileHandler;
import org.osmf.net.httpstreaming.f4f.HTTPStreamingF4FIndexHandler;
import org.osmf.net.rtmpstreaming.DroppedFramesRule;
import org.osmf.traits.LoadState;
public class HTTPStreamingNetLoader extends NetLoader
{
public function HTTPStreamingNetLoader()
{
super();
}
override public function canHandleResource(resource:MediaResourceBase) : Boolean
{
return resource.getMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA) as Metadata != null;
}
override protected function createNetStream(connection:NetConnection, resource:URLResource) : NetStream
{
var fileHandler:HTTPStreamingFileHandlerBase = new HTTPStreamingF4FFileHandler();
var indexHandler:HTTPStreamingIndexHandlerBase = new HTTPStreamingF4FIndexHandler(fileHandler);
var httpNetStream:HTTPNetStream = new HTTPNetStream(connection,indexHandler,fileHandler);
httpNetStream.manualSwitchMode = true;
httpNetStream.indexInfo = HTTPStreamingUtils.createF4FIndexInfo(resource);
return httpNetStream;
}
override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource) : NetStreamSwitchManagerBase
{
var metrics:HTTPNetStreamMetrics = null;
if(dsResource != null)
{
metrics = new HTTPNetStreamMetrics(netStream as HTTPNetStream);
return new NetStreamSwitchManager(connection,netStream,dsResource,metrics,this.getDefaultSwitchingRules(metrics));
}
return null;
}
override protected function processFinishLoading(loadTrait:NetStreamLoadTrait) : void
{
var netStream:HTTPNetStream = null;
var onDVRStreamInfo:Function = null;
onDVRStreamInfo = function(event:DVRStreamInfoEvent):void
{
netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO,onDVRStreamInfo);
loadTrait.setTrait(new HTTPStreamingDVRCastDVRTrait(loadTrait.connection,netStream,event.info as DVRInfo));
loadTrait.setTrait(new HTTPStreamingDVRCastTimeTrait(loadTrait.connection,netStream,event.info as DVRInfo));
updateLoadTrait(loadTrait,LoadState.READY);
};
var resource:URLResource = loadTrait.resource as URLResource;
if(!this.dvrMetadataPresent(resource))
{
updateLoadTrait(loadTrait,LoadState.READY);
return;
}
netStream = loadTrait.netStream as HTTPNetStream;
netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO,onDVRStreamInfo);
netStream.DVRGetStreamInfo(null);
}
private function dvrMetadataPresent(resource:URLResource) : Boolean
{
var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata;
return metadata != null;
}
private function getDefaultSwitchingRules(metrics:HTTPNetStreamMetrics) : Vector.<SwitchingRuleBase>
{
var rules:Vector.<SwitchingRuleBase> = new Vector.<SwitchingRuleBase>();
rules.push(new DownloadRatioRule(metrics));
rules.push(new DroppedFramesRule(metrics));
return rules;
}
}
}
@@ -0,0 +1,43 @@
package org.osmf.net.httpstreaming
{
[ExcludeClass]
internal class HTTPStreamingState
{
internal static const INIT:String = "init";
internal static const LOAD_SEEK:String = "loadSeek";
internal static const LOAD_SEEK_RETRY_WAIT:String = "loadSeekRetryWait";
internal static const LOAD:String = "load";
internal static const LOAD_WAIT:String = "loadWait";
internal static const LOAD_NEXT:String = "loadNext";
internal static const LOAD_NEXT_RETRY_WAIT:String = "loadNextRetryWait";
internal static const PLAY_START_SEEK:String = "playStartSeek";
internal static const PLAY_START_NEXT:String = "playStartNext";
internal static const PLAY_START_COMMON:String = "playStartCommon";
internal static const PLAY:String = "play";
internal static const END_SEGMENT:String = "endSegment";
internal static const SEEK:String = "seek";
internal static const STOP:String = "stop";
internal static const HALT:String = "halt";
public function HTTPStreamingState()
{
super();
}
}
}
@@ -0,0 +1,184 @@
package org.osmf.net.httpstreaming
{
import flash.utils.ByteArray;
import org.osmf.elements.f4mClasses.BootstrapInfo;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.httpstreaming.dvr.DVRInfo;
import org.osmf.net.httpstreaming.f4f.HTTPStreamingF4FIndexInfo;
import org.osmf.net.httpstreaming.f4f.HTTPStreamingF4FStreamInfo;
[ExcludeClass]
public class HTTPStreamingUtils
{
public function HTTPStreamingUtils()
{
super();
}
public static function createHTTPStreamingMetadata(abstUrl:String, abstData:ByteArray, serverBaseUrls:Vector.<String>) : Metadata
{
var metadata:Metadata = new Metadata();
var bootstrap:BootstrapInfo = new BootstrapInfo();
if(abstUrl != null && abstUrl.length > 0)
{
bootstrap.url = abstUrl;
}
bootstrap.data = abstData;
metadata.addValue(MetadataNamespaces.HTTP_STREAMING_BOOTSTRAP_KEY,bootstrap);
if(serverBaseUrls != null && serverBaseUrls.length > 0)
{
metadata.addValue(MetadataNamespaces.HTTP_STREAMING_SERVER_BASE_URLS_KEY,serverBaseUrls);
}
return metadata;
}
public static function createF4FIndexInfo(resource:URLResource) : HTTPStreamingF4FIndexInfo
{
var serverBaseURLs:Vector.<String> = null;
var streamInfos:Vector.<HTTPStreamingF4FStreamInfo> = null;
var dvrInfo:DVRInfo = null;
var indexInfo:HTTPStreamingF4FIndexInfo = null;
var httpMetadata:Metadata = resource.getMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA) as Metadata;
var dvrMetadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata;
if(httpMetadata != null)
{
serverBaseURLs = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_SERVER_BASE_URLS_KEY) as Vector.<String>;
streamInfos = generateStreamInfos(resource);
dvrInfo = generateDVRInfo(dvrMetadata);
indexInfo = new HTTPStreamingF4FIndexInfo(serverBaseURLs != null && serverBaseURLs.length > 0 ? serverBaseURLs[0] : null,streamInfos,dvrInfo);
}
return indexInfo;
}
public static function normalizeURL(url:String) : String
{
var temp:String = null;
var i:int = 0;
var ret:String = "";
var protocol:String = "";
if(url.indexOf("http://") == 0)
{
protocol = "http://";
}
else if(url.indexOf("https://") == 0)
{
protocol = "https://";
}
if(protocol.length > 0)
{
temp = url.substr(protocol.length);
}
else
{
temp = url;
}
var items:Array = temp.split("/");
var index:int = items.indexOf("..");
while(index >= 0)
{
items.splice(index - 1,2);
index = items.indexOf("..");
}
ret = protocol;
if(items.length > 0)
{
for(i = 0; i < items.length; i++)
{
if(i != 0)
{
ret += "/";
}
ret += items[i] as String;
}
}
return ret;
}
private static function generateDVRInfo(metadata:Metadata) : DVRInfo
{
if(metadata == null)
{
return null;
}
var dvrInfo:DVRInfo = new DVRInfo();
dvrInfo.id = "";
dvrInfo.beginOffset = NaN;
dvrInfo.endOffset = NaN;
dvrInfo.offline = false;
if(metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_ID_KEY) != null)
{
dvrInfo.id = metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_ID_KEY) as String;
}
if(metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_BEGIN_OFFSET_KEY) != null)
{
dvrInfo.beginOffset = metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_BEGIN_OFFSET_KEY) as uint;
}
if(metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_END_OFFSET_KEY) != null)
{
dvrInfo.endOffset = metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_END_OFFSET_KEY) as uint;
}
if(metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_OFFLINE_KEY) != null)
{
dvrInfo.offline = metadata.getValue(MetadataNamespaces.HTTP_STREAMING_DVR_OFFLINE_KEY) as Boolean;
}
return dvrInfo;
}
private static function generateStreamInfos(resource:URLResource) : Vector.<HTTPStreamingF4FStreamInfo>
{
var streamMetadata:Object = null;
var xmpMetadata:ByteArray = null;
var streamItem:DynamicStreamingItem = null;
var streamName:String = null;
var streamInfos:Vector.<HTTPStreamingF4FStreamInfo> = new Vector.<HTTPStreamingF4FStreamInfo>();
var drmMetadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DRM_METADATA) as Metadata;
var httpMetadata:Metadata = resource.getMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA) as Metadata;
var additionalHeader:ByteArray = null;
var bootstrap:BootstrapInfo = null;
var dsResource:DynamicStreamingResource = resource as DynamicStreamingResource;
if(dsResource != null)
{
for each(streamItem in dsResource.streamItems)
{
additionalHeader = null;
bootstrap = null;
streamMetadata = null;
xmpMetadata = null;
if(drmMetadata != null)
{
additionalHeader = drmMetadata.getValue(MetadataNamespaces.DRM_ADDITIONAL_HEADER_KEY + streamItem.streamName) as ByteArray;
}
if(httpMetadata != null)
{
bootstrap = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_BOOTSTRAP_KEY + streamItem.streamName) as BootstrapInfo;
streamMetadata = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_STREAM_METADATA_KEY + streamItem.streamName);
xmpMetadata = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_XMP_METADATA_KEY + streamItem.streamName) as ByteArray;
}
streamInfos.push(new HTTPStreamingF4FStreamInfo(bootstrap,streamItem.streamName,streamItem.bitrate,additionalHeader,streamMetadata,xmpMetadata));
}
}
else
{
if(drmMetadata != null)
{
additionalHeader = drmMetadata.getValue(MetadataNamespaces.DRM_ADDITIONAL_HEADER_KEY) as ByteArray;
}
if(httpMetadata != null)
{
bootstrap = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_BOOTSTRAP_KEY) as BootstrapInfo;
streamMetadata = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_STREAM_METADATA_KEY);
xmpMetadata = httpMetadata.getValue(MetadataNamespaces.HTTP_STREAMING_XMP_METADATA_KEY) as ByteArray;
}
streamName = resource.url;
streamInfos.push(new HTTPStreamingF4FStreamInfo(bootstrap,streamName,NaN,additionalHeader,streamMetadata,xmpMetadata));
}
return streamInfos;
}
}
}
@@ -0,0 +1,29 @@
package org.osmf.net.httpstreaming.dvr
{
[ExcludeClass]
public class DVRInfo
{
public var id:String;
public var url:String;
public var beginOffset:uint = 0;
public var endOffset:uint = 0;
public var offline:Boolean;
public var isRecording:Boolean;
public var curLength:Number;
public var startTime:Number = NaN;
public function DVRInfo()
{
super();
}
}
}
@@ -0,0 +1,34 @@
package org.osmf.net.httpstreaming.dvr
{
import flash.net.NetConnection;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.net.httpstreaming.HTTPNetStream;
import org.osmf.traits.DVRTrait;
[ExcludeClass]
public class HTTPStreamingDVRCastDVRTrait extends DVRTrait
{
private var _connection:NetConnection;
private var _stream:HTTPNetStream;
private var _dvrInfo:DVRInfo;
public function HTTPStreamingDVRCastDVRTrait(connection:NetConnection, stream:HTTPNetStream, dvrInfo:DVRInfo)
{
this._connection = connection;
this._stream = stream;
this._dvrInfo = dvrInfo;
this._stream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO,this.onDVRStreamInfo);
super(dvrInfo.isRecording);
}
private function onDVRStreamInfo(event:DVRStreamInfoEvent) : void
{
this._dvrInfo = event.info as DVRInfo;
setIsRecording(this._dvrInfo == null ? false : this._dvrInfo.isRecording);
}
}
}
@@ -0,0 +1,60 @@
package org.osmf.net.httpstreaming.dvr
{
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.net.NetStreamCodes;
import org.osmf.net.httpstreaming.HTTPNetStream;
import org.osmf.traits.TimeTrait;
[ExcludeClass]
public class HTTPStreamingDVRCastTimeTrait extends TimeTrait
{
private var _connection:NetConnection;
private var _stream:HTTPNetStream;
private var _dvrInfo:DVRInfo;
public function HTTPStreamingDVRCastTimeTrait(connection:NetConnection, stream:HTTPNetStream, dvrInfo:DVRInfo)
{
super(NaN);
this._connection = connection;
this._stream = stream;
this._dvrInfo = dvrInfo;
this._stream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO,this.onDVRStreamInfo);
this._stream.addEventListener(NetStatusEvent.NET_STATUS,this.onNetStatus);
}
override public function get duration() : Number
{
if(this._dvrInfo == null)
{
return NaN;
}
return this._dvrInfo.curLength;
}
override public function get currentTime() : Number
{
return this._stream.time;
}
private function onDVRStreamInfo(event:DVRStreamInfoEvent) : void
{
this._dvrInfo = event.info as DVRInfo;
setDuration(this._dvrInfo.curLength);
}
private function onNetStatus(event:NetStatusEvent) : void
{
switch(event.info.code)
{
case NetStreamCodes.NETSTREAM_PLAY_UNPUBLISH_NOTIFY:
signalComplete();
}
}
}
}
@@ -0,0 +1,224 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
public class AdobeBootstrapBox extends FullBox
{
private var _bootstrapVersion:uint;
private var _profile:uint;
private var _live:Boolean;
private var _update:Boolean;
private var _timeScale:uint;
private var _currentMediaTime:Number;
private var _smpteTimeCodeOffset:Number;
private var _movieIdentifier:String;
private var _serverEntryCount:uint;
private var _serverBaseURLs:Vector.<String>;
private var _qualitySegmentURLModifiers:Vector.<String>;
private var _drmData:String;
private var _metadata:String;
private var _segmentRunTables:Vector.<AdobeSegmentRunTable>;
private var _fragmentRunTables:Vector.<AdobeFragmentRunTable>;
public function AdobeBootstrapBox()
{
super();
}
public function get bootstrapVersion() : uint
{
return this._bootstrapVersion;
}
public function set bootstrapVersion(value:uint) : void
{
this._bootstrapVersion = value;
}
public function get profile() : uint
{
return this._profile;
}
public function set profile(value:uint) : void
{
this._profile = value;
}
public function get live() : Boolean
{
return this._live;
}
public function set live(value:Boolean) : void
{
this._live = value;
}
public function get update() : Boolean
{
return this._update;
}
public function set update(value:Boolean) : void
{
this._update = value;
}
public function get timeScale() : uint
{
return this._timeScale;
}
public function set timeScale(value:uint) : void
{
this._timeScale = value;
}
public function get currentMediaTime() : Number
{
return this._currentMediaTime;
}
public function set currentMediaTime(value:Number) : void
{
this._currentMediaTime = value;
}
public function get smpteTimeCodeOffset() : Number
{
return this._smpteTimeCodeOffset;
}
public function set smpteTimeCodeOffset(value:Number) : void
{
this._smpteTimeCodeOffset = value;
}
public function get movieIdentifier() : String
{
return this._movieIdentifier;
}
public function set movieIdentifier(value:String) : void
{
this._movieIdentifier = value;
}
public function get serverBaseURLs() : Vector.<String>
{
return this._serverBaseURLs;
}
public function set serverBaseURLs(value:Vector.<String>) : void
{
this._serverBaseURLs = value;
}
public function get qualitySegmentURLModifiers() : Vector.<String>
{
return this._qualitySegmentURLModifiers;
}
public function set qualitySegmentURLModifiers(value:Vector.<String>) : void
{
this._qualitySegmentURLModifiers = value;
}
public function get drmData() : String
{
return this._drmData;
}
public function set drmData(value:String) : void
{
this._drmData = value;
}
public function get metadata() : String
{
return this._metadata;
}
public function set metadata(value:String) : void
{
this._metadata = value;
}
public function get segmentRunTables() : Vector.<AdobeSegmentRunTable>
{
return this._segmentRunTables;
}
public function set segmentRunTables(value:Vector.<AdobeSegmentRunTable>) : void
{
this._segmentRunTables = value;
}
public function get fragmentRunTables() : Vector.<AdobeFragmentRunTable>
{
return this._fragmentRunTables;
}
public function set fragmentRunTables(value:Vector.<AdobeFragmentRunTable>) : void
{
var frt:AdobeFragmentRunTable = null;
this._fragmentRunTables = value;
if(value != null && value.length > 0)
{
frt = value[value.length - 1];
frt.adjustEndEntryDurationAccrued(this._currentMediaTime);
}
}
public function findSegmentId(fragmentId:uint) : uint
{
return this._segmentRunTables[0].findSegmentIdByFragmentId(fragmentId);
}
public function get totalFragments() : uint
{
var afrt:AdobeFragmentRunTable = this._fragmentRunTables[this._fragmentRunTables.length - 1];
var fdps:Vector.<FragmentDurationPair> = afrt.fragmentDurationPairs;
var lastValidFdp:FragmentDurationPair = fdps[fdps.length - 1];
if(lastValidFdp.duration == 0)
{
lastValidFdp = fdps[fdps.length - 2];
}
var deltaTime:Number = this._currentMediaTime - lastValidFdp.durationAccrued;
var fragCount:uint = deltaTime <= 0 ? 0 : uint(deltaTime / lastValidFdp.duration);
return lastValidFdp.firstFragment + fragCount - 1;
}
public function get totalDuration() : uint
{
if(this._fragmentRunTables == null || this._fragmentRunTables.length < 1)
{
return 0;
}
var frt:AdobeFragmentRunTable = this._fragmentRunTables[0];
return this._currentMediaTime - frt.fragmentDurationPairs[0].durationAccrued;
}
public function contentComplete() : Boolean
{
var frt:AdobeFragmentRunTable = this._fragmentRunTables[this._fragmentRunTables.length - 1];
return frt.tableComplete();
}
}
}
@@ -0,0 +1,65 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class AdobeFragmentRandomAccessBox extends FullBox
{
private var _timeScale:uint;
private var _localRandomAccessEntries:Vector.<LocalRandomAccessEntry>;
private var _globalRandomAccessEntries:Vector.<GlobalRandomAccessEntry>;
public function AdobeFragmentRandomAccessBox()
{
super();
}
public function get timeScale() : uint
{
return this._timeScale;
}
public function set timeScale(value:uint) : void
{
this._timeScale = value;
}
public function get localRandomAccessEntries() : Vector.<LocalRandomAccessEntry>
{
return this._localRandomAccessEntries;
}
public function set localRandomAccessEntries(value:Vector.<LocalRandomAccessEntry>) : void
{
this._localRandomAccessEntries = value;
}
public function get globalRandomAccessEntries() : Vector.<GlobalRandomAccessEntry>
{
return this._globalRandomAccessEntries;
}
public function set globalRandomAccessEntries(value:Vector.<GlobalRandomAccessEntry>) : void
{
this._globalRandomAccessEntries = value;
}
public function findNearestKeyFrameOffset(seekToTime:Number) : LocalRandomAccessEntry
{
var entry:LocalRandomAccessEntry = null;
var i:int = this._localRandomAccessEntries.length - 1;
while(i >= 0)
{
entry = this._localRandomAccessEntries[i];
if(entry.time <= seekToTime)
{
return entry;
}
i--;
}
return null;
}
}
}
@@ -0,0 +1,237 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class AdobeFragmentRunTable extends FullBox
{
private var _timeScale:uint;
private var _qualitySegmentURLModifiers:Vector.<String>;
private var _fragmentDurationPairs:Vector.<FragmentDurationPair>;
public function AdobeFragmentRunTable()
{
super();
this._fragmentDurationPairs = new Vector.<FragmentDurationPair>();
}
public function get timeScale() : uint
{
return this._timeScale;
}
public function set timeScale(value:uint) : void
{
this._timeScale = value;
}
public function get qualitySegmentURLModifiers() : Vector.<String>
{
return this._qualitySegmentURLModifiers;
}
public function set qualitySegmentURLModifiers(value:Vector.<String>) : void
{
this._qualitySegmentURLModifiers = value;
}
public function get fragmentDurationPairs() : Vector.<FragmentDurationPair>
{
return this._fragmentDurationPairs;
}
public function addFragmentDurationPair(fdp:FragmentDurationPair) : void
{
this._fragmentDurationPairs.push(fdp);
}
public function findFragmentIdByTime(time:Number, totalDuration:Number, live:Boolean = false) : FragmentAccessInformation
{
if(this._fragmentDurationPairs.length <= 0)
{
return null;
}
var fdp:FragmentDurationPair = null;
for(var i:uint = 1; i < this._fragmentDurationPairs.length; i++)
{
fdp = this._fragmentDurationPairs[i];
if(fdp.durationAccrued >= time)
{
return this.validateFragment(this.calculateFragmentId(this._fragmentDurationPairs[i - 1],time),totalDuration,live);
}
}
return this.validateFragment(this.calculateFragmentId(this._fragmentDurationPairs[this._fragmentDurationPairs.length - 1],time),totalDuration,live);
}
public function validateFragment(fragId:uint, totalDuration:Number, live:Boolean = false) : FragmentAccessInformation
{
var curFdp:FragmentDurationPair = null;
var nextFdp:FragmentDurationPair = null;
var timeResidue:Number = NaN;
var timeDistance:Number = NaN;
var fragStartTime:Number = NaN;
var lastFdp:FragmentDurationPair = null;
var size:uint = this._fragmentDurationPairs.length - 1;
var fai:FragmentAccessInformation = null;
for(var i:uint = 0; i < size; i++)
{
curFdp = this._fragmentDurationPairs[i];
nextFdp = this._fragmentDurationPairs[i + 1];
if(curFdp.firstFragment <= fragId && fragId < nextFdp.firstFragment)
{
if(curFdp.duration <= 0)
{
fai = this.getNextValidFragment(i + 1,totalDuration);
}
else
{
fai = new FragmentAccessInformation();
fai.fragId = fragId;
fai.fragDuration = curFdp.duration;
fai.fragmentEndTime = curFdp.durationAccrued + curFdp.duration * (fragId - curFdp.firstFragment + 1);
}
break;
}
if(curFdp.firstFragment <= fragId && this.endOfStreamEntry(nextFdp))
{
if(curFdp.duration > 0)
{
timeResidue = totalDuration - curFdp.durationAccrued;
timeDistance = (fragId - curFdp.firstFragment + 1) * curFdp.duration;
fragStartTime = (fragId - curFdp.firstFragment) * curFdp.duration;
if(timeResidue > fragStartTime)
{
if(!live || fragStartTime + curFdp.duration + curFdp.durationAccrued <= totalDuration)
{
fai = new FragmentAccessInformation();
fai.fragId = fragId;
fai.fragDuration = curFdp.duration;
if(timeResidue >= timeDistance)
{
fai.fragmentEndTime = curFdp.durationAccrued + timeDistance;
}
else
{
fai.fragmentEndTime = curFdp.durationAccrued + timeResidue;
}
break;
}
}
}
}
}
if(fai == null)
{
lastFdp = this._fragmentDurationPairs[size];
if(lastFdp.duration > 0 && fragId >= lastFdp.firstFragment)
{
timeResidue = totalDuration - lastFdp.durationAccrued;
timeDistance = (fragId - lastFdp.firstFragment + 1) * lastFdp.duration;
fragStartTime = (fragId - lastFdp.firstFragment) * lastFdp.duration;
if(timeResidue > fragStartTime)
{
if(!live || fragStartTime + lastFdp.duration + lastFdp.durationAccrued <= totalDuration)
{
fai = new FragmentAccessInformation();
fai.fragId = fragId;
fai.fragDuration = lastFdp.duration;
if(timeResidue >= timeDistance)
{
fai.fragmentEndTime = lastFdp.durationAccrued + timeDistance;
}
else
{
fai.fragmentEndTime = lastFdp.durationAccrued + timeResidue;
}
}
}
}
}
return fai;
}
private function getNextValidFragment(startIdx:uint, totalDuration:Number) : FragmentAccessInformation
{
var fdp:FragmentDurationPair = null;
var fai:FragmentAccessInformation = null;
for(var i:uint = startIdx; i < this._fragmentDurationPairs.length; i++)
{
fdp = this._fragmentDurationPairs[i];
if(fdp.duration > 0)
{
fai = new FragmentAccessInformation();
fai.fragId = fdp.firstFragment;
fai.fragDuration = fdp.duration;
fai.fragmentEndTime = fdp.durationAccrued + fdp.duration;
break;
}
}
return fai;
}
private function endOfStreamEntry(fdp:FragmentDurationPair) : Boolean
{
return fdp.duration == 0 && fdp.discontinuityIndicator == 0;
}
public function fragmentsLeft(fragId:uint, currentMediaTime:Number) : uint
{
if(this._fragmentDurationPairs == null || this._fragmentDurationPairs.length == 0)
{
return 0;
}
var fdp:FragmentDurationPair = this._fragmentDurationPairs[this.fragmentDurationPairs.length - 1] as FragmentDurationPair;
return uint((currentMediaTime - fdp.durationAccrued) / fdp.duration + fdp.firstFragment - fragId - 1);
}
public function tableComplete() : Boolean
{
if(this._fragmentDurationPairs == null || this._fragmentDurationPairs.length <= 0)
{
return false;
}
var fdp:FragmentDurationPair = this._fragmentDurationPairs[this.fragmentDurationPairs.length - 1] as FragmentDurationPair;
return fdp.duration == 0 && fdp.discontinuityIndicator == 0;
}
public function adjustEndEntryDurationAccrued(value:Number) : void
{
var fdp:FragmentDurationPair = this._fragmentDurationPairs[this._fragmentDurationPairs.length - 1];
if(fdp.duration == 0)
{
fdp.durationAccrued = value;
}
}
private function findValidFragmentDurationPair(index:uint) : FragmentDurationPair
{
var fdp:FragmentDurationPair = null;
for(var i:uint = index; index < this._fragmentDurationPairs.length; i++)
{
fdp = this._fragmentDurationPairs[i];
if(fdp.duration > 0)
{
return fdp;
}
}
return null;
}
private function calculateFragmentId(fdp:FragmentDurationPair, time:Number) : uint
{
if(fdp.duration <= 0)
{
return fdp.firstFragment;
}
var deltaTime:Number = time - fdp.durationAccrued;
var count:uint = deltaTime > 0 ? uint(deltaTime / fdp.duration) : 1;
if(deltaTime % fdp.duration > 0)
{
count++;
}
return fdp.firstFragment + count - 1;
}
}
}
@@ -0,0 +1,73 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class AdobeSegmentRunTable extends FullBox
{
private var _qualitySegmentURLModifiers:Vector.<String>;
private var _segmentFragmentPairs:Vector.<SegmentFragmentPair>;
public function AdobeSegmentRunTable()
{
super();
this._segmentFragmentPairs = new Vector.<SegmentFragmentPair>();
}
public function get qualitySegmentURLModifiers() : Vector.<String>
{
return this._qualitySegmentURLModifiers;
}
public function set qualitySegmentURLModifiers(value:Vector.<String>) : void
{
this._qualitySegmentURLModifiers = value;
}
public function get segmentFragmentPairs() : Vector.<SegmentFragmentPair>
{
return this._segmentFragmentPairs;
}
public function addSegmentFragmentPair(sfp:SegmentFragmentPair) : void
{
var prevSfp:SegmentFragmentPair = this._segmentFragmentPairs.length <= 0 ? null : this._segmentFragmentPairs[this._segmentFragmentPairs.length - 1];
var fragmentsAccrued:uint = 0;
if(prevSfp != null)
{
fragmentsAccrued = prevSfp.fragmentsAccrued + (sfp.firstSegment - prevSfp.firstSegment) * prevSfp.fragmentsPerSegment;
}
sfp.fragmentsAccrued = fragmentsAccrued;
this._segmentFragmentPairs.push(sfp);
}
public function findSegmentIdByFragmentId(fragmentId:uint) : uint
{
var curSfp:SegmentFragmentPair = null;
if(fragmentId < 1)
{
return 0;
}
for(var i:uint = 1; i < this._segmentFragmentPairs.length; i++)
{
curSfp = this._segmentFragmentPairs[i];
if(curSfp.fragmentsAccrued >= fragmentId)
{
return this.calculateSegmentId(this._segmentFragmentPairs[i - 1],fragmentId);
}
}
return this.calculateSegmentId(this._segmentFragmentPairs[this._segmentFragmentPairs.length - 1],fragmentId);
}
public function get totalFragments() : uint
{
return this._segmentFragmentPairs[this._segmentFragmentPairs.length - 1].fragmentsPerSegment + this._segmentFragmentPairs[this._segmentFragmentPairs.length - 1].fragmentsAccrued;
}
private function calculateSegmentId(sfp:SegmentFragmentPair, fragmentId:uint) : uint
{
return sfp.firstSegment + int((fragmentId - sfp.fragmentsAccrued - 1) / sfp.fragmentsPerSegment);
}
}
}
@@ -0,0 +1,49 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class Box
{
private var _size:Number;
private var _type:String;
private var _boxLength:uint;
public function Box()
{
super();
}
public function get size() : Number
{
return this._size;
}
public function set size(value:Number) : void
{
this._size = value;
}
public function get type() : String
{
return this._type;
}
public function set type(value:String) : void
{
this._type = value;
}
public function get boxLength() : uint
{
return this._boxLength;
}
public function set boxLength(value:uint) : void
{
this._boxLength = value;
}
}
}
@@ -0,0 +1,34 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class BoxInfo
{
private var _size:Number;
private var _type:String;
public function BoxInfo(size:Number, type:String)
{
super();
this._size = size;
this._type = type;
}
public function get size() : Number
{
return this._size;
}
public function set size(value:Number) : void
{
this._size = value;
}
public function get type() : String
{
return this._type;
}
}
}
@@ -0,0 +1,391 @@
package org.osmf.net.httpstreaming.f4f
{
import flash.errors.IllegalOperationError;
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
[ExcludeClass]
internal class BoxParser extends EventDispatcher
{
private static const FULL_BOX_FIELD_FLAGS_LENGTH:uint = 3;
private static const AFRA_MASK_LONG_ID:uint = 128;
private static const AFRA_MASK_LONG_OFFSET:uint = 64;
private static const AFRA_MASK_GLOBAL_ENTRIES:uint = 32;
private var _ba:ByteArray;
public function BoxParser()
{
super();
this._ba = null;
}
public function init(ba:ByteArray) : void
{
this._ba = ba;
this._ba.position = 0;
}
public function getNextBoxInfo() : BoxInfo
{
if(this._ba == null || this._ba.bytesAvailable < F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH)
{
return null;
}
var size:Number = this._ba.readUnsignedInt();
var type:String = this._ba.readUTFBytes(F4FConstants.FIELD_TYPE_LENGTH);
return new BoxInfo(size,type);
}
public function getBoxes() : Vector.<Box>
{
var abst:AdobeBootstrapBox = null;
var afra:AdobeFragmentRandomAccessBox = null;
var mdat:MediaDataBox = null;
var boxes:Vector.<Box> = new Vector.<Box>();
var bi:BoxInfo = this.getNextBoxInfo();
while(bi != null)
{
if(bi.type == F4FConstants.BOX_TYPE_ABST)
{
abst = new AdobeBootstrapBox();
this.parseAdobeBootstrapBox(bi,abst);
boxes.push(abst);
}
else if(bi.type == F4FConstants.BOX_TYPE_AFRA)
{
afra = new AdobeFragmentRandomAccessBox();
this.parseAdobeFragmentRandomAccessBox(bi,afra);
boxes.push(afra);
}
else if(bi.type == F4FConstants.BOX_TYPE_MDAT)
{
mdat = new MediaDataBox();
this.parseMediaDataBox(bi,mdat);
boxes.push(mdat);
}
else
{
this._ba.position = this._ba.position + bi.size - (F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH);
}
bi = this.getNextBoxInfo();
if(bi != null && bi.size <= 0)
{
break;
}
}
return boxes;
}
public function readFragmentRandomAccessBox(bi:BoxInfo) : AdobeFragmentRandomAccessBox
{
var afra:AdobeFragmentRandomAccessBox = new AdobeFragmentRandomAccessBox();
this.parseAdobeFragmentRandomAccessBox(bi,afra);
return afra;
}
public function readAdobeBootstrapBox(bi:BoxInfo) : AdobeBootstrapBox
{
var abst:AdobeBootstrapBox = new AdobeBootstrapBox();
this.parseAdobeBootstrapBox(bi,abst);
return abst;
}
internal function readLongUIntToNumber() : Number
{
if(this._ba == null || this._ba.bytesAvailable < 8)
{
throw new IllegalOperationError("not enough length for readLongUIntToNumer");
}
var result:Number = this._ba.readUnsignedInt();
result *= 4294967296;
return result + this._ba.readUnsignedInt();
}
private function readUnsignedInt() : uint
{
if(this._ba == null || this._ba.bytesAvailable < 4)
{
throw new IllegalOperationError("not enough length for readUnsignedInt");
}
return this._ba.readUnsignedInt();
}
private function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0) : void
{
if(this._ba == null || this._ba.bytesAvailable < length)
{
throw new IllegalOperationError("not enough length for readBytes: " + length);
}
return this._ba.readBytes(bytes,offset,length);
}
private function readUnsignedByte() : uint
{
if(this._ba == null || this._ba.bytesAvailable < 1)
{
throw new IllegalOperationError("not enough length for readUnsingedByte");
}
return this._ba.readUnsignedByte();
}
private function readBytesToUint(length:uint) : uint
{
var byte:uint = 0;
if(this._ba == null || this._ba.bytesAvailable < length)
{
throw new IllegalOperationError("not enough length for readUnsingedByte");
}
if(length > 4)
{
throw new IllegalOperationError("number of bytes to read must be equal or less than 4");
}
var result:uint = 0;
for(var i:uint = 0; i < length; i++)
{
result <<= 8;
byte = this._ba.readUnsignedByte();
result += byte;
}
return result;
}
private function readString() : String
{
var c:uint = 0;
var pos:uint = this._ba.position;
while(this._ba.position < this._ba.length)
{
c = uint(this._ba.readByte());
if(c == 0)
{
break;
}
}
var length:uint = this._ba.position - pos;
this._ba.position = pos;
return this._ba.readUTFBytes(length);
}
private function parseBox(boxInfo:BoxInfo, box:Box) : void
{
var extendedType:ByteArray = null;
var size:Number = boxInfo.size;
var boxLength:uint = F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH;
if(boxInfo.size == F4FConstants.FLAG_USE_LARGE_SIZE)
{
size = this.readLongUIntToNumber();
boxLength += F4FConstants.FIELD_LARGE_SIZE_LENGTH;
}
if(boxInfo.type == F4FConstants.EXTENDED_TYPE)
{
extendedType = new ByteArray();
this.readBytes(extendedType,0,F4FConstants.FIELD_EXTENDED_TYPE_LENGTH);
boxLength += F4FConstants.FIELD_EXTENDED_TYPE_LENGTH;
}
box.size = size;
box.type = boxInfo.type;
box.boxLength = boxLength;
}
private function parseFullBox(boxInfo:BoxInfo, fullBox:FullBox) : void
{
this.parseBox(boxInfo,fullBox);
fullBox.version = this.readUnsignedByte();
fullBox.flags = this.readBytesToUint(FULL_BOX_FIELD_FLAGS_LENGTH);
}
private function parseAdobeBootstrapBox(boxInfo:BoxInfo, abst:AdobeBootstrapBox) : void
{
var asrt:AdobeSegmentRunTable = null;
var afrt:AdobeFragmentRunTable = null;
this.parseFullBox(boxInfo,abst);
abst.bootstrapVersion = this.readUnsignedInt();
var temp:uint = this.readUnsignedByte();
abst.profile = temp >> 6;
abst.live = (temp & 0x20) == 32;
abst.update = (temp & 1) == 1;
abst.timeScale = this.readUnsignedInt();
abst.currentMediaTime = this.readLongUIntToNumber();
abst.smpteTimeCodeOffset = this.readLongUIntToNumber();
abst.movieIdentifier = this.readString();
var serverEntryCount:uint = this.readUnsignedByte();
var serverBaseURLs:Vector.<String> = new Vector.<String>();
for(var i:int = 0; i < serverEntryCount; i++)
{
serverBaseURLs.push(this.readString());
}
abst.serverBaseURLs = serverBaseURLs;
var qualityEntryCount:uint = this.readUnsignedByte();
var qualitySegmentURLModifiers:Vector.<String> = new Vector.<String>();
for(i = 0; i < qualityEntryCount; i++)
{
qualitySegmentURLModifiers.push(this.readString());
}
abst.qualitySegmentURLModifiers = qualitySegmentURLModifiers;
abst.drmData = this.readString();
abst.metadata = this.readString();
var segmentRunTableCount:uint = this.readUnsignedByte();
var segmentRunTables:Vector.<AdobeSegmentRunTable> = new Vector.<AdobeSegmentRunTable>();
for(i = 0; i < segmentRunTableCount; i++)
{
boxInfo = this.getNextBoxInfo();
if(boxInfo.type != F4FConstants.BOX_TYPE_ASRT)
{
throw new IllegalOperationError("Unexpected data structure: " + boxInfo.type);
}
asrt = new AdobeSegmentRunTable();
this.parseAdobeSegmentRunTable(boxInfo,asrt);
segmentRunTables.push(asrt);
}
abst.segmentRunTables = segmentRunTables;
var fragmentRunTableCount:uint = this.readUnsignedByte();
var fragmentRunTables:Vector.<AdobeFragmentRunTable> = new Vector.<AdobeFragmentRunTable>();
for(i = 0; i < fragmentRunTableCount; i++)
{
boxInfo = this.getNextBoxInfo();
if(boxInfo.type != F4FConstants.BOX_TYPE_AFRT)
{
throw new IllegalOperationError("Unexpected data structure: " + boxInfo.type);
}
afrt = new AdobeFragmentRunTable();
this.parseAdobeFragmentRunTable(boxInfo,afrt);
fragmentRunTables.push(afrt);
}
abst.fragmentRunTables = fragmentRunTables;
}
private function parseAdobeSegmentRunTable(boxInfo:BoxInfo, asrt:AdobeSegmentRunTable) : void
{
this.parseFullBox(boxInfo,asrt);
var qualityEntryCount:uint = this.readUnsignedByte();
var qualitySegmentURLModifiers:Vector.<String> = new Vector.<String>();
for(var i:uint = 0; i < qualityEntryCount; i++)
{
qualitySegmentURLModifiers.push(this.readString());
}
asrt.qualitySegmentURLModifiers = qualitySegmentURLModifiers;
var entryCount:uint = this.readUnsignedInt();
for(i = 0; i < entryCount; i++)
{
asrt.addSegmentFragmentPair(new SegmentFragmentPair(this.readUnsignedInt(),this.readUnsignedInt()));
}
}
private function parseAdobeFragmentRunTable(boxInfo:BoxInfo, afrt:AdobeFragmentRunTable) : void
{
var fdp:FragmentDurationPair = null;
this.parseFullBox(boxInfo,afrt);
afrt.timeScale = this.readUnsignedInt();
var qualityEntryCount:uint = this.readUnsignedByte();
var qualitySegmentURLModifiers:Vector.<String> = new Vector.<String>();
for(var i:uint = 0; i < qualityEntryCount; i++)
{
qualitySegmentURLModifiers.push(this.readString());
}
afrt.qualitySegmentURLModifiers = qualitySegmentURLModifiers;
var entryCount:uint = this.readUnsignedInt();
for(i = 0; i < entryCount; i++)
{
fdp = new FragmentDurationPair();
this.parseFragmentDurationPair(fdp);
afrt.addFragmentDurationPair(fdp);
}
}
private function parseFragmentDurationPair(fdp:FragmentDurationPair) : void
{
fdp.firstFragment = this.readUnsignedInt();
fdp.durationAccrued = this.readLongUIntToNumber();
fdp.duration = this.readUnsignedInt();
if(fdp.duration == 0)
{
fdp.discontinuityIndicator = this.readUnsignedByte();
}
}
private function parseAdobeFragmentRandomAccessBox(boxInfo:BoxInfo, afra:AdobeFragmentRandomAccessBox) : void
{
var lrae:LocalRandomAccessEntry = null;
var grae:GlobalRandomAccessEntry = null;
this.parseFullBox(boxInfo,afra);
var sizes:uint = this.readBytesToUint(1);
var longIdFields:Boolean = (sizes & AFRA_MASK_LONG_ID) > 0;
var longOffsetFields:Boolean = (sizes & AFRA_MASK_LONG_OFFSET) > 0;
var globalEntries:Boolean = (sizes & AFRA_MASK_GLOBAL_ENTRIES) > 0;
afra.timeScale = this.readUnsignedInt();
var entryCount:uint = this.readUnsignedInt();
var localRandomAccessEntries:Vector.<LocalRandomAccessEntry> = new Vector.<LocalRandomAccessEntry>();
for(var i:uint = 0; i < entryCount; i++)
{
lrae = new LocalRandomAccessEntry();
this.parseLocalRandomAccessEntry(lrae,longOffsetFields);
localRandomAccessEntries.push(lrae);
}
afra.localRandomAccessEntries = localRandomAccessEntries;
var globalRandomAccessEntries:Vector.<GlobalRandomAccessEntry> = new Vector.<GlobalRandomAccessEntry>();
if(globalEntries)
{
entryCount = this.readUnsignedInt();
for(i = 0; i < entryCount; i++)
{
grae = new GlobalRandomAccessEntry();
this.parseGlobalRandomAccessEntry(grae,longIdFields,longOffsetFields);
globalRandomAccessEntries.push(grae);
}
}
afra.globalRandomAccessEntries = globalRandomAccessEntries;
}
private function parseLocalRandomAccessEntry(lrae:LocalRandomAccessEntry, longOffsetFields:Boolean) : void
{
lrae.time = this.readLongUIntToNumber();
if(longOffsetFields)
{
lrae.offset = this.readLongUIntToNumber();
}
else
{
lrae.offset = this.readUnsignedInt();
}
}
private function parseGlobalRandomAccessEntry(grae:GlobalRandomAccessEntry, longIdFields:Boolean, longOffsetFields:Boolean) : void
{
grae.time = this.readLongUIntToNumber();
if(longIdFields)
{
grae.segment = this.readUnsignedInt();
grae.fragment = this.readUnsignedInt();
}
else
{
grae.segment = this.readBytesToUint(2);
grae.fragment = this.readBytesToUint(2);
}
if(longOffsetFields)
{
grae.afraOffset = this.readLongUIntToNumber();
grae.offsetFromAfra = this.readLongUIntToNumber();
}
else
{
grae.afraOffset = this.readUnsignedInt();
grae.offsetFromAfra = this.readUnsignedInt();
}
}
private function parseMediaDataBox(boxInfo:BoxInfo, mdat:MediaDataBox) : void
{
this.parseBox(boxInfo,mdat);
var data:ByteArray = new ByteArray();
this.readBytes(data,0,mdat.size - mdat.boxLength);
mdat.data = data;
}
}
}
@@ -0,0 +1,39 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class F4FConstants
{
internal static const BOX_TYPE_UUID:String = "uuid";
internal static const BOX_TYPE_ABST:String = "abst";
internal static const BOX_TYPE_ASRT:String = "asrt";
internal static const BOX_TYPE_AFRT:String = "afrt";
internal static const BOX_TYPE_AFRA:String = "afra";
internal static const BOX_TYPE_MDAT:String = "mdat";
internal static const BOX_TYPE_MOOF:String = "moof";
internal static const EXTENDED_TYPE:String = "uuid";
internal static const FIELD_SIZE_LENGTH:uint = 4;
internal static const FIELD_TYPE_LENGTH:uint = 4;
internal static const FIELD_LARGE_SIZE_LENGTH:uint = 8;
internal static const FIELD_EXTENDED_TYPE_LENGTH:uint = 16;
internal static const FLAG_USE_LARGE_SIZE:uint = 1;
public function F4FConstants()
{
super();
}
}
}
@@ -0,0 +1,19 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class FragmentAccessInformation
{
public var fragId:uint;
public var fragmentEndTime:Number;
public var fragDuration:uint;
public function FragmentAccessInformation()
{
super();
}
}
}
@@ -0,0 +1,61 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class FragmentDurationPair
{
private var _firstFragment:uint;
private var _duration:uint;
private var _durationAccrued:Number;
private var _discontinuityIndicator:uint = 0;
public function FragmentDurationPair()
{
super();
}
public function get firstFragment() : uint
{
return this._firstFragment;
}
public function set firstFragment(value:uint) : void
{
this._firstFragment = value;
}
public function get duration() : uint
{
return this._duration;
}
public function set duration(value:uint) : void
{
this._duration = value;
}
public function get durationAccrued() : Number
{
return this._durationAccrued;
}
public function set durationAccrued(value:Number) : void
{
this._durationAccrued = value;
}
public function get discontinuityIndicator() : uint
{
return this._discontinuityIndicator;
}
public function set discontinuityIndicator(value:uint) : void
{
this._discontinuityIndicator = value;
}
}
}
@@ -0,0 +1,37 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class FullBox extends Box
{
private var _version:uint;
private var _flags:uint;
public function FullBox()
{
super();
}
public function get version() : uint
{
return this._version;
}
public function set version(value:uint) : void
{
this._version = value;
}
public function get flags() : uint
{
return this._flags;
}
public function set flags(value:uint) : void
{
this._flags = value;
}
}
}
@@ -0,0 +1,73 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class GlobalRandomAccessEntry
{
private var _time:Number;
private var _segment:uint;
private var _fragment:uint;
private var _afraOffset:Number;
private var _offsetFromAfra:Number;
public function GlobalRandomAccessEntry()
{
super();
}
public function get time() : Number
{
return this._time;
}
public function set time(value:Number) : void
{
this._time = value;
}
public function get segment() : uint
{
return this._segment;
}
public function set segment(value:uint) : void
{
this._segment = value;
}
public function get fragment() : uint
{
return this._fragment;
}
public function set fragment(value:uint) : void
{
this._fragment = value;
}
public function get afraOffset() : Number
{
return this._afraOffset;
}
public function set afraOffset(value:Number) : void
{
this._afraOffset = value;
}
public function get offsetFromAfra() : Number
{
return this._offsetFromAfra;
}
public function set offsetFromAfra(value:Number) : void
{
this._offsetFromAfra = value;
}
}
}
@@ -0,0 +1,227 @@
package org.osmf.net.httpstreaming.f4f
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import org.osmf.events.HTTPStreamingFileHandlerEvent;
import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase;
[ExcludeClass]
public class HTTPStreamingF4FFileHandler extends HTTPStreamingFileHandlerBase
{
private static const MAX_BYTES_PER_MDAT_READ:uint = 5 * 1024;
private var _afra:AdobeFragmentRandomAccessBox;
private var _ba:ByteArray;
private var _boxInfoPending:Boolean;
private var _bytesNeeded:uint;
private var _bytesReadSinceAfraStart:uint;
private var _countingReadBytes:Boolean;
private var _mdatBytesPending:uint;
private var _nextBox:BoxInfo;
private var _parser:BoxParser = new BoxParser();
private var _seekToTime:Number;
private var _mdatBytesOffset:Number;
private var _processRequestWasSeek:Boolean = false;
public function HTTPStreamingF4FFileHandler()
{
super();
}
override public function beginProcessFile(seek:Boolean, seekTime:Number) : void
{
this._processRequestWasSeek = seek;
this._seekToTime = seek ? seekTime : 0;
this._bytesNeeded = F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH + F4FConstants.FIELD_LARGE_SIZE_LENGTH + F4FConstants.FIELD_EXTENDED_TYPE_LENGTH;
this._bytesReadSinceAfraStart = 0;
this._countingReadBytes = false;
this._boxInfoPending = true;
this._nextBox = null;
}
override public function get inputBytesNeeded() : Number
{
return this._bytesNeeded;
}
override public function processFileSegment(input:IDataInput) : ByteArray
{
var pos:uint = 0;
var abst:AdobeBootstrapBox = null;
if(input.bytesAvailable < this._bytesNeeded)
{
return null;
}
var returnByteArray:ByteArray = null;
var bytesRead:Number = F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH;
if(this._boxInfoPending)
{
this._ba = new ByteArray();
input.readBytes(this._ba,0,bytesRead);
if(this._countingReadBytes)
{
this._bytesReadSinceAfraStart += bytesRead;
}
this._parser.init(this._ba);
this._nextBox = this._parser.getNextBoxInfo();
if(this._nextBox.size == F4FConstants.FLAG_USE_LARGE_SIZE)
{
bytesRead += F4FConstants.FIELD_LARGE_SIZE_LENGTH;
this._ba.position = 0;
input.readBytes(this._ba,0,F4FConstants.FIELD_LARGE_SIZE_LENGTH);
if(this._countingReadBytes)
{
this._bytesReadSinceAfraStart += F4FConstants.FIELD_LARGE_SIZE_LENGTH;
}
this._nextBox.size = this._parser.readLongUIntToNumber();
}
this._boxInfoPending = false;
if(this._nextBox.type == F4FConstants.BOX_TYPE_MDAT)
{
this._bytesNeeded = 0;
this._mdatBytesPending = this._nextBox.size - bytesRead;
}
else
{
this._bytesNeeded = this._nextBox.size - bytesRead;
this._mdatBytesPending = 0;
if(this._nextBox.type == F4FConstants.BOX_TYPE_AFRA)
{
this._bytesReadSinceAfraStart = bytesRead;
this._countingReadBytes = true;
}
}
}
else if(this._bytesNeeded > 0)
{
pos = this._ba.position;
input.readBytes(this._ba,this._ba.length,this._nextBox.size - bytesRead);
if(this._countingReadBytes)
{
this._bytesReadSinceAfraStart += this._nextBox.size - bytesRead;
}
this._ba.position = pos;
if(this._nextBox.type == F4FConstants.BOX_TYPE_ABST)
{
abst = this._parser.readAdobeBootstrapBox(this._nextBox);
if(abst != null)
{
dispatchEvent(new HTTPStreamingFileHandlerEvent(HTTPStreamingFileHandlerEvent.NOTIFY_BOOTSTRAP_BOX,false,false,0,null,false,false,abst));
}
}
else if(this._nextBox.type == F4FConstants.BOX_TYPE_AFRA)
{
this._afra = this._parser.readFragmentRandomAccessBox(this._nextBox);
this.processSeekToTime();
}
else if(this._nextBox.type == F4FConstants.BOX_TYPE_MOOF)
{
}
this._bytesNeeded = F4FConstants.FIELD_SIZE_LENGTH + F4FConstants.FIELD_TYPE_LENGTH + F4FConstants.FIELD_LARGE_SIZE_LENGTH + F4FConstants.FIELD_EXTENDED_TYPE_LENGTH;
this._boxInfoPending = true;
this._nextBox = null;
}
else
{
returnByteArray = this.getMDATBytes(input,false);
}
return returnByteArray;
}
override public function endProcessFile(input:IDataInput) : ByteArray
{
if(this._bytesNeeded > 0)
{
dispatchEvent(new HTTPStreamingFileHandlerEvent(HTTPStreamingFileHandlerEvent.NOTIFY_ERROR,false,false,0,null,false,false,null,true));
}
return this.getMDATBytes(input,true);
}
override public function flushFileSegment(input:IDataInput) : ByteArray
{
return null;
}
private function getMDATBytes(input:IDataInput, endOfFile:Boolean) : ByteArray
{
var ba:ByteArray = null;
var bytesToRead:uint = 0;
if(input == null)
{
return null;
}
this.skipSeekBytes(input);
if(this._mdatBytesPending > 0)
{
bytesToRead = this._mdatBytesPending < input.bytesAvailable ? this._mdatBytesPending : input.bytesAvailable;
if(!endOfFile && bytesToRead > MAX_BYTES_PER_MDAT_READ)
{
bytesToRead = MAX_BYTES_PER_MDAT_READ;
}
ba = new ByteArray();
this._mdatBytesPending -= bytesToRead;
input.readBytes(ba,0,bytesToRead);
}
return ba;
}
private function skipSeekBytes(input:IDataInput) : void
{
var skip:uint = 0;
var ba:ByteArray = null;
if(this._bytesReadSinceAfraStart < this._mdatBytesOffset)
{
skip = this._mdatBytesOffset - this._bytesReadSinceAfraStart;
if(input.bytesAvailable < skip)
{
skip = input.bytesAvailable;
}
ba = new ByteArray();
input.readBytes(ba,0,skip);
this._bytesReadSinceAfraStart += skip;
this._mdatBytesPending -= skip;
}
}
private function processSeekToTime() : void
{
var timeBias:Number = 0;
var entry:LocalRandomAccessEntry = null;
if(this._seekToTime <= 0)
{
this._mdatBytesOffset = 0;
}
else
{
entry = this.getMDATBytesOffset(this._seekToTime);
if(entry != null)
{
this._mdatBytesOffset = entry.offset;
timeBias = entry.time;
}
else
{
this._mdatBytesOffset = 0;
}
}
}
private function getMDATBytesOffset(seekToTime:Number) : LocalRandomAccessEntry
{
return !isNaN(seekToTime) ? this._afra.findNearestKeyFrameOffset(seekToTime * this._afra.timeScale) : null;
}
}
}
@@ -0,0 +1,489 @@
package org.osmf.net.httpstreaming.f4f
{
import flash.net.URLRequest;
import flash.utils.ByteArray;
import org.osmf.elements.f4mClasses.BootstrapInfo;
import org.osmf.events.DVRStreamInfoEvent;
import org.osmf.events.HTTPStreamingFileHandlerEvent;
import org.osmf.events.HTTPStreamingIndexHandlerEvent;
import org.osmf.net.dvr.DVRUtils;
import org.osmf.net.httpstreaming.HTTPStreamRequest;
import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase;
import org.osmf.net.httpstreaming.HTTPStreamingIndexHandlerBase;
import org.osmf.net.httpstreaming.HTTPStreamingUtils;
import org.osmf.net.httpstreaming.flv.FLVTagScriptDataObject;
[ExcludeClass]
public class HTTPStreamingF4FIndexHandler extends HTTPStreamingIndexHandlerBase
{
public static const DEFAULT_FRAGMENTS_THRESHOLD:uint = 5;
private var pendingIndexLoads:int;
private var pendingIndexUpdates:int;
private var bootstrapBoxes:Vector.<AdobeBootstrapBox>;
private var serverBaseURL:String;
private var streamInfos:Vector.<HTTPStreamingF4FStreamInfo>;
private var currentQuality:int;
private var currentFAI:FragmentAccessInformation;
private var fragmentsThreshold:uint;
private var fragmentRunTablesUpdating:Boolean;
private var f4fIndexInfo:HTTPStreamingF4FIndexInfo;
private var fileHandler:HTTPStreamingFileHandlerBase;
private var dvrGetStreamInfoCall:Boolean;
private var playInProgress:Boolean;
private var offsetFromCurrent:Number = 5;
private var delay:Number = 0.05;
private var pureLiveOffset:Number = NaN;
public function HTTPStreamingF4FIndexHandler(fileHandler:HTTPStreamingFileHandlerBase, fragmentsThreshold:uint = 5)
{
super();
this.currentQuality = -1;
this.currentFAI = null;
this.fragmentRunTablesUpdating = false;
this.fileHandler = fileHandler;
this.fragmentsThreshold = fragmentsThreshold;
this.dvrGetStreamInfoCall = false;
fileHandler.addEventListener(HTTPStreamingFileHandlerEvent.NOTIFY_BOOTSTRAP_BOX,this.onNewBootstrapBox);
}
public function get bootstrapInfo() : AdobeBootstrapBox
{
return this.currentQuality < 0 ? null : this.bootstrapBoxes[this.currentQuality];
}
override public function dvrGetStreamInfo(indexInfo:Object) : void
{
this.dvrGetStreamInfoCall = true;
this.playInProgress = false;
this.initialize(indexInfo);
}
override public function initialize(indexInfo:Object) : void
{
var bootstrapBox:AdobeBootstrapBox = null;
var bootstrap:BootstrapInfo = null;
this.f4fIndexInfo = indexInfo as HTTPStreamingF4FIndexInfo;
if(this.f4fIndexInfo == null || this.f4fIndexInfo.streamInfos == null || this.f4fIndexInfo.streamInfos.length <= 0)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_ERROR));
return;
}
this.bootstrapBoxes = new Vector.<AdobeBootstrapBox>(this.f4fIndexInfo.streamInfos.length);
this.fragmentRunTablesUpdating = false;
this.playInProgress = false;
this.pendingIndexLoads = 0;
this.pureLiveOffset = NaN;
this.serverBaseURL = this.f4fIndexInfo.serverBaseURL;
this.streamInfos = this.f4fIndexInfo.streamInfos;
for(var i:int = 0; i < this.streamInfos.length; i++)
{
bootstrap = this.streamInfos[i].bootstrapInfo;
if(bootstrap == null || bootstrap.url == null && bootstrap.data == null)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_ERROR));
return;
}
if(bootstrap.data != null)
{
bootstrapBox = this.processBootstrapData(bootstrap.data,null);
if(bootstrapBox == null)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_ERROR));
return;
}
this.bootstrapBoxes[i] = bootstrapBox;
}
else
{
++this.pendingIndexLoads;
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.REQUEST_LOAD_INDEX,false,false,false,NaN,null,null,new URLRequest(HTTPStreamingUtils.normalizeURL(bootstrap.url)),i,true));
}
}
if(this.pendingIndexLoads == 0)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_RATES,false,false,false,NaN,this.getStreamNames(this.streamInfos),this.getQualityRates(this.streamInfos)));
this.notifyIndexReady(0);
}
}
override public function processIndexData(data:*, indexContext:Object) : void
{
var index:int = indexContext as int;
var bootstrapBox:AdobeBootstrapBox = this.processBootstrapData(data,index);
if(bootstrapBox == null)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_ERROR));
return;
}
if(!this.fragmentRunTablesUpdating)
{
--this.pendingIndexLoads;
}
else
{
--this.pendingIndexUpdates;
if(this.pendingIndexUpdates == 0)
{
this.fragmentRunTablesUpdating = false;
this.dispatchDVRStreamInfo(bootstrapBox);
}
}
if(this.bootstrapBoxes[index] == null || this.bootstrapBoxes[index].bootstrapVersion < bootstrapBox.bootstrapVersion || this.bootstrapBoxes[index].currentMediaTime < bootstrapBox.currentMediaTime)
{
this.delay = 0.05;
this.bootstrapBoxes[index] = bootstrapBox;
}
if(this.pendingIndexLoads == 0 && !this.fragmentRunTablesUpdating)
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_RATES,false,false,false,NaN,this.getStreamNames(this.streamInfos),this.getQualityRates(this.streamInfos)));
this.notifyIndexReady(index);
}
}
override public function getFileForTime(time:Number, quality:int) : HTTPStreamRequest
{
var fdp:FragmentDurationPair = null;
var segId:uint = 0;
var requestUrl:String = null;
var abst:AdobeBootstrapBox = this.bootstrapBoxes[quality];
var streamRequest:HTTPStreamRequest = null;
if(!this.playInProgress && this.stopPlaying(abst))
{
return null;
}
this.checkMetadata(quality,abst);
var frt:AdobeFragmentRunTable = this.getFragmentRunTable(abst);
if(time >= 0 && time * abst.timeScale <= abst.currentMediaTime && quality >= 0 && quality < this.streamInfos.length)
{
this.currentFAI = frt.findFragmentIdByTime(time * abst.timeScale,abst.currentMediaTime,abst.contentComplete() ? false : abst.live);
if(this.currentFAI == null || this.fragmentOverflow(abst,this.currentFAI.fragId))
{
if(abst.contentComplete())
{
if(abst.live)
{
return new HTTPStreamRequest(null,quality,-1,-1,true);
}
return null;
}
this.adjustDelay();
this.refreshBootstrapInfo(quality);
return new HTTPStreamRequest(null,quality,0,this.delay);
}
this.playInProgress = true;
fdp = frt.fragmentDurationPairs[0];
segId = abst.findSegmentId(this.currentFAI.fragId - fdp.firstFragment + 1);
requestUrl = "";
if((this.streamInfos[quality].streamName as String).indexOf("http") != 0)
{
requestUrl = this.serverBaseURL + "/" + this.streamInfos[quality].streamName + "Seg" + segId + "-Frag" + this.currentFAI.fragId;
}
else
{
requestUrl = this.streamInfos[quality].streamName + "Seg" + segId + "-Frag" + this.currentFAI.fragId;
}
streamRequest = new HTTPStreamRequest(requestUrl);
this.checkQuality(quality);
this.notifyFragmentDuration(this.currentFAI.fragDuration / abst.timeScale);
}
return streamRequest;
}
override public function getNextFile(quality:int) : HTTPStreamRequest
{
var frt:AdobeFragmentRunTable = null;
var oldCurrentFAI:FragmentAccessInformation = null;
var fdp:FragmentDurationPair = null;
var segId:uint = 0;
var requestUrl:String = null;
var abst:AdobeBootstrapBox = this.bootstrapBoxes[quality];
var streamRequest:HTTPStreamRequest = null;
if(!this.playInProgress && this.stopPlaying(abst))
{
return null;
}
this.checkMetadata(quality,abst);
if(quality >= 0 && quality < this.streamInfos.length)
{
frt = this.getFragmentRunTable(abst);
oldCurrentFAI = this.currentFAI;
this.currentFAI = frt.validateFragment(this.currentFAI.fragId + 1,abst.currentMediaTime,abst.contentComplete() ? false : abst.live);
if(this.currentFAI == null || this.fragmentOverflow(abst,this.currentFAI.fragId))
{
if(!abst.live || abst.contentComplete())
{
if(abst.live)
{
return new HTTPStreamRequest(null,quality,-1,-1,true);
}
return null;
}
this.adjustDelay();
this.currentFAI = oldCurrentFAI;
this.refreshBootstrapInfo(quality);
return new HTTPStreamRequest(null,quality,0,this.delay);
}
this.playInProgress = true;
fdp = frt.fragmentDurationPairs[0];
segId = abst.findSegmentId(this.currentFAI.fragId - fdp.firstFragment + 1);
requestUrl = "";
if((this.streamInfos[quality].streamName as String).indexOf("http") != 0)
{
requestUrl = this.serverBaseURL + "/" + this.streamInfos[quality].streamName + "Seg" + segId + "-Frag" + this.currentFAI.fragId;
}
else
{
requestUrl = this.streamInfos[quality].streamName + "Seg" + segId + "-Frag" + this.currentFAI.fragId;
}
streamRequest = new HTTPStreamRequest(requestUrl);
this.checkQuality(quality);
this.notifyFragmentDuration(this.currentFAI.fragDuration / abst.timeScale);
}
return streamRequest;
}
internal function calculateSegmentDuration(abst:AdobeBootstrapBox, timeBias:Number) : Number
{
var fragmentDurationPair:FragmentDurationPair = null;
var duration:Number = NaN;
var durationAccrued:Number = NaN;
var fragmentDurationPairs:Vector.<FragmentDurationPair> = abst.fragmentRunTables[0].fragmentDurationPairs;
var fragmentId:uint = this.currentFAI.fragId;
var index:int = fragmentDurationPairs.length - 1;
while(index >= 0)
{
fragmentDurationPair = fragmentDurationPairs[index];
if(fragmentDurationPair.firstFragment <= fragmentId)
{
duration = fragmentDurationPair.duration;
durationAccrued = fragmentDurationPair.durationAccrued;
durationAccrued += (fragmentId - fragmentDurationPair.firstFragment) * fragmentDurationPair.duration;
if(timeBias > 0)
{
duration -= timeBias - durationAccrued;
}
return duration;
}
index--;
}
return 0;
}
private function checkQuality(quality:int) : void
{
var prevAdditionalHeader:ByteArray = null;
var newAdditionalHeader:ByteArray = null;
var flvTag:FLVTagScriptDataObject = null;
if(this.currentQuality != quality)
{
prevAdditionalHeader = this.currentQuality < 0 ? null : this.streamInfos[this.currentQuality].additionalHeader;
this.currentQuality = quality;
newAdditionalHeader = this.streamInfos[this.currentQuality].additionalHeader;
if(newAdditionalHeader != prevAdditionalHeader && newAdditionalHeader != null)
{
flvTag = new FLVTagScriptDataObject();
flvTag.data = newAdditionalHeader;
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_SCRIPT_DATA,false,false,false,NaN,null,null,null,null,true,0,flvTag,true,false));
}
}
}
private function checkMetadata(quality:int, abst:AdobeBootstrapBox) : void
{
if(this.currentQuality != quality)
{
this.notifyTotalDuration(abst.totalDuration / abst.timeScale,quality);
}
}
private function refreshBootstrapInfo(quality:uint) : void
{
++this.pendingIndexUpdates;
this.fragmentRunTablesUpdating = true;
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.REQUEST_LOAD_INDEX,false,false,false,NaN,null,null,new URLRequest(HTTPStreamingUtils.normalizeURL((this.streamInfos[quality] as HTTPStreamingF4FStreamInfo).bootstrapInfo.url)),quality,true));
}
private function processBootstrapData(data:*, indexContext:Object) : AdobeBootstrapBox
{
var boxes:Vector.<Box> = null;
var bootstrapBox:AdobeBootstrapBox = null;
var parser:BoxParser = new BoxParser();
data.position = 0;
parser.init(data);
try
{
boxes = parser.getBoxes();
}
catch(e:Error)
{
boxes = null;
}
if(boxes == null || boxes.length < 1)
{
return null;
}
bootstrapBox = boxes[0] as AdobeBootstrapBox;
if(bootstrapBox == null)
{
return null;
}
if(this.serverBaseURL == null || this.serverBaseURL.length <= 0)
{
if(bootstrapBox.serverBaseURLs == null || bootstrapBox.serverBaseURLs.length <= 0)
{
return null;
}
}
return bootstrapBox;
}
private function getQualityRates(streamInfos:Vector.<HTTPStreamingF4FStreamInfo>) : Array
{
var i:int = 0;
var streamInfo:HTTPStreamingF4FStreamInfo = null;
var rates:Array = [];
if(streamInfos.length >= 1)
{
for(i = 0; i < streamInfos.length; i++)
{
streamInfo = streamInfos[i] as HTTPStreamingF4FStreamInfo;
rates.push(streamInfo.bitrate);
}
}
return rates;
}
private function getStreamNames(streamInfos:Vector.<HTTPStreamingF4FStreamInfo>) : Array
{
var i:int = 0;
var streamInfo:HTTPStreamingF4FStreamInfo = null;
var streamNames:Array = [];
if(streamInfos.length >= 1)
{
for(i = 0; i < streamInfos.length; i++)
{
streamInfo = streamInfos[i] as HTTPStreamingF4FStreamInfo;
streamNames.push(streamInfo.streamName);
}
}
return streamNames;
}
private function getFragmentRunTable(abst:AdobeBootstrapBox) : AdobeFragmentRunTable
{
return abst.fragmentRunTables[0];
}
private function notifyTotalDuration(duration:Number, quality:int) : void
{
var sdo:FLVTagScriptDataObject = new FLVTagScriptDataObject();
var metaInfo:Object = this.f4fIndexInfo.streamInfos[quality].streamMetadata;
if(metaInfo == null)
{
metaInfo = new Object();
}
metaInfo.duration = duration;
sdo.objects = ["onMetaData",metaInfo];
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_SCRIPT_DATA,false,false,false,NaN,null,null,null,null,false,0,sdo,false,true));
}
private function notifyFragmentDuration(duration:Number) : void
{
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_SEGMENT_DURATION,false,false,false,NaN,null,null,null,null,true,duration));
}
private function notifyIndexReady(quality:int) : void
{
var abst:AdobeBootstrapBox = this.bootstrapBoxes[quality];
var frt:AdobeFragmentRunTable = this.getFragmentRunTable(abst);
this.dispatchDVRStreamInfo(abst);
if(!this.dvrGetStreamInfoCall)
{
if(abst.live && this.f4fIndexInfo.dvrInfo == null && isNaN(this.pureLiveOffset))
{
this.pureLiveOffset = abst.currentMediaTime - this.offsetFromCurrent * abst.timeScale > 0 ? abst.currentMediaTime / abst.timeScale - this.offsetFromCurrent : NaN;
}
dispatchEvent(new HTTPStreamingIndexHandlerEvent(HTTPStreamingIndexHandlerEvent.NOTIFY_INDEX_READY,false,false,abst.live,this.pureLiveOffset));
}
this.dvrGetStreamInfoCall = false;
}
private function stopPlaying(abst:AdobeBootstrapBox) : Boolean
{
var frt:AdobeFragmentRunTable = this.getFragmentRunTable(abst);
if(this.f4fIndexInfo.dvrInfo == null && abst.live && frt.tableComplete() || this.f4fIndexInfo.dvrInfo != null && this.f4fIndexInfo.dvrInfo.offline)
{
return true;
}
return false;
}
private function onNewBootstrapBox(event:HTTPStreamingFileHandlerEvent) : void
{
var abst:AdobeBootstrapBox = this.bootstrapBoxes[this.currentQuality];
if(abst.bootstrapVersion < event.bootstrapBox.bootstrapVersion || abst.currentMediaTime < event.bootstrapBox.currentMediaTime)
{
this.bootstrapBoxes[this.currentQuality] = event.bootstrapBox;
this.dispatchDVRStreamInfo(event.bootstrapBox);
}
}
private function dispatchDVRStreamInfo(abst:AdobeBootstrapBox) : void
{
var frt:AdobeFragmentRunTable = this.getFragmentRunTable(abst);
if(this.f4fIndexInfo.dvrInfo != null)
{
this.f4fIndexInfo.dvrInfo.isRecording = !frt.tableComplete();
if(isNaN(this.f4fIndexInfo.dvrInfo.startTime))
{
this.f4fIndexInfo.dvrInfo.startTime = frt.tableComplete() ? 0 : DVRUtils.calculateOffset(this.f4fIndexInfo.dvrInfo.beginOffset < 0 || isNaN(this.f4fIndexInfo.dvrInfo.beginOffset) ? 0 : this.f4fIndexInfo.dvrInfo.beginOffset,this.f4fIndexInfo.dvrInfo.endOffset < 0 || isNaN(this.f4fIndexInfo.dvrInfo.endOffset) ? 0 : this.f4fIndexInfo.dvrInfo.endOffset,abst.totalDuration / abst.timeScale);
this.f4fIndexInfo.dvrInfo.startTime += frt.fragmentDurationPairs[0].durationAccrued / abst.timeScale;
if(this.f4fIndexInfo.dvrInfo.startTime > abst.currentMediaTime)
{
this.f4fIndexInfo.dvrInfo.startTime = abst.currentMediaTime;
}
}
this.f4fIndexInfo.dvrInfo.curLength = abst.currentMediaTime / abst.timeScale - this.f4fIndexInfo.dvrInfo.startTime;
dispatchEvent(new DVRStreamInfoEvent(DVRStreamInfoEvent.DVRSTREAMINFO,false,false,this.f4fIndexInfo.dvrInfo));
}
}
private function fragmentOverflow(abst:AdobeBootstrapBox, fragId:uint) : Boolean
{
var fragmentRunTable:AdobeFragmentRunTable = abst.fragmentRunTables[0];
var fdp:FragmentDurationPair = fragmentRunTable.fragmentDurationPairs[0];
var segmentRunTable:AdobeSegmentRunTable = abst.segmentRunTables[0];
return segmentRunTable == null || segmentRunTable.totalFragments + fdp.firstFragment - 1 < fragId;
}
private function adjustDelay() : void
{
if(this.delay < 1)
{
this.delay *= 2;
if(this.delay > 1)
{
this.delay = 1;
}
}
}
}
}
@@ -0,0 +1,40 @@
package org.osmf.net.httpstreaming.f4f
{
import org.osmf.net.httpstreaming.HTTPStreamingIndexInfoBase;
import org.osmf.net.httpstreaming.dvr.DVRInfo;
[ExcludeClass]
public class HTTPStreamingF4FIndexInfo extends HTTPStreamingIndexInfoBase
{
private var _serverBaseURL:String;
private var _dvrInfo:DVRInfo;
private var _streamInfos:Vector.<HTTPStreamingF4FStreamInfo>;
public function HTTPStreamingF4FIndexInfo(serverBaseURL:String = null, streamInfos:Vector.<HTTPStreamingF4FStreamInfo> = null, dvrInfo:DVRInfo = null)
{
super();
this._serverBaseURL = serverBaseURL;
this._streamInfos = streamInfos;
this._dvrInfo = dvrInfo;
}
public function get serverBaseURL() : String
{
return this._serverBaseURL;
}
public function get streamInfos() : Vector.<HTTPStreamingF4FStreamInfo>
{
return this._streamInfos;
}
public function get dvrInfo() : DVRInfo
{
return this._dvrInfo;
}
}
}
@@ -0,0 +1,64 @@
package org.osmf.net.httpstreaming.f4f
{
import flash.utils.ByteArray;
import org.osmf.elements.f4mClasses.BootstrapInfo;
[ExcludeClass]
public class HTTPStreamingF4FStreamInfo
{
private var _streamName:String;
private var _bitrate:Number;
private var _bootstrap:BootstrapInfo;
private var _additionalHeader:ByteArray;
private var _streamMetadata:Object;
private var _xmpMetadata:ByteArray;
public function HTTPStreamingF4FStreamInfo(bootstrap:BootstrapInfo, streamName:String, bitrate:Number, additionalHeader:ByteArray, streamMetadata:Object, xmpMetadata:ByteArray)
{
super();
this._streamName = streamName;
this._bitrate = bitrate;
this._additionalHeader = additionalHeader;
this._bootstrap = bootstrap;
this._streamMetadata = streamMetadata;
this._xmpMetadata = xmpMetadata;
}
public function get streamName() : String
{
return this._streamName;
}
public function get bitrate() : Number
{
return this._bitrate;
}
public function get additionalHeader() : ByteArray
{
return this._additionalHeader;
}
public function get bootstrapInfo() : BootstrapInfo
{
return this._bootstrap;
}
public function get streamMetadata() : Object
{
return this._streamMetadata;
}
public function get xmpMetadata() : ByteArray
{
return this._xmpMetadata;
}
}
}
@@ -0,0 +1,37 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class LocalRandomAccessEntry
{
private var _time:Number;
private var _offset:Number;
public function LocalRandomAccessEntry()
{
super();
}
public function get time() : Number
{
return this._time;
}
public function set time(value:Number) : void
{
this._time = value;
}
public function get offset() : Number
{
return this._offset;
}
public function set offset(value:Number) : void
{
this._offset = value;
}
}
}
@@ -0,0 +1,27 @@
package org.osmf.net.httpstreaming.f4f
{
import flash.utils.ByteArray;
[ExcludeClass]
internal class MediaDataBox extends Box
{
private var _data:ByteArray;
public function MediaDataBox()
{
super();
}
public function get data() : ByteArray
{
return this._data;
}
public function set data(value:ByteArray) : void
{
this._data = value;
}
}
}
@@ -0,0 +1,41 @@
package org.osmf.net.httpstreaming.f4f
{
[ExcludeClass]
internal class SegmentFragmentPair
{
private var _firstSegment:uint;
private var _fragmentsPerSegment:uint;
private var _fragmentsAccrued:uint;
public function SegmentFragmentPair(firstSegment:uint, fragmentsPerSegment:uint)
{
super();
this._firstSegment = firstSegment;
this._fragmentsPerSegment = fragmentsPerSegment;
}
public function get firstSegment() : uint
{
return this._firstSegment;
}
public function get fragmentsPerSegment() : uint
{
return this._fragmentsPerSegment;
}
public function set fragmentsAccrued(v:uint) : void
{
this._fragmentsAccrued = v;
}
public function get fragmentsAccrued() : uint
{
return this._fragmentsAccrued;
}
}
}
@@ -0,0 +1,128 @@
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
[ExcludeClass]
public class FLVHeader
{
public static const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
private var _hasVideoTags:Boolean = true;
private var _hasAudioTags:Boolean = true;
private var offset:uint;
public function FLVHeader(input:IDataInput = null)
{
super();
if(input != null)
{
this.readHeader(input);
this.readRest(input);
}
}
public function get hasAudioTags() : Boolean
{
return this._hasAudioTags;
}
public function set hasAudioTags(value:Boolean) : void
{
this._hasAudioTags = value;
}
public function get hasVideoTags() : Boolean
{
return this._hasVideoTags;
}
public function set hasVideoTags(value:Boolean) : void
{
this._hasVideoTags = value;
}
public function write(output:IDataOutput) : void
{
output.writeByte(70);
output.writeByte(76);
output.writeByte(86);
output.writeByte(1);
var flags:uint = 0;
if(this._hasAudioTags)
{
flags |= 4;
}
if(this._hasVideoTags)
{
flags |= 1;
}
output.writeByte(flags);
var offsetToWrite:uint = uint(MIN_FILE_HEADER_BYTE_COUNT);
output.writeUnsignedInt(offsetToWrite);
var previousTagSize0:uint = 0;
output.writeUnsignedInt(previousTagSize0);
}
internal function readHeader(input:IDataInput) : void
{
if(input.bytesAvailable < MIN_FILE_HEADER_BYTE_COUNT)
{
throw new Error("FLVHeader() input too short");
}
if(input.readByte() != 70)
{
throw new Error("FLVHeader readHeader() Signature[0] not \'F\'");
}
if(input.readByte() != 76)
{
throw new Error("FLVHeader readHeader() Signature[1] not \'L\'");
}
if(input.readByte() != 86)
{
throw new Error("FLVHeader readHeader() Signature[2] not \'V\'");
}
if(input.readByte() != 1)
{
throw new Error("FLVHeader readHeader() Version not 0x01");
}
var flags:int = input.readByte();
this._hasAudioTags = Boolean(flags & 4) ? true : false;
this._hasVideoTags = Boolean(flags & 1) ? true : false;
this.offset = input.readUnsignedInt();
if(this.offset < MIN_FILE_HEADER_BYTE_COUNT)
{
throw new Error("FLVHeader() offset smaller than minimum");
}
}
internal function readRest(input:IDataInput) : void
{
var discard:ByteArray = null;
if(this.offset > MIN_FILE_HEADER_BYTE_COUNT)
{
if(this.offset - MIN_FILE_HEADER_BYTE_COUNT < input.bytesAvailable - FLVTag.PREV_TAG_BYTE_COUNT)
{
throw new Error("FLVHeader() input too short for nonstandard offset");
}
discard = new ByteArray();
input.readBytes(discard,0,this.offset - MIN_FILE_HEADER_BYTE_COUNT);
}
if(input.bytesAvailable < FLVTag.PREV_TAG_BYTE_COUNT)
{
throw new Error("FLVHeader() input too short for previousTagSize0");
}
input.readUnsignedInt();
}
internal function get restBytesNeeded() : int
{
return FLVTag.PREV_TAG_BYTE_COUNT + (this.offset - MIN_FILE_HEADER_BYTE_COUNT);
}
}
}
@@ -0,0 +1,176 @@
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
[ExcludeClass]
public class FLVParser
{
private var state:String;
private var savedBytes:ByteArray;
private var currentTag:FLVTag = null;
private var flvHeader:FLVHeader;
public function FLVParser(startWithFileHeader:Boolean)
{
super();
this.savedBytes = new ByteArray();
if(startWithFileHeader)
{
this.state = FLVParserState.FILE_HEADER;
}
else
{
this.state = FLVParserState.TYPE;
}
}
public function flush(output:IDataOutput) : void
{
output.writeBytes(this.savedBytes);
}
public function parse(input:IDataInput, consumeAll:Boolean, onEachFLVTag:Function) : void
{
var source:IDataInput = null;
var type:int = 0;
var continueParsing:Boolean = true;
while(continueParsing)
{
switch(this.state)
{
case FLVParserState.FILE_HEADER:
source = this.byteSource(input,FLVHeader.MIN_FILE_HEADER_BYTE_COUNT);
if(source != null)
{
this.flvHeader = new FLVHeader();
this.flvHeader.readHeader(source);
this.state = FLVParserState.FILE_HEADER_REST;
}
else
{
continueParsing = false;
}
break;
case FLVParserState.FILE_HEADER_REST:
source = this.byteSource(input,this.flvHeader.restBytesNeeded);
if(source != null)
{
this.flvHeader.readRest(source);
this.state = FLVParserState.TYPE;
}
else
{
continueParsing = false;
}
break;
case FLVParserState.TYPE:
source = this.byteSource(input,1);
if(source != null)
{
type = source.readByte();
switch(type)
{
case FLVTag.TAG_TYPE_AUDIO:
case FLVTag.TAG_TYPE_ENCRYPTED_AUDIO:
this.currentTag = new FLVTagAudio(type);
break;
case FLVTag.TAG_TYPE_VIDEO:
case FLVTag.TAG_TYPE_ENCRYPTED_VIDEO:
this.currentTag = new FLVTagVideo(type);
break;
case FLVTag.TAG_TYPE_SCRIPTDATAOBJECT:
case FLVTag.TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT:
this.currentTag = new FLVTagScriptDataObject(type);
break;
default:
this.currentTag = new FLVTag(type);
}
this.state = FLVParserState.HEADER;
}
else
{
continueParsing = false;
}
break;
case FLVParserState.HEADER:
source = this.byteSource(input,FLVTag.TAG_HEADER_BYTE_COUNT - 1);
if(source != null)
{
this.currentTag.readRemainingHeader(source);
if(Boolean(this.currentTag.dataSize))
{
this.state = FLVParserState.DATA;
}
else
{
this.state = FLVParserState.PREV_TAG;
}
}
else
{
continueParsing = false;
}
break;
case FLVParserState.DATA:
source = this.byteSource(input,this.currentTag.dataSize);
if(source != null)
{
this.currentTag.readData(source);
this.state = FLVParserState.PREV_TAG;
}
else
{
continueParsing = false;
}
break;
case FLVParserState.PREV_TAG:
source = this.byteSource(input,FLVTag.PREV_TAG_BYTE_COUNT);
if(source != null)
{
this.currentTag.readPrevTag(source);
this.state = FLVParserState.TYPE;
continueParsing = onEachFLVTag(this.currentTag);
}
else
{
continueParsing = false;
}
break;
default:
throw new Error("FLVParser state machine in unknown state");
}
}
if(consumeAll)
{
input.readBytes(this.savedBytes,this.savedBytes.length);
}
}
private function byteSource(input:IDataInput, numBytes:int) : IDataInput
{
var needed:int = 0;
if(this.savedBytes.bytesAvailable + input.bytesAvailable < numBytes)
{
return null;
}
if(Boolean(this.savedBytes.bytesAvailable))
{
needed = numBytes - this.savedBytes.bytesAvailable;
if(needed > 0)
{
input.readBytes(this.savedBytes,this.savedBytes.length,needed);
}
return this.savedBytes;
}
this.savedBytes.length = 0;
return input;
}
}
}
@@ -0,0 +1,25 @@
package org.osmf.net.httpstreaming.flv
{
[ExcludeClass]
internal class FLVParserState
{
internal static const FILE_HEADER:String = "fileHeader";
internal static const FILE_HEADER_REST:String = "fileHeaderRest";
internal static const TYPE:String = "type";
internal static const HEADER:String = "header";
internal static const DATA:String = "data";
internal static const PREV_TAG:String = "prevTag";
public function FLVParserState()
{
super();
}
}
}
@@ -0,0 +1,156 @@
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
[ExcludeClass]
public class FLVTag
{
public static const TAG_TYPE_AUDIO:int = 8;
public static const TAG_TYPE_VIDEO:int = 9;
public static const TAG_TYPE_SCRIPTDATAOBJECT:int = 18;
public static const TAG_FLAG_ENCRYPTED:int = 32;
public static const TAG_TYPE_ENCRYPTED_AUDIO:int = TAG_TYPE_AUDIO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_VIDEO:int = TAG_TYPE_VIDEO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT:int = TAG_TYPE_SCRIPTDATAOBJECT + TAG_FLAG_ENCRYPTED;
internal static const TAG_HEADER_BYTE_COUNT:int = 11;
internal static const PREV_TAG_BYTE_COUNT:int = 4;
protected var bytes:ByteArray = null;
public function FLVTag(type:int)
{
super();
this.bytes = new ByteArray();
this.bytes.length = TAG_HEADER_BYTE_COUNT;
this.bytes[0] = type;
}
public function read(input:IDataInput) : void
{
this.readType(input);
this.readRemainingHeader(input);
this.readData(input);
this.readPrevTag(input);
}
public function readType(input:IDataInput) : void
{
if(input.bytesAvailable < 1)
{
throw new Error("FLVTag.readType() input too short");
}
input.readBytes(this.bytes,0,1);
}
public function readRemaining(input:IDataInput) : void
{
this.readRemainingHeader(input);
this.readData(input);
this.readPrevTag(input);
}
public function readRemainingHeader(input:IDataInput) : void
{
if(input.bytesAvailable < 10)
{
throw new Error("FLVTag.readHeader() input too short");
}
input.readBytes(this.bytes,1,TAG_HEADER_BYTE_COUNT - 1);
}
public function readData(input:IDataInput) : void
{
if(this.dataSize > 0)
{
if(input.bytesAvailable < this.dataSize)
{
throw new Error("FLVTag().readData input shorter than dataSize");
}
input.readBytes(this.bytes,TAG_HEADER_BYTE_COUNT,this.dataSize);
}
}
public function readPrevTag(input:IDataInput) : void
{
if(input.bytesAvailable < 4)
{
throw new Error("FLVTag.readPrevTag() input too short");
}
input.readUnsignedInt();
}
public function write(output:IDataOutput) : void
{
output.writeBytes(this.bytes,0,TAG_HEADER_BYTE_COUNT + this.dataSize);
output.writeUnsignedInt(TAG_HEADER_BYTE_COUNT + this.dataSize);
}
public function get tagType() : uint
{
return this.bytes[0];
}
public function set tagType(value:uint) : void
{
this.bytes[0] = value;
}
public function get isEncrpted() : Boolean
{
return Boolean(this.bytes[0] & TAG_FLAG_ENCRYPTED) ? true : false;
}
public function get dataSize() : uint
{
return this.bytes[1] << 16 | this.bytes[2] << 8 | this.bytes[3];
}
public function set dataSize(value:uint) : void
{
this.bytes[1] = value >> 16 & 0xFF;
this.bytes[2] = value >> 8 & 0xFF;
this.bytes[3] = value & 0xFF;
this.bytes.length = TAG_HEADER_BYTE_COUNT + value;
}
public function get timestamp() : uint
{
return this.bytes[7] << 24 | this.bytes[4] << 16 | this.bytes[5] << 8 | this.bytes[6];
}
public function set timestamp(value:uint) : void
{
this.bytes[7] = value >> 24 & 0xFF;
this.bytes[4] = value >> 16 & 0xFF;
this.bytes[5] = value >> 8 & 0xFF;
this.bytes[6] = value & 0xFF;
}
public function get data() : ByteArray
{
var data:ByteArray = new ByteArray();
data.writeBytes(this.bytes,TAG_HEADER_BYTE_COUNT,this.dataSize);
return data;
}
public function set data(value:ByteArray) : void
{
this.bytes.length = TAG_HEADER_BYTE_COUNT + value.length;
this.bytes.position = TAG_HEADER_BYTE_COUNT;
this.bytes.writeBytes(value,0,value.length);
this.dataSize = value.length;
}
}
}
@@ -0,0 +1,247 @@
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
[ExcludeClass]
public class FLVTagAudio extends FLVTag
{
public static const SOUND_FORMAT_LINEAR:int = 0;
public static const SOUND_FORMAT_ADPCM:int = 1;
public static const SOUND_FORMAT_MP3:int = 2;
public static const SOUND_FORMAT_LINEAR_LE:int = 3;
public static const SOUND_FORMAT_NELLYMOSER_16K:int = 4;
public static const SOUND_FORMAT_NELLYMOSER_8K:int = 5;
public static const SOUND_FORMAT_NELLYMOSER:int = 6;
public static const SOUND_FORMAT_G711A:int = 7;
public static const SOUND_FORMAT_G711U:int = 8;
public static const SOUND_FORMAT_AAC:int = 10;
public static const SOUND_FORMAT_SPEEX:int = 11;
public static const SOUND_FORMAT_MP3_8K:int = 14;
public static const SOUND_FORMAT_DEVICE_SPECIFIC:int = 15;
public static const SOUND_RATE_5K:Number = 5512.5;
public static const SOUND_RATE_11K:Number = 11025;
public static const SOUND_RATE_22K:Number = 22050;
public static const SOUND_RATE_44K:Number = 44100;
public static const SOUND_SIZE_8BITS:int = 8;
public static const SOUND_SIZE_16BITS:int = 16;
public static const SOUND_CHANNELS_MONO:int = 1;
public static const SOUND_CHANNELS_STEREO:int = 2;
public function FLVTagAudio(type:int = 8)
{
super(type);
}
public function get soundFormatByte() : int
{
return bytes[TAG_HEADER_BYTE_COUNT + 0];
}
public function set soundFormatByte(value:int) : void
{
bytes[TAG_HEADER_BYTE_COUNT + 0] = value;
}
public function get soundFormat() : int
{
return bytes[TAG_HEADER_BYTE_COUNT + 0] >> 4 & 0x0F;
}
public function set soundFormat(value:int) : void
{
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 15;
bytes[TAG_HEADER_BYTE_COUNT + 0] |= value << 4 & 0xF0;
if(value == SOUND_FORMAT_AAC)
{
this.soundRate = SOUND_RATE_44K;
this.soundChannels = SOUND_CHANNELS_STEREO;
this.isAACSequenceHeader = false;
}
}
public function get soundRate() : Number
{
switch(bytes[TAG_HEADER_BYTE_COUNT + 0] >> 2 & 3)
{
case 0:
return SOUND_RATE_5K;
case 1:
return SOUND_RATE_11K;
case 2:
return SOUND_RATE_22K;
case 3:
return SOUND_RATE_44K;
default:
throw new Error("get soundRate() a two-bit number wasn\'t 0, 1, 2, or 3. impossible.");
}
}
public function set soundRate(value:Number) : void
{
var setting:int = 0;
switch(value)
{
case SOUND_RATE_5K:
setting = 0;
break;
case SOUND_RATE_11K:
setting = 1;
break;
case SOUND_RATE_22K:
setting = 2;
break;
case SOUND_RATE_44K:
setting = 3;
break;
default:
throw new Error("set soundRate valid values 5512.5, 11025, 22050, 44100");
}
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 243;
bytes[TAG_HEADER_BYTE_COUNT + 0] |= setting << 2;
}
public function get soundSize() : int
{
if(Boolean(bytes[TAG_HEADER_BYTE_COUNT + 0] >> 1 & 1))
{
return SOUND_SIZE_16BITS;
}
return SOUND_SIZE_8BITS;
}
public function set soundSize(value:int) : void
{
switch(value)
{
case SOUND_SIZE_8BITS:
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 253;
break;
case SOUND_SIZE_16BITS:
bytes[TAG_HEADER_BYTE_COUNT + 0] |= 2;
break;
default:
throw new Error("set soundSize valid values 8, 16");
}
}
public function get soundChannels() : int
{
if(Boolean(bytes[TAG_HEADER_BYTE_COUNT + 0] & 1))
{
return SOUND_CHANNELS_STEREO;
}
return SOUND_CHANNELS_MONO;
}
public function set soundChannels(value:int) : void
{
switch(value)
{
case SOUND_CHANNELS_MONO:
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 254;
break;
case SOUND_CHANNELS_STEREO:
bytes[TAG_HEADER_BYTE_COUNT + 0] |= 1;
break;
default:
throw new Error("set soundChannels valid values 1, 2");
}
}
public function get isAACSequenceHeader() : Boolean
{
if(this.soundFormat != SOUND_FORMAT_AAC)
{
throw new Error("get isAACSequenceHeader not valid if soundFormat != SOUND_FORMAT_AAC");
}
if(bytes[TAG_HEADER_BYTE_COUNT + 1] == 0)
{
return true;
}
return false;
}
public function set isAACSequenceHeader(value:Boolean) : void
{
if(this.soundFormat != SOUND_FORMAT_AAC)
{
throw new Error("set isAACSequenceHeader not valid if soundFormat != SOUND_FORMAT_AAC");
}
if(value)
{
bytes[TAG_HEADER_BYTE_COUNT + 1] = 0;
}
else
{
bytes[TAG_HEADER_BYTE_COUNT + 1] = 1;
}
}
public function get isCodecConfiguration() : Boolean
{
switch(this.soundFormat)
{
case FLVTagAudio.SOUND_FORMAT_AAC:
if(this.isAACSequenceHeader)
{
return true;
}
}
return false;
}
override public function get data() : ByteArray
{
var data:ByteArray = new ByteArray();
if(this.soundFormat == SOUND_FORMAT_AAC)
{
data.writeBytes(bytes,TAG_HEADER_BYTE_COUNT + 2,dataSize - 2);
}
else
{
data.writeBytes(bytes,TAG_HEADER_BYTE_COUNT + 1,dataSize - 1);
}
return data;
}
override public function set data(value:ByteArray) : void
{
if(this.soundFormat == SOUND_FORMAT_AAC)
{
bytes.length = TAG_HEADER_BYTE_COUNT + value.length + 2;
bytes.position = TAG_HEADER_BYTE_COUNT + 2;
bytes.writeBytes(value,0,value.length);
dataSize = value.length + 2;
}
else
{
bytes.length = TAG_HEADER_BYTE_COUNT + value.length + 1;
bytes.position = TAG_HEADER_BYTE_COUNT + 1;
bytes.writeBytes(value,0,value.length);
dataSize = value.length + 1;
}
}
}
}
@@ -0,0 +1,39 @@
package org.osmf.net.httpstreaming.flv
{
import flash.net.ObjectEncoding;
[ExcludeClass]
public class FLVTagScriptDataObject extends FLVTag
{
public function FLVTagScriptDataObject(type:int = 18)
{
super(type);
}
public function get objects() : Array
{
var array:Array = new Array();
bytes.position = TAG_HEADER_BYTE_COUNT;
while(Boolean(bytes.bytesAvailable))
{
array.push(bytes.readObject());
}
return array;
}
public function set objects(array:Array) : void
{
var object:Object = null;
bytes.objectEncoding = ObjectEncoding.AMF0;
bytes.length = TAG_HEADER_BYTE_COUNT;
bytes.position = TAG_HEADER_BYTE_COUNT;
for each(object in array)
{
bytes.writeObject(object);
}
dataSize = bytes.length - TAG_HEADER_BYTE_COUNT;
}
}
}
@@ -0,0 +1,176 @@
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
[ExcludeClass]
public class FLVTagVideo extends FLVTag
{
public static const FRAME_TYPE_KEYFRAME:int = 1;
public static const FRAME_TYPE_INTER:int = 2;
public static const FRAME_TYPE_DISPOSABLE_INTER:int = 3;
public static const FRAME_TYPE_GENERATED_KEYFRAME:int = 4;
public static const FRAME_TYPE_INFO:int = 5;
public static const CODEC_ID_JPEG:int = 1;
public static const CODEC_ID_SORENSON:int = 2;
public static const CODEC_ID_SCREEN:int = 3;
public static const CODEC_ID_VP6:int = 4;
public static const CODEC_ID_VP6_ALPHA:int = 5;
public static const CODEC_ID_SCREEN_V2:int = 6;
public static const CODEC_ID_AVC:int = 7;
public static const AVC_PACKET_TYPE_SEQUENCE_HEADER:int = 0;
public static const AVC_PACKET_TYPE_NALU:int = 1;
public static const AVC_PACKET_TYPE_END_OF_SEQUENCE:int = 2;
public static const INFO_PACKET_SEEK_START:int = 0;
public static const INFO_PACKET_SEEK_END:int = 1;
public function FLVTagVideo(type:int = 9)
{
super(type);
}
public function get frameType() : int
{
return bytes[TAG_HEADER_BYTE_COUNT + 0] >> 4 & 0x0F;
}
public function set frameType(value:int) : void
{
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 15;
bytes[TAG_HEADER_BYTE_COUNT + 0] |= (value & 0x0F) << 4;
}
public function get codecID() : int
{
return bytes[TAG_HEADER_BYTE_COUNT + 0] & 0x0F;
}
public function set codecID(value:int) : void
{
bytes[TAG_HEADER_BYTE_COUNT + 0] &= 240;
bytes[TAG_HEADER_BYTE_COUNT + 0] |= value & 0x0F;
}
public function get infoPacketValue() : int
{
if(this.frameType != FRAME_TYPE_INFO)
{
throw new Error("get infoPacketValue() not permitted unless frameType is FRAME_TYPE_INFO");
}
return bytes[TAG_HEADER_BYTE_COUNT + 1];
}
public function set infoPacketValue(value:int) : void
{
if(this.frameType != FRAME_TYPE_INFO)
{
throw new Error("get infoPacketValue() not permitted unless frameType is FRAME_TYPE_INFO");
}
bytes[TAG_HEADER_BYTE_COUNT + 1] = value;
bytes.length = TAG_HEADER_BYTE_COUNT + 2;
dataSize = 2;
}
public function get avcPacketType() : int
{
if(this.codecID != CODEC_ID_AVC)
{
throw new Error("get avcPacketType() not permitted unless codecID is CODEC_ID_AVC");
}
return bytes[TAG_HEADER_BYTE_COUNT + 1];
}
public function set avcPacketType(value:int) : void
{
if(this.codecID != CODEC_ID_AVC)
{
throw new Error("set avcPacketType() not permitted unless codecID is CODEC_ID_AVC");
}
bytes[TAG_HEADER_BYTE_COUNT + 1] = value;
if(this.avcPacketType != AVC_PACKET_TYPE_NALU)
{
bytes[TAG_HEADER_BYTE_COUNT + 2] = 0;
bytes[TAG_HEADER_BYTE_COUNT + 3] = 0;
bytes[TAG_HEADER_BYTE_COUNT + 4] = 0;
bytes.length = TAG_HEADER_BYTE_COUNT + 5;
dataSize = 5;
}
}
public function get avcCompositionTimeOffset() : int
{
if(this.codecID != CODEC_ID_AVC || this.avcPacketType != AVC_PACKET_TYPE_NALU)
{
throw new Error("get avcCompositionTimeOffset() not permitted unless codecID is CODEC_ID_AVC and avcPacketType is AVC NALU");
}
var value:int = bytes[TAG_HEADER_BYTE_COUNT + 2] << 16;
value |= bytes[TAG_HEADER_BYTE_COUNT + 3] << 8;
value |= bytes[TAG_HEADER_BYTE_COUNT + 4];
if(Boolean(value & 0x800000))
{
value |= 4278190080;
}
return value;
}
public function set avcCompositionTimeOffset(value:int) : void
{
if(this.codecID != CODEC_ID_AVC || this.avcPacketType != AVC_PACKET_TYPE_NALU)
{
throw new Error("set avcCompositionTimeOffset() not permitted unless codecID is CODEC_ID_AVC and avcPacketType is AVC NALU");
}
bytes[TAG_HEADER_BYTE_COUNT + 2] = value >> 16 & 0xFF;
bytes[TAG_HEADER_BYTE_COUNT + 3] = value >> 8 & 0xFF;
bytes[TAG_HEADER_BYTE_COUNT + 4] = value & 0xFF;
}
override public function get data() : ByteArray
{
var data:ByteArray = new ByteArray();
if(this.codecID == CODEC_ID_AVC)
{
data.writeBytes(bytes,TAG_HEADER_BYTE_COUNT + 5,dataSize - 5);
}
else
{
data.writeBytes(bytes,TAG_HEADER_BYTE_COUNT + 1,dataSize - 1);
}
return data;
}
override public function set data(value:ByteArray) : void
{
if(this.codecID == CODEC_ID_AVC)
{
bytes.length = TAG_HEADER_BYTE_COUNT + value.length + 5;
bytes.position = TAG_HEADER_BYTE_COUNT + 5;
bytes.writeBytes(value,0,value.length);
dataSize = value.length + 5;
}
else
{
bytes.length = TAG_HEADER_BYTE_COUNT + value.length + 1;
bytes.position = TAG_HEADER_BYTE_COUNT + 1;
bytes.writeBytes(value,0,value.length);
dataSize = value.length + 1;
}
}
}
}
@@ -0,0 +1,77 @@
package org.osmf.net.rtmpstreaming
{
import flash.utils.getTimer;
import org.osmf.net.NetStreamMetricsBase;
import org.osmf.net.SwitchingRuleBase;
public class DroppedFramesRule extends SwitchingRuleBase
{
private static const LOCK_INTERVAL:Number = 30000;
private var downSwitchByOne:int;
private var downSwitchByTwo:int;
private var downSwitchToZero:int;
private var lockLevel:Number;
private var lastLockTime:Number;
public function DroppedFramesRule(metrics:NetStreamMetricsBase, downSwitchByOne:int = 10, downSwitchByTwo:int = 20, downSwitchToZero:int = 24)
{
super(metrics);
this.downSwitchByOne = downSwitchByOne;
this.downSwitchByTwo = downSwitchByTwo;
this.downSwitchToZero = downSwitchToZero;
this.lastLockTime = 0;
this.lockLevel = int.MAX_VALUE;
}
override public function getNewIndex() : int
{
var moreDetail:String = null;
var newIndex:int = -1;
if(metrics.averageDroppedFPS > this.downSwitchToZero)
{
newIndex = 0;
moreDetail = "Average droppedFPS of " + Math.round(metrics.averageDroppedFPS) + " > " + this.downSwitchToZero;
}
else if(metrics.averageDroppedFPS > this.downSwitchByTwo)
{
newIndex = metrics.currentIndex - 2 < 0 ? 0 : int(metrics.currentIndex - 2);
moreDetail = "Average droppedFPS of " + Math.round(metrics.averageDroppedFPS) + " > " + this.downSwitchByTwo;
}
else if(metrics.averageDroppedFPS > this.downSwitchByOne)
{
newIndex = metrics.currentIndex - 1 < 0 ? 0 : int(metrics.currentIndex - 1);
moreDetail = "Average droppedFPS of " + Math.round(metrics.averageDroppedFPS) + " > " + this.downSwitchByOne;
}
if(newIndex != -1 && newIndex < metrics.currentIndex)
{
this.lockIndex(newIndex);
}
if(newIndex == -1 && this.isLocked(metrics.currentIndex))
{
newIndex = metrics.currentIndex;
}
return newIndex;
}
private function lockIndex(index:int) : void
{
if(!this.isLocked(index))
{
this.lockLevel = index;
this.lastLockTime = getTimer();
}
}
private function isLocked(index:int) : Boolean
{
return index >= this.lockLevel && getTimer() - this.lastLockTime < LOCK_INTERVAL;
}
}
}
@@ -0,0 +1,42 @@
package org.osmf.net.rtmpstreaming
{
import org.osmf.net.SwitchingRuleBase;
public class InsufficientBandwidthRule extends SwitchingRuleBase
{
private var bitrateMultiplier:Number;
public function InsufficientBandwidthRule(metrics:RTMPNetStreamMetrics, bitrateMultiplier:Number = 1.15)
{
super(metrics);
this.bitrateMultiplier = bitrateMultiplier;
}
override public function getNewIndex() : int
{
var moreDetail:String = null;
var i:int = 0;
var newIndex:int = -1;
if(this.rtmpMetrics.averageMaxBytesPerSecond != 0)
{
for(i = this.rtmpMetrics.currentIndex; i >= 0; i--)
{
if(this.rtmpMetrics.averageMaxBytesPerSecond * 8 / 1024 > this.rtmpMetrics.resource.streamItems[i].bitrate * this.bitrateMultiplier)
{
newIndex = i;
break;
}
}
newIndex = newIndex == this.rtmpMetrics.currentIndex ? -1 : newIndex;
}
return newIndex;
}
private function get rtmpMetrics() : RTMPNetStreamMetrics
{
return metrics as RTMPNetStreamMetrics;
}
}
}
@@ -0,0 +1,60 @@
package org.osmf.net.rtmpstreaming
{
import flash.events.NetStatusEvent;
import org.osmf.net.NetStreamCodes;
import org.osmf.net.SwitchingRuleBase;
public class InsufficientBufferRule extends SwitchingRuleBase
{
private var _panic:Boolean;
private var _moreDetail:String;
private var minBufferLength:Number;
public function InsufficientBufferRule(metrics:RTMPNetStreamMetrics, minBufferLength:Number = 2)
{
super(metrics);
this._panic = false;
this.minBufferLength = minBufferLength;
metrics.netStream.addEventListener(NetStatusEvent.NET_STATUS,this.monitorNetStatus,false,0,true);
}
override public function getNewIndex() : int
{
var newIndex:int = -1;
if(this._panic || this.rtmpMetrics.netStream.bufferLength < this.minBufferLength && this.rtmpMetrics.netStream.bufferLength > this.rtmpMetrics.netStream.bufferTime)
{
newIndex = 0;
}
return newIndex;
}
private function monitorNetStatus(e:NetStatusEvent) : void
{
switch(e.info.code)
{
case NetStreamCodes.NETSTREAM_BUFFER_FULL:
this._panic = false;
break;
case NetStreamCodes.NETSTREAM_BUFFER_EMPTY:
if(Math.round(this.rtmpMetrics.netStream.time) != 0)
{
this._panic = true;
this._moreDetail = "Buffer was empty";
}
break;
case NetStreamCodes.NETSTREAM_PLAY_INSUFFICIENTBW:
this._panic = true;
this._moreDetail = "Stream had insufficient bandwidth";
}
}
private function get rtmpMetrics() : RTMPNetStreamMetrics
{
return metrics as RTMPNetStreamMetrics;
}
}
}
@@ -0,0 +1,76 @@
package org.osmf.net.rtmpstreaming
{
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import flash.net.NetStreamPlayTransitions;
import org.osmf.media.MediaResourceBase;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.NetConnectionFactoryBase;
import org.osmf.net.NetLoader;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.net.NetStreamSwitchManager;
import org.osmf.net.NetStreamSwitchManagerBase;
import org.osmf.net.NetStreamUtils;
import org.osmf.net.SwitchingRuleBase;
public class RTMPDynamicStreamingNetLoader extends NetLoader
{
public function RTMPDynamicStreamingNetLoader(factory:NetConnectionFactoryBase = null)
{
super(factory);
}
override public function canHandleResource(resource:MediaResourceBase) : Boolean
{
var dsResource:DynamicStreamingResource = resource as DynamicStreamingResource;
return dsResource != null && NetStreamUtils.isRTMPStream(dsResource.host) || Boolean(super.canHandleResource(resource));
}
override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource) : NetStreamSwitchManagerBase
{
var metrics:RTMPNetStreamMetrics = null;
if(dsResource != null)
{
metrics = new RTMPNetStreamMetrics(netStream);
return new NetStreamSwitchManager(connection,netStream,dsResource,metrics,this.getDefaultSwitchingRules(metrics));
}
return null;
}
private function getDefaultSwitchingRules(metrics:RTMPNetStreamMetrics) : Vector.<SwitchingRuleBase>
{
var rules:Vector.<SwitchingRuleBase> = new Vector.<SwitchingRuleBase>();
rules.push(new SufficientBandwidthRule(metrics));
rules.push(new InsufficientBandwidthRule(metrics));
rules.push(new DroppedFramesRule(metrics));
rules.push(new InsufficientBufferRule(metrics));
return rules;
}
override protected function reconnectStream(loadTrait:NetStreamLoadTrait) : void
{
var nsPlayOptions:NetStreamPlayOptions = null;
var currentStreamItem:DynamicStreamingItem = null;
var streamName:String = null;
var dsResource:DynamicStreamingResource = loadTrait.resource as DynamicStreamingResource;
if(dsResource == null)
{
super.reconnectStream(loadTrait);
}
else
{
nsPlayOptions = new NetStreamPlayOptions();
loadTrait.netStream.attach(loadTrait.connection);
nsPlayOptions.transition = NetStreamPlayTransitions.RESUME;
currentStreamItem = dsResource.streamItems[loadTrait.switchManager.currentIndex];
streamName = currentStreamItem.streamName;
nsPlayOptions.streamName = streamName;
loadTrait.netStream.play2(nsPlayOptions);
}
}
}
}
@@ -0,0 +1,63 @@
package org.osmf.net.rtmpstreaming
{
import flash.net.NetStream;
import org.osmf.net.NetStreamMetricsBase;
import org.osmf.net.StreamType;
public class RTMPNetStreamMetrics extends NetStreamMetricsBase
{
private static const DEFAULT_AVG_MAX_BYTES_SAMPLE_SIZE:Number = 50;
private var _averageMaxBytesPerSecondArray:Array;
private var _averageMaxBytesPerSecond:Number;
public function RTMPNetStreamMetrics(netStream:NetStream)
{
super(netStream);
this._averageMaxBytesPerSecondArray = new Array();
}
public function get averageMaxBytesPerSecond() : Number
{
return this._averageMaxBytesPerSecond;
}
override protected function calculateMetrics() : void
{
var maxBytesPerSecond:Number = NaN;
var totalMaxBytesPerSecond:Number = NaN;
var peakMaxBytesPerSecond:Number = NaN;
var b:uint = 0;
super.calculateMetrics();
try
{
maxBytesPerSecond = netStream.info.maxBytesPerSecond;
this._averageMaxBytesPerSecondArray.unshift(maxBytesPerSecond);
if(this._averageMaxBytesPerSecondArray.length > DEFAULT_AVG_MAX_BYTES_SAMPLE_SIZE)
{
this._averageMaxBytesPerSecondArray.pop();
}
totalMaxBytesPerSecond = 0;
peakMaxBytesPerSecond = 0;
for(b = 0; b < this._averageMaxBytesPerSecondArray.length; b++)
{
totalMaxBytesPerSecond += this._averageMaxBytesPerSecondArray[b];
peakMaxBytesPerSecond = this._averageMaxBytesPerSecondArray[b] > peakMaxBytesPerSecond ? Number(this._averageMaxBytesPerSecondArray[b]) : peakMaxBytesPerSecond;
}
this._averageMaxBytesPerSecond = this._averageMaxBytesPerSecondArray.length < DEFAULT_AVG_MAX_BYTES_SAMPLE_SIZE ? 0 : (this.isLive ? peakMaxBytesPerSecond : totalMaxBytesPerSecond / this._averageMaxBytesPerSecondArray.length);
}
catch(error:Error)
{
throw error;
}
}
private function get isLive() : Boolean
{
return Boolean(resource) && resource.streamType == StreamType.LIVE;
}
}
}
@@ -0,0 +1,50 @@
package org.osmf.net.rtmpstreaming
{
import org.osmf.net.SwitchingRuleBase;
public class SufficientBandwidthRule extends SwitchingRuleBase
{
private static const BANDWIDTH_SAFETY_MULTIPLE:Number = 1.15;
private static const MIN_DROPPED_FPS:int = 2;
public function SufficientBandwidthRule(metrics:RTMPNetStreamMetrics)
{
super(metrics);
}
override public function getNewIndex() : int
{
var moreDetail:String = null;
var i:int = 0;
var newIndex:int = -1;
if(this.rtmpMetrics.averageMaxBytesPerSecond != 0)
{
for(i = this.rtmpMetrics.resource.streamItems.length - 1; i >= 0; i--)
{
if(this.rtmpMetrics.averageMaxBytesPerSecond * 8 / 1024 > this.rtmpMetrics.resource.streamItems[i].bitrate * BANDWIDTH_SAFETY_MULTIPLE)
{
newIndex = i;
break;
}
}
if(newIndex > this.rtmpMetrics.currentIndex)
{
newIndex = this.rtmpMetrics.droppedFPS < MIN_DROPPED_FPS && this.rtmpMetrics.netStream.bufferLength > this.rtmpMetrics.netStream.bufferTime ? newIndex : -1;
}
else
{
newIndex = -1;
}
}
return newIndex;
}
private function get rtmpMetrics() : RTMPNetStreamMetrics
{
return metrics as RTMPNetStreamMetrics;
}
}
}