PageRenderTime 112ms CodeModel.GetById 43ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/blogs.dir/2/files/2011/02/20110220-dancemarathon/SatPM/com/greensock/loading/VideoLoader.as

https://github.com/digitalstrategyworks/Reese-WordPress
ActionScript | 521 lines | 203 code | 29 blank | 289 comment | 44 complexity | 050980cd8f10d2c3017c46200996db40 MD5 | raw file
  1. /**
  2. * VERSION: 1.767
  3. * DATE: 2010-12-17
  4. * AS3
  5. * UPDATES AND DOCS AT: http://www.greensock.com/loadermax/
  6. **/
  7. package com.greensock.loading {
  8. import com.greensock.events.LoaderEvent;
  9. import com.greensock.loading.core.LoaderItem;
  10. import com.greensock.loading.display.ContentDisplay;
  11. import flash.display.Sprite;
  12. import flash.events.Event;
  13. import flash.events.NetStatusEvent;
  14. import flash.events.ProgressEvent;
  15. import flash.events.TimerEvent;
  16. import flash.media.SoundTransform;
  17. import flash.media.Video;
  18. import flash.net.NetConnection;
  19. import flash.net.NetStream;
  20. import flash.utils.Timer;
  21. import flash.utils.getTimer;
  22. /** Dispatched when the loader's <code>httpStatus</code> value changes. **/
  23. [Event(name="httpStatus", type="com.greensock.events.LoaderEvent")]
  24. /** Dispatched when the <code>netStream</code> dispatches a NET_STATUS event. **/
  25. [Event(name="netStatus", type="flash.events.NetStatusEvent")]
  26. /**
  27. * Loads an FLV, F4V, or MP4 video file using a NetStream and also provides convenient playback methods
  28. * and properties like <code>pauseVideo(), playVideo(), gotoVideoTime(), bufferProgress, playProgress, volume,
  29. * duration, videoPaused, metaData, </code> and <code>videoTime</code>. Just like ImageLoader and SWFLoader,
  30. * VideoLoader's <code>content</code> property refers to a <code>ContentDisplay</code> object (Sprite) that
  31. * gets created immediately so that you can position/scale/rotate it or add ROLL_OVER/ROLL_OUT/CLICK listeners
  32. * before (or while) the video loads. Use the VideoLoader's <code>content</code> property to get the ContentDisplay
  33. * Sprite, or use the <code>rawContent</code> property to get the <code>Video</code> object that is used inside the
  34. * ContentDisplay to display the video. If a <code>container</code> is defined in the <code>vars</code> object,
  35. * the ContentDisplay will immediately be added to that container).<br /><br />
  36. *
  37. * You don't need to worry about creating a NetConnection, a Video object, attaching the NetStream, or any
  38. * of the typical hassles. VideoLoader can even scale the video into the area you specify using scaleModes
  39. * like <code>"stretch", "proportionalInside", "proportionalOutside",</code> and more. A VideoLoader will
  40. * dispatch useful events like <code>VIDEO_COMPLETE, VIDEO_PAUSE, VIDEO_PLAY, VIDEO_BUFFER_FULL,
  41. * VIDEO_BUFFER_EMPTY, NET_STATUS, VIDEO_CUE_POINT</code>, and <code>PLAY_PROGRESS</code> in addition
  42. * to the typical loader events, making it easy to hook up your own control interface. It packs a
  43. * surprising amount of functionality into a very small amount of kb.<br /><br />
  44. *
  45. * <strong>OPTIONAL VARS PROPERTIES</strong><br />
  46. * The following special properties can be passed into the VideoLoader constructor via its <code>vars</code>
  47. * parameter which can be either a generic object or a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> object:<br />
  48. * <ul>
  49. * <li><strong> name : String</strong> - A name that is used to identify the VideoLoader instance. This name can be fed to the <code>LoaderMax.getLoader()</code> or <code>LoaderMax.getContent()</code> methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".</li>
  50. * <li><strong> bufferTime : Number</strong> - The amount of time (in seconds) that should be buffered before the video can begin playing (set <code>autoPlay</code> to <code>false</code> to pause the video initially).</li>
  51. * <li><strong> autoPlay : Boolean</strong> - By default, the video will begin playing as soon as it has been adequately buffered, but to prevent it from playing initially, set <code>autoPlay</code> to <code>false</code>.</li>
  52. * <li><strong> smoothing : Boolean</strong> - When <code>smoothing</code> is <code>true</code> (the default), smoothing will be enabled for the video which typically leads to better scaling results.</li>
  53. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  54. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  55. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  56. * <li><strong> centerRegistration : Boolean </strong> - if <code>true</code>, the registration point will be placed in the center of the <code>ContentDisplay</code> which can be useful if, for example, you want to animate its scale and have it grow/shrink from its center.</li>
  57. * <li><strong> scaleMode : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>scaleMode</code> controls how the video will be scaled to fit the area. The following values are recognized (you may use the <code>com.greensock.layout.ScaleMode</code> constants if you prefer):
  58. * <ul>
  59. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  60. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  61. * <li><code>"proportionalOutside"</code> - The video will be scaled proportionally to completely fill the area, allowing portions of it to exceed the bounds defined by the width/height.</li>
  62. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  63. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  64. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  65. * </ul></li>
  66. * <li><strong> hAlign : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>hAlign</code> determines how the video is horizontally aligned within that area. The following values are recognized (you may use the <code>com.greensock.layout.AlignMode</code> constants if you prefer):
  67. * <ul>
  68. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  69. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  70. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  71. * </ul></li>
  72. * <li><strong> vAlign : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>vAlign</code> determines how the video is vertically aligned within that area. The following values are recognized (you may use the <code>com.greensock.layout.AlignMode</code> constants if you prefer):
  73. * <ul>
  74. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  75. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  76. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  77. * </ul></li>
  78. * <li><strong> crop : Boolean</strong> - When a <code>width</code> and <code>height</code> are defined, setting <code>crop</code> to <code>true</code> will cause the video to be cropped within that area (by applying a <code>scrollRect</code> for maximum performance). This is typically useful when the <code>scaleMode</code> is <code>"proportionalOutside"</code> or <code>"none"</code> so that any parts of the video that exceed the dimensions defined by <code>width</code> and <code>height</code> are visually chopped off. Use the <code>hAlign</code> and <code>vAlign</code> special properties to control the vertical and horizontal alignment within the cropped area.</li>
  79. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  80. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  81. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  82. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  83. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  84. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  85. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  86. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  87. * <li><strong> bgColor : uint </strong> - When a <code>width</code> and <code>height</code> are defined, a rectangle will be drawn inside the <code>ContentDisplay</code> immediately in order to ease the development process. It is transparent by default, but you may define a <code>bgAlpha</code> if you prefer.</li>
  88. * <li><strong> bgAlpha : Number </strong> - Controls the alpha of the rectangle that is drawn when a <code>width</code> and <code>height</code> are defined.</li>
  89. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  90. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  91. * <li><strong> checkPolicyFile : Boolean</strong> - If <code>true</code>, the VideoLoader will check for a crossdomain.xml file on the remote host (only useful when loading videos from other domains - see Adobe's docs for details about NetStream's <code>checkPolicyFile</code> property). </li>
  92. * <li><strong> estimatedDuration : Number</strong> - Estimated duration of the video in seconds. VideoLoader will only use this value until it receives the necessary metaData from the video in order to accurately determine the video's duration. You do not need to specify an <code>estimatedDuration</code>, but doing so can help make the playProgress and some other values more accurate (until the metaData has loaded). It can also make the <code>progress/bytesLoaded/bytesTotal</code> more accurate when a <code>estimatedDuration</code> is defined, particularly in <code>bufferMode</code>.</li>
  93. * <li><strong> deblocking : int</strong> - Indicates the type of filter applied to decoded video as part of post-processing. The default value is 0, which lets the video compressor apply a deblocking filter as needed. See Adobe's <code>flash.media.Video</code> class docs for details.</li>
  94. * <li><strong> bufferMode : Boolean </strong> - When <code>true</code>, the loader will report its progress only in terms of the video's buffer which can be very convenient if, for example, you want to display loading progress for the video's buffer or tuck it into a LoaderMax with other loaders and allow the LoaderMax to dispatch its <code>COMPLETE</code> event when the buffer is full instead of waiting for the whole file to download. When <code>bufferMode</code> is <code>true</code>, the VideoLoader will dispatch its <code>COMPLETE</code> event when the buffer is full as opposed to waiting for the entire video to load. You can toggle the <code>bufferMode</code> anytime. Please read the full <code>bufferMode</code> property ASDoc description below for details about how it affects things like <code>bytesTotal</code>.</li>
  95. * <li><strong> autoAdjustBuffer : Boolean </strong> If the buffer becomes empty during playback and <code>autoAdjustBuffer</code> is <code>true</code> (the default), it will automatically attempt to adjust the NetStream's <code>bufferTime</code> based on the rate at which the video has been loading, estimating what it needs to be in order to play the rest of the video without emptying the buffer again. This can prevent the annoying problem of video playback start/stopping/starting/stopping on a system tht doesn't have enough bandwidth to adequately buffer the video. You may also set the <code>bufferTime</code> in the constructor's <code>vars</code> parameter to set the initial value.</li>
  96. * <li><strong> alternateURL : String</strong> - If you define an <code>alternateURL</code>, the loader will initially try to load from its original <code>url</code> and if it fails, it will automatically (and permanently) change the loader's <code>url</code> to the <code>alternateURL</code> and try again. Think of it as a fallback or backup <code>url</code>. It is perfectly acceptable to use the same <code>alternateURL</code> for multiple loaders (maybe a default image for various ImageLoaders for example).</li>
  97. * <li><strong> noCache : Boolean</strong> - If <code>noCache</code> is <code>true</code>, a "gsCacheBusterID" parameter will be appended to the url with a random set of numbers to prevent caching (don't worry, this info is ignored when you <code>getLoader()</code> or <code>getContent()</code> by url and when you're running locally)</li>
  98. * <li><strong> estimatedBytes : uint</strong> - Initially, the loader's <code>bytesTotal</code> is set to the <code>estimatedBytes</code> value (or <code>LoaderMax.defaultEstimatedBytes</code> if one isn't defined). Then, when the loader begins loading and it can accurately determine the bytesTotal, it will do so. Setting <code>estimatedBytes</code> is optional, but the more accurate the value, the more accurate your loaders' overall progress will be initially. If the loader will be inserted into a LoaderMax instance (for queue management), its <code>auditSize</code> feature can attempt to automatically determine the <code>bytesTotal</code> at runtime (there is a slight performance penalty for this, however - see LoaderMax's documentation for details).</li>
  99. * <li><strong> requireWithRoot : DisplayObject</strong> - LoaderMax supports <i>subloading</i>, where an object can be factored into a parent's loading progress. If you want LoaderMax to require this VideoLoader as part of its parent SWFLoader's progress, you must set the <code>requireWithRoot</code> property to your swf's <code>root</code>. For example, <code>var loader:VideoLoader = new VideoLoader("myScript.php", {name:"textData", requireWithRoot:this.root});</code></li>
  100. * <li><strong> autoDispose : Boolean</strong> - When <code>autoDispose</code> is <code>true</code>, the loader will be disposed immediately after it completes (it calls the <code>dispose()</code> method internally after dispatching its <code>COMPLETE</code> event). This will remove any listeners that were defined in the vars object (like onComplete, onProgress, onError, onInit). Once a loader is disposed, it can no longer be found with <code>LoaderMax.getLoader()</code> or <code>LoaderMax.getContent()</code> - it is essentially destroyed but its content is not unloaded (you must call <code>unload()</code> or <code>dispose(true)</code> to unload its content). The default <code>autoDispose</code> value is <code>false</code>.
  101. *
  102. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  103. * <li><strong> onOpen : Function</strong> - A handler function for <code>LoaderEvent.OPEN</code> events which are dispatched when the loader begins loading. Make sure your onOpen function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  104. * <li><strong> onInit : Function</strong> - A handler function for <code>Event.INIT</code> events which will be called when the video's metaData has been received and the video is placed into the <code>ContentDisplay</code>. Make sure your onInit function accepts a single parameter of type <code>Event</code> (flash.events.Event).</li>
  105. * <li><strong> onProgress : Function</strong> - A handler function for <code>LoaderEvent.PROGRESS</code> events which are dispatched whenever the <code>bytesLoaded</code> changes. Make sure your onProgress function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>). You can use the LoaderEvent's <code>target.progress</code> to get the loader's progress value or use its <code>target.bytesLoaded</code> and <code>target.bytesTotal</code>.</li>
  106. * <li><strong> onComplete : Function</strong> - A handler function for <code>LoaderEvent.COMPLETE</code> events which are dispatched when the loader has finished loading successfully. Make sure your onComplete function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  107. * <li><strong> onCancel : Function</strong> - A handler function for <code>LoaderEvent.CANCEL</code> events which are dispatched when loading is aborted due to either a failure or because another loader was prioritized or <code>cancel()</code> was manually called. Make sure your onCancel function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  108. * <li><strong> onError : Function</strong> - A handler function for <code>LoaderEvent.ERROR</code> events which are dispatched whenever the loader experiences an error (typically an IO_ERROR). An error doesn't necessarily mean the loader failed, however - to listen for when a loader fails, use the <code>onFail</code> special property. Make sure your onError function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  109. * <li><strong> onFail : Function</strong> - A handler function for <code>LoaderEvent.FAIL</code> events which are dispatched whenever the loader fails and its <code>status</code> changes to <code>LoaderStatus.FAILED</code>. Make sure your onFail function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  110. * <li><strong> onIOError : Function</strong> - A handler function for <code>LoaderEvent.IO_ERROR</code> events which will also call the onError handler, so you can use that as more of a catch-all whereas <code>onIOError</code> is specifically for LoaderEvent.IO_ERROR events. Make sure your onIOError function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  111. * </ul><br />
  112. *
  113. * <strong>Note:</strong> Using a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> instance
  114. * instead of a generic object to define your <code>vars</code> is a bit more verbose but provides
  115. * code hinting and improved debugging because it enforces strict data typing. Use whichever one you prefer.<br /><br />
  116. *
  117. * <strong>Note:</strong> To avoid garbage collection issues in the Flash player, the <code>netStream</code>
  118. * object that VideoLoader employs must get recreated internally anytime the VideoLoader is unloaded or its loading
  119. * is cancelled, so if you need to directly access the <code>netStream</code>, it is best to do so <strong>after</strong>
  120. * the <code>COMPLETE</code> event has been dispatched. Otherwise, if you store a reference to the VideoLoader's
  121. * <code>netStream</code> before or during a load and it gets cancelled or unloaded for some reason, it won't reference
  122. * the one that was used to load the video.<br /><br />
  123. *
  124. * @example Example AS3 code:<listing version="3.0">
  125. import com.greensock.loading.~~;
  126. import com.greensock.loading.display.~~;
  127. import com.greensock.~~;
  128. import com.greensock.events.LoaderEvent;
  129. //create a VideoLoader
  130. var video:VideoLoader = new VideoLoader("assets/video.flv", {name:"myVideo", container:this, width:400, height:300, scaleMode:"proportionalInside", bgColor:0x000000, autoPlay:false, volume:0, requireWithRoot:this.root, estimatedBytes:75000});
  131. //start loading
  132. video.load();
  133. //add a CLICK listener to a button that causes the video to toggle its paused state.
  134. button.addEventListener(MouseEvent.CLICK, togglePause);
  135. function togglePause(event:MouseEvent):void {
  136. video.videoPaused = !video.videoPaused;
  137. }
  138. //or you could put the VideoLoader into a LoaderMax queue. Create one first...
  139. var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
  140. //append the VideoLoader and several other loaders
  141. queue.append( video );
  142. queue.append( new DataLoader("assets/data.txt", {name:"myText"}) );
  143. queue.append( new ImageLoader("assets/image1.png", {name:"myImage", estimatedBytes:3500}) );
  144. //start loading the LoaderMax queue
  145. queue.load();
  146. function progressHandler(event:LoaderEvent):void {
  147. trace("progress: " + event.target.progress);
  148. }
  149. function completeHandler(event:LoaderEvent):void {
  150. //play the video
  151. loader.playVideo();
  152. //tween the volume up to 1 over the course of 2 seconds.
  153. TweenLite.to(loader, 2, {volume:1});
  154. }
  155. function errorHandler(event:LoaderEvent):void {
  156. trace("error occured with " + event.target + ": " + event.text);
  157. }
  158. </listing>
  159. *
  160. * <b>Copyright 2010, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
  161. *
  162. * @see com.greensock.loading.data.VideoLoaderVars
  163. *
  164. * @author Jack Doyle, jack@greensock.com
  165. */
  166. public class VideoLoader extends LoaderItem {
  167. /** @private **/
  168. private static var _classActivated:Boolean = _activateClass("VideoLoader", VideoLoader, "flv,f4v,mp4,mov");
  169. /** Event type constant for when the video completes. **/
  170. public static const VIDEO_COMPLETE:String="videoComplete";
  171. /** Event type constant for when the video's buffer is full. **/
  172. public static const VIDEO_BUFFER_FULL:String="videoBufferFull";
  173. /** Event type constant for when the video's buffer is empty. **/
  174. public static const VIDEO_BUFFER_EMPTY:String="videoBufferEmpty";
  175. /** Event type constant for when the video is paused. **/
  176. public static const VIDEO_PAUSE:String="videoPause";
  177. /** Event type constant for when the video begins or resumes playing. If the buffer isn't full yet when VIDEO_PLAY is dispatched, the video will wait to visually begin playing until the buffer is full. So VIDEO_PLAY indicates when the NetStream received an instruction to play, not necessarily when it visually begins playing. **/
  178. public static const VIDEO_PLAY:String="videoPlay";
  179. /** Event type constant for when the video reaches a cue point in the playback of the NetStream. **/
  180. public static const VIDEO_CUE_POINT:String="videoCuePoint";
  181. /** Event type constant for when the playback progresses (only dispatched when the video is playing). **/
  182. public static const PLAY_PROGRESS:String="playProgress";
  183. /** @private **/
  184. protected var _ns:NetStream;
  185. /** @private **/
  186. protected var _nc:NetConnection;
  187. /** @private **/
  188. protected var _video:Video;
  189. /** @private **/
  190. protected var _sound:SoundTransform;
  191. /** @private **/
  192. protected var _videoPaused:Boolean;
  193. /** @private **/
  194. protected var _videoComplete:Boolean;
  195. /** @private **/
  196. protected var _forceTime:Number;
  197. /** @private **/
  198. protected var _duration:Number;
  199. /** @private **/
  200. protected var _pausePending:Boolean;
  201. /** @private **/
  202. protected var _volume:Number;
  203. /** @private **/
  204. protected var _sprite:Sprite;
  205. /** @private **/
  206. protected var _initted:Boolean;
  207. /** @private **/
  208. protected var _bufferMode:Boolean;
  209. /** @private **/
  210. protected var _repeatCount:uint;
  211. /** @private **/
  212. protected var _bufferFull:Boolean;
  213. /** @private **/
  214. protected var _dispatchPlayProgress:Boolean;
  215. /** @private **/
  216. protected var _prevTime:Number;
  217. /** @private **/
  218. protected var _firstCuePoint:CuePoint;
  219. /** @private due to a bug in the NetStream class, we cannot seek() or pause() before the NetStream has dispatched a RENDER Event (or the NetStream.Buffer.Full status event is received for Flash Player 9). **/
  220. protected var _renderedOnce:Boolean;
  221. /** @private primarily used for FP9 to work around a Flash bug with seek() and pause() (see the _onBufferFull() method for note). **/
  222. protected var _timer:Timer = new Timer(50, 1);
  223. /** The metaData that was received from the video (contains information about its width, height, frame rate, etc.). See Adobe's docs for information about a NetStream's onMetaData callback. **/
  224. public var metaData:Object;
  225. /** If the buffer becomes empty during playback and <code>autoAdjustBuffer</code> is <code>true</code> (the default), it will automatically attempt to adjust the NetStream's <code>bufferTime</code> based on the rate at which the video has been loading, estimating what it needs to be in order to play the rest of the video without emptying the buffer again. This can prevent the annoying problem of video playback start/stopping/starting/stopping on a system tht doesn't have enough bandwidth to adequately buffer the video. You may also set the <code>bufferTime</code> in the constructor's <code>vars</code> parameter to set the initial value. **/
  226. public var autoAdjustBuffer:Boolean;
  227. /**
  228. * Constructor
  229. *
  230. * @param urlOrRequest The url (<code>String</code>) or <code>URLRequest</code> from which the loader should get its content.
  231. * @param vars An object containing optional configuration details. For example: <code>new VideoLoader("video/video.flv", {name:"myVideo", onComplete:completeHandler, onProgress:progressHandler})</code>.<br /><br />
  232. *
  233. * The following special properties can be passed into the constructor via the <code>vars</code> parameter
  234. * which can be either a generic object or a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> object:<br />
  235. * <ul>
  236. * <li><strong> name : String</strong> - A name that is used to identify the VideoLoader instance. This name can be fed to the <code>LoaderMax.getLoader()</code> or <code>LoaderMax.getContent()</code> methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".</li>
  237. * <li><strong> bufferTime : Number</strong> - The amount of time (in seconds) that should be buffered before the video can begin playing (set <code>autoPlay</code> to <code>false</code> to pause the video initially).</li>
  238. * <li><strong> autoPlay : Boolean</strong> - By default, the video will begin playing as soon as it has been adequately buffered, but to prevent it from playing initially, set <code>autoPlay</code> to <code>false</code>.</li>
  239. * <li><strong> smoothing : Boolean</strong> - When <code>smoothing</code> is <code>true</code> (the default), smoothing will be enabled for the video which typically leads to better scaling results.</li>
  240. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  241. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  242. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  243. * <li><strong> centerRegistration : Boolean </strong> - if <code>true</code>, the registration point will be placed in the center of the <code>ContentDisplay</code> which can be useful if, for example, you want to animate its scale and have it grow/shrink from its center.</li>
  244. * <li><strong> scaleMode : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>scaleMode</code> controls how the video will be scaled to fit the area. The following values are recognized (you may use the <code>com.greensock.layout.ScaleMode</code> constants if you prefer):
  245. * <ul>
  246. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  247. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  248. * <li><code>"proportionalOutside"</code> - The video will be scaled proportionally to completely fill the area, allowing portions of it to exceed the bounds defined by the width/height.</li>
  249. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  250. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  251. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  252. * </ul></li>
  253. * <li><strong> hAlign : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>hAlign</code> determines how the video is horizontally aligned within that area. The following values are recognized (you may use the <code>com.greensock.layout.AlignMode</code> constants if you prefer):
  254. * <ul>
  255. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  256. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  257. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  258. * </ul></li>
  259. * <li><strong> vAlign : String </strong> - When a <code>width</code> and <code>height</code> are defined, the <code>vAlign</code> determines how the video is vertically aligned within that area. The following values are recognized (you may use the <code>com.greensock.layout.AlignMode</code> constants if you prefer):
  260. * <ul>
  261. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  262. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  263. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  264. * </ul></li>
  265. * <li><strong> crop : Boolean</strong> - When a <code>width</code> and <code>height</code> are defined, setting <code>crop</code> to <code>true</code> will cause the video to be cropped within that area (by applying a <code>scrollRect</code> for maximum performance). This is typically useful when the <code>scaleMode</code> is <code>"proportionalOutside"</code> or <code>"none"</code> so that any parts of the video that exceed the dimensions defined by <code>width</code> and <code>height</code> are visually chopped off. Use the <code>hAlign</code> and <code>vAlign</code> special properties to control the vertical and horizontal alignment within the cropped area.</li>
  266. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  267. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  268. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  269. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  270. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  271. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  272. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  273. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  274. * <li><strong> bgColor : uint </strong> - When a <code>width</code> and <code>height</code> are defined, a rectangle will be drawn inside the <code>ContentDisplay</code> immediately in order to ease the development process. It is transparent by default, but you may define a <code>bgAlpha</code> if you prefer.</li>
  275. * <li><strong> bgAlpha : Number </strong> - Controls the alpha of the rectangle that is drawn when a <code>width</code> and <code>height</code> are defined.</li>
  276. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  277. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  278. * <li><strong> checkPolicyFile : Boolean</strong> - If <code>true</code>, the VideoLoader will check for a crossdomain.xml file on the remote host (only useful when loading videos from other domains - see Adobe's docs for details about NetStream's <code>checkPolicyFile</code> property). </li>
  279. * <li><strong> estimatedDuration : Number</strong> - Estimated duration of the video in seconds. VideoLoader will only use this value until it receives the necessary metaData from the video in order to accurately determine the video's duration. You do not need to specify an <code>estimatedDuration</code>, but doing so can help make the playProgress and some other values more accurate (until the metaData has loaded). It can also make the <code>progress/bytesLoaded/bytesTotal</code> more accurate when a <code>estimatedDuration</code> is defined, particularly in <code>bufferMode</code>.</li>
  280. * <li><strong> deblocking : int</strong> - Indicates the type of filter applied to decoded video as part of post-processing. The default value is 0, which lets the video compressor apply a deblocking filter as needed. See Adobe's <code>flash.media.Video</code> class docs for details.</li>
  281. * <li><strong> bufferMode : Boolean </strong> - When <code>true</code>, the loader will report its progress only in terms of the video's buffer which can be very convenient if, for example, you want to display loading progress for the video's buffer or tuck it into a LoaderMax with other loaders and allow the LoaderMax to dispatch its <code>COMPLETE</code> event when the buffer is full instead of waiting for the whole file to download. When <code>bufferMode</code> is <code>true</code>, the VideoLoader will dispatch its <code>COMPLETE</code> event when the buffer is full as opposed to waiting for the entire video to load. You can toggle the <code>bufferMode</code> anytime. Please read the full <code>bufferMode</code> property ASDoc description below for details about how it affects things like <code>bytesTotal</code>.</li>
  282. * <li><strong> autoAdjustBuffer : Boolean </strong> If the buffer becomes empty during playback and <code>autoAdjustBuffer</code> is <code>true</code> (the default), it will automatically attempt to adjust the NetStream's <code>bufferTime</code> based on the rate at which the video has been loading, estimating what it needs to be in order to play the rest of the video without emptying the buffer again. This can prevent the annoying problem of video playback start/stopping/starting/stopping on a system tht doesn't have enough bandwidth to adequately buffer the video. You may also set the <code>bufferTime</code> in the constructor's <code>vars</code> parameter to set the initial value.</li>
  283. * <li><strong> alternateURL : String</strong> - If you define an <code>alternateURL</code>, the loader will initially try to load from its original <code>url</code> and if it fails, it will automatically (and permanently) change the loader's <code>url</code> to the <code>alternateURL</code> and try again. Think of it as a fallback or backup <code>url</code>. It is perfectly acceptable to use the same <code>alternateURL</code> for multiple loaders (maybe a default image for various ImageLoaders for example).</li>
  284. * <li><strong> noCache : Boolean</strong> - If <code>noCache</code> is <code>true</code>, a "gsCacheBusterID" parameter will be appended to the url with a random set of numbers to prevent caching (don't worry, this info is ignored when you <code>getLoader()</code> or <code>getContent()</code> by url and when you're running locally)</li>
  285. * <li><strong> estimatedBytes : uint</strong> - Initially, the loader's <code>bytesTotal</code> is set to the <code>estimatedBytes</code> value (or <code>LoaderMax.defaultEstimatedBytes</code> if one isn't defined). Then, when the loader begins loading and it can accurately determine the bytesTotal, it will do so. Setting <code>estimatedBytes</code> is optional, but the more accurate the value, the more accurate your loaders' overall progress will be initially. If the loader will be inserted into a LoaderMax instance (for queue management), its <code>auditSize</code> feature can attempt to automatically determine the <code>bytesTotal</code> at runtime (there is a slight performance penalty for this, however - see LoaderMax's documentation for details).</li>
  286. * <li><strong> requireWithRoot : DisplayObject</strong> - LoaderMax supports <i>subloading</i>, where an object can be factored into a parent's loading progress. If you want LoaderMax to require this VideoLoader as part of its parent SWFLoader's progress, you must set the <code>requireWithRoot</code> property to your swf's <code>root</code>. For example, <code>var loader:VideoLoader = new VideoLoader("myScript.php", {name:"textData", requireWithRoot:this.root});</code></li>
  287. * <li><strong> autoDispose : Boolean</strong> - When <code>autoDispose</code> is <code>true</code>, the loader will be disposed immediately after it completes (it calls the <code>dispose()</code> method internally after dispatching its <code>COMPLETE</code> event). This will remove any listeners that were defined in the vars object (like onComplete, onProgress, onError, onInit). Once a loader is disposed, it can no longer be found with <code>LoaderMax.getLoader()</code> or <code>LoaderMax.getContent()</code> - it is essentially destroyed but its content is not unloaded (you must call <code>unload()</code> or <code>dispose(true)</code> to unload its content). The default <code>autoDispose</code> value is <code>false</code>.
  288. *
  289. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  290. * <li><strong> onOpen : Function</strong> - A handler function for <code>LoaderEvent.OPEN</code> events which are dispatched when the loader begins loading. Make sure your onOpen function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  291. * <li><strong> onInit : Function</strong> - A handler function for <code>Event.INIT</code> events which will be called when the video's metaData has been received and the video is placed into the <code>ContentDisplay</code>. Make sure your onInit function accepts a single parameter of type <code>Event</code> (flash.events.Event).</li>
  292. * <li><strong> onProgress : Function</strong> - A handler function for <code>LoaderEvent.PROGRESS</code> events which are dispatched whenever the <code>bytesLoaded</code> changes. Make sure your onProgress function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>). You can use the LoaderEvent's <code>target.progress</code> to get the loader's progress value or use its <code>target.bytesLoaded</code> and <code>target.bytesTotal</code>.</li>
  293. * <li><strong> onComplete : Function</strong> - A handler function for <code>LoaderEvent.COMPLETE</code> events which are dispatched when the loader has finished loading successfully. Make sure your onComplete function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  294. * <li><strong> onCancel : Function</strong> - A handler function for <code>LoaderEvent.CANCEL</code> events which are dispatched when loading is aborted due to either a failure or because another loader was prioritized or <code>cancel()</code> was manually called. Make sure your onCancel function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  295. * <li><strong> onError : Function</strong> - A handler function for <code>LoaderEvent.ERROR</code> events which are dispatched whenever the loader experiences an error (typically an IO_ERROR). An error doesn't necessarily mean the loader failed, however - to listen for when a loader fails, use the <code>onFail</code> special property. Make sure your onError function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  296. * <li><strong> onFail : Function</strong> - A handler function for <code>LoaderEvent.FAIL</code> events which are dispatched whenever the loader fails and its <code>status</code> changes to <code>LoaderStatus.FAILED</code>. Make sure your onFail function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  297. * <li><strong> onIOError : Function</strong> - A handler function for <code>LoaderEvent.IO_ERROR</code> events which will also call the onError handler, so you can use that as more of a catch-all whereas <code>onIOError</code> is specifically for LoaderEvent.IO_ERROR events. Make sure your onIOError function accepts a single parameter of type <code>LoaderEvent</code> (<code>com.greensock.events.LoaderEvent</code>).</li>
  298. * </ul>
  299. * @see com.greensock.loading.data.VideoLoaderVars
  300. */
  301. public function VideoLoader(urlOrRequest:*, vars:Object=null) {
  302. super(urlOrRequest, vars);
  303. _type = "VideoLoader";
  304. _nc = new NetConnection();
  305. _nc.connect(null);
  306. _nc.addEventListener("asyncError", _failHandler, false, 0, true);
  307. _nc.addEventListener("securityError", _failHandler, false, 0, true);
  308. _video = new Video(this.vars.width || 320, this.vars.height || 240);
  309. _video.smoothing = Boolean(this.vars.smoothing != false);
  310. _video.deblocking = uint(this.vars.deblocking);
  311. _refreshNetStream();
  312. _duration = isNaN(this.vars.estimatedDuration) ? 200 : Number(this.vars.estimatedDuration); //just set it to a high number so that the progress starts out low.
  313. _bufferMode = _preferEstimatedBytesInAudit = Boolean(this.vars.bufferMode == true);
  314. _videoPaused = _pausePending = Boolean(this.vars.autoPlay == false);
  315. this.autoAdjustBuffer = !(this.vars.autoAdjustBuffer == false);
  316. this.volume = ("volume" in this.vars) ? Number(this.vars.volume) : 1;
  317. if (LoaderMax.contentDisplayClass is Class) {
  318. _sprite = new LoaderMax.contentDisplayClass(this);
  319. if (!_sprite.hasOwnProperty("rawContent")) {
  320. throw new Error("LoaderMax.contentDisplayClass must be set to a class with a 'rawContent' property, like com.greensock.loading.display.ContentDisplay");
  321. }
  322. } else {
  323. _sprite = new ContentDisplay(this);
  324. }
  325. Object(_sprite).rawContent = null; //so that the video doesn't initially show at the wrong size before the metaData is received at which point we can accurately determine the aspect ratio.
  326. }
  327. /** @private **/
  328. protected function _refreshNetStream():void {
  329. if (_ns != null) {
  330. _ns.pause();
  331. try {
  332. _ns.close();
  333. } catch (error:Error) {
  334. }
  335. _sprite.removeEventListener(Event.ENTER_FRAME, _playProgressHandler);
  336. _sprite.removeEventListener(Event.ENTER_FRAME, _forceTimeHandler);
  337. _ns.client = {};
  338. _ns.removeEventListener(NetStatusEvent.NET_STATUS, _statusHandler);
  339. _ns.removeEventListener("ioError", _failHandler);
  340. _ns.removeEventListener("asyncError", _failHandler);
  341. _ns.removeEventListener(Event.RENDER, _renderHandler);
  342. }
  343. _prevTime = 0;
  344. _ns = (this.vars.netStream is NetStream) ? this.vars.netStream : new NetStream(_nc);
  345. _ns.checkPolicyFile = Boolean(this.vars.checkPolicyFile == true);
  346. _ns.client = {onMetaData:_metaDataHandler, onCuePoint:_cuePointHandler};
  347. _ns.addEventListener(NetStatusEvent.NET_STATUS, _statusHandler, false, 0, true);
  348. _ns.addEventListener("ioError", _failHandler, false, 0, true);
  349. _ns.addEventListener("asyncError", _failHandler, false, 0, true);
  350. _ns.bufferTime = isNaN(this.vars.bufferTime) ? 5 : Number(this.vars.bufferTime);
  351. _video.attachNetStream(_ns);
  352. _sound = _ns.soundTransform;
  353. }
  354. /** @private **/
  355. override protected function _load():void {
  356. _prepRequest();
  357. _repeatCount = 0;
  358. _prevTime = 0;
  359. _bufferFull = false;
  360. _renderedOnce = false;
  361. _timer.reset();
  362. this.metaData = null;
  363. _pausePending = _videoPaused;
  364. if (_videoPaused) {
  365. _setForceTime(0);
  366. _sound.volume = 0;
  367. _ns.soundTransform = _sound; //temporarily silence the audio because in some cases, the Flash Player will begin playing it for a brief second right before the buffer is full (we can't pause until then)
  368. } else {
  369. this.volume = _volume; //ensures the volume is back to normal in case it had been temporarily silenced while buffering
  370. }
  371. _sprite.addEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  372. _ns.addEventListener(Event.RENDER, _renderHandler, false, 0, true);
  373. _videoComplete = _initted = false;
  374. _ns.play(_request.url);
  375. }
  376. /** @private scrubLevel: 0 = cancel, 1 = unload, 2 = dispose, 3 = flush **/
  377. override protected function _dump(scrubLevel:int=0, newStatus:int=0, suppressEvents:Boolean=false):void {
  378. _sprite.removeEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  379. _ns.removeEventListener(Event.RENDER, _renderHandler);
  380. _sprite.removeEventListener(Event.ENTER_FRAME, _forceTimeHandler);
  381. _timer.removeEventListener(TimerEvent.TIMER, _renderHandler);
  382. _forceTime = NaN;
  383. _prevTime = 0;
  384. _initted = false;
  385. _renderedOnce = false;
  386. this.metaData = null;
  387. if (scrubLevel != 2) {
  388. _refreshNetStream();
  389. (_sprite as Object).rawContent = null;
  390. if (_video.parent != null) {
  391. _video.parent.removeChild(_video);
  392. }
  393. }
  394. if (scrubLevel >= 2) {
  395. if (scrubLevel == 3) {
  396. _video.attachNetStream(null);
  397. (_sprite as Object).dispose(false, false);
  398. }
  399. _nc.removeEventListener("asyncError", _failHandler);
  400. _nc.removeEventListener("securityError", _failHandler);
  401. _ns.removeEventListener(NetStatusEvent.NET_STATUS, _statusHandler);
  402. _ns.removeEventListener("ioError", _failHandler);
  403. _ns.removeEventListener("asyncError", _failHandler);
  404. _firstCuePoint = null;
  405. (_sprite as Object).gcProtect = (scrubLevel == 3) ? null : _ns; //we need to reference the NetStream in the ContentDisplay before forcing garbage collection, otherwise gc kills the NetStream even if it's attached to the Video and is playing on the stage!
  406. _ns.client = {};
  407. _video = null;
  408. _ns = null;
  409. _nc = null;
  410. _sound = null;
  411. (_sprite as Object).loader = null;
  412. _sprite = null;
  413. }
  414. super._dump(scrubLevel, newStatus, suppressEvents);
  415. }
  416. /** @private Set inside ContentDisplay's or FlexContentDisplay's "loader" setter. **/
  417. public function setContentDisplay(contentDisplay:Sprite):void {
  418. _sprite = contentDisplay;
  419. }
  420. /** @inheritDoc **/
  421. override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void {
  422. if (type == PLAY_PROGRESS) {
  423. _dispatchPlayProgress = true;
  424. }
  425. super.addEventListener(type, listener, useCapture, priority, useWeakReference);
  426. }
  427. /** @private **/
  428. override protected function _calculateProgress():void {
  429. _cachedBytesLoaded = _ns.bytesLoaded;
  430. if (_cachedBytesLoaded > 1) {
  431. if (_bufferMode) {
  432. _cachedBytesTotal = _ns.bytesTotal * (_ns.bufferTime / _duration);
  433. if (_ns.bufferLength > 0) {
  434. _cachedBytesLoaded = (_ns.bufferLength / _ns.bufferTime) * _cachedBytesTotal;
  435. }
  436. if (_cachedBytesTotal <= _cachedBytesLoaded) {
  437. _cachedBytesTotal = (this.metaData == null || !_renderedOnce) ? int(1.01 * _cachedBytesLoaded) + 1 : _cachedBytesLoaded;
  438. }
  439. } else {
  440. _cachedBytesTotal = _ns.bytesTotal;
  441. }
  442. if (!_auditedSize) {
  443. _auditedSize = true;
  444. dispatchEvent(new Event("auditedSize"));
  445. }
  446. }
  447. _cacheIsDirty = false;
  448. }
  449. /**
  450. * Adds an ActionScript cue point. Cue points are only triggered when the video is playing and passes
  451. * the cue point's position in the video (in the forwards direction - they are not triggered when you skip
  452. * to a previous time in the video with <code>gotoVideoTime()</code>). <br /><br />
  453. *
  454. * For example, to add a cue point named "coolPart" at the 5-second point of the video, do:<br /><br /><code>
  455. *
  456. * myVideoLoader.addASCuePoint(5, "coolPart", {message:"This is a cool part.", id:5}); <br />
  457. * myVideoLoader.addEventListener(VideoLoader.VIDEO_CUE_POINT, cuePointHandler); <br />
  458. * function cuePointHandler(event:LoaderEvent):void { <br />
  459. * trace("hit cue point " + event.data.name + ", message: " + event.data.parameters.message); <br />
  460. * }</code>
  461. *
  462. * @param time The time (in seconds) at which the cue point should be placed in the video.
  463. * @param name The name of the cue point. It is acceptable to have multiple cue points with the same name.
  464. * @param parameters An object containing any data that you want associated with the cue point. For example, <code>{message:"descriptive text", id:5}</code>. This data can be retrieved in the VIDEO_CUE_POINT handler via the LoaderEvent's <code>data</code> property like <code>event.data.parameters</code>
  465. * @return The cue point that was added
  466. * @see #removeASCuePoint()
  467. * @see #gotoVideoCuePoint()
  468. * @see #getCuePointTime()
  469. */
  470. public function addASCuePoint(time:Number, name:String="", parameters:Object=null):Object {
  471. var prev:CuePoint = _firstCuePoint;
  472. if (prev != null && prev.time > time) {
  473. prev = null;
  474. } else {
  475. while (prev && prev.time <= time && prev.next && prev.next.time <= time) {
  476. prev = prev.next;
  477. }
  478. }
  479. var cp:CuePoint = new CuePoint(time, name, parameters, prev);
  480. if (prev == null) {
  481. if (_firstCuePoint != null) {
  482. _firstCuePoint.prev = cp;