PageRenderTime 53ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src_lib/com/greensock/loading/VideoLoader.as

https://github.com/dallavilla/ParticleNodeSequencer
ActionScript | 518 lines | 200 code | 29 blank | 289 comment | 41 complexity | 570904d0012c934c03516a242aa6db3f MD5 | raw file
  1. /**
  2. * VERSION: 1.62
  3. * DATE: 2010-10-02
  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.media.SoundTransform;
  16. import flash.media.Video;
  17. import flash.net.NetConnection;
  18. import flash.net.NetStream;
  19. import flash.utils.getTimer;
  20. /** Dispatched when the loader's <code>httpStatus</code> value changes. **/
  21. [Event(name="httpStatus", type="com.greensock.events.LoaderEvent")]
  22. /** Dispatched when the <code>netStream</code> dispatches a NET_STATUS event. **/
  23. [Event(name="netStatus", type="flash.events.NetStatusEvent")]
  24. /**
  25. * Loads an FLV, F4V, or MP4 video file using a NetStream and also provides convenient playback methods
  26. * and properties like <code>pauseVideo(), playVideo(), gotoVideoTime(), bufferProgress, playProgress, volume,
  27. * duration, videoPaused, metaData, </code> and <code>videoTime</code>. Just like ImageLoader and SWFLoader,
  28. * VideoLoader's <code>content</code> property refers to a <code>ContentDisplay</code> object (Sprite) that
  29. * gets created immediately so that you can position/scale/rotate it or add ROLL_OVER/ROLL_OUT/CLICK listeners
  30. * before (or while) the video loads. Use the VideoLoader's <code>content</code> property to get the ContentDisplay
  31. * Sprite, or use the <code>rawContent</code> property to get the <code>Video</code> object that is used inside the
  32. * ContentDisplay to display the video. If a <code>container</code> is defined in the <code>vars</code> object,
  33. * the ContentDisplay will immediately be added to that container).<br /><br />
  34. *
  35. * You don't need to worry about creating a NetConnection, a Video object, attaching the NetStream, or any
  36. * of the typical hassles. VideoLoader can even scale the video into the area you specify using scaleModes
  37. * like <code>"stretch", "proportionalInside", "proportionalOutside",</code> and more. A VideoLoader will
  38. * dispatch useful events like <code>VIDEO_COMPLETE, VIDEO_PAUSE, VIDEO_PLAY, VIDEO_BUFFER_FULL,
  39. * VIDEO_BUFFER_EMPTY, NET_STATUS, VIDEO_CUE_POINT</code>, and <code>PLAY_PROGRESS</code> in addition
  40. * to the typical loader events, making it easy to hook up your own control interface. It packs a
  41. * surprising amount of functionality into a very small amount of kb.<br /><br />
  42. *
  43. * <strong>OPTIONAL VARS PROPERTIES</strong><br />
  44. * The following special properties can be passed into the VideoLoader constructor via its <code>vars</code>
  45. * parameter which can be either a generic object or a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> object:<br />
  46. * <ul>
  47. * <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>
  48. * <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>
  49. * <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>
  50. * <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>
  51. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  52. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  53. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  54. * <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>
  55. * <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):
  56. * <ul>
  57. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  58. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  59. * <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>
  60. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  61. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  62. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  63. * </ul></li>
  64. * <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):
  65. * <ul>
  66. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  67. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  68. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  69. * </ul></li>
  70. * <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):
  71. * <ul>
  72. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  73. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  74. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  75. * </ul></li>
  76. * <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>
  77. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  78. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  79. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  80. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  81. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  82. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  83. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  84. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  85. * <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>
  86. * <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>
  87. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  88. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  89. * <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>
  90. * <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>
  91. * <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>
  92. * <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>
  93. * <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>
  94. * <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>
  95. * <li><strong> noCache : Boolean</strong> - If <code>noCache</code> is <code>true</code>, a "cacheBusterID" 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>
  96. * <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>
  97. * <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>
  98. * <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>.
  99. *
  100. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  101. * <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>
  102. * <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>
  103. * <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>
  104. * <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>
  105. * <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>
  106. * <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>
  107. * <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>
  108. * <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>
  109. * </ul><br />
  110. *
  111. * <strong>Note:</strong> Using a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> instance
  112. * instead of a generic object to define your <code>vars</code> is a bit more verbose but provides
  113. * code hinting and improved debugging because it enforces strict data typing. Use whichever one you prefer.<br /><br />
  114. *
  115. * <strong>Note:</strong> To avoid garbage collection issues in the Flash player, the <code>netStream</code>
  116. * object that VideoLoader employs must get recreated internally anytime the VideoLoader is unloaded or its loading
  117. * is cancelled, so if you need to directly access the <code>netStream</code>, it is best to do so <strong>after</strong>
  118. * the <code>COMPLETE</code> event has been dispatched. Otherwise, if you store a reference to the VideoLoader's
  119. * <code>netStream</code> before or during a load and it gets cancelled or unloaded for some reason, it won't reference
  120. * the one that was used to load the video.<br /><br />
  121. *
  122. * @example Example AS3 code:<listing version="3.0">
  123. import com.greensock.loading.~~;
  124. import com.greensock.loading.display.~~;
  125. import com.greensock.~~;
  126. import com.greensock.events.LoaderEvent;
  127. //create a VideoLoader
  128. 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});
  129. //start loading
  130. video.load();
  131. //add a CLICK listener to a button that causes the video to toggle its paused state.
  132. button.addEventListener(MouseEvent.CLICK, togglePause);
  133. function togglePause(event:MouseEvent):void {
  134. video.videoPaused = !video.videoPaused;
  135. }
  136. //or you could put the VideoLoader into a LoaderMax queue. Create one first...
  137. var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
  138. //append the VideoLoader and several other loaders
  139. queue.append( video );
  140. queue.append( new DataLoader("assets/data.txt", {name:"myText"}) );
  141. queue.append( new ImageLoader("assets/image1.png", {name:"myImage", estimatedBytes:3500}) );
  142. //start loading the LoaderMax queue
  143. queue.load();
  144. function progressHandler(event:LoaderEvent):void {
  145. trace("progress: " + event.target.progress);
  146. }
  147. function completeHandler(event:LoaderEvent):void {
  148. //play the video
  149. loader.playVideo();
  150. //tween the volume up to 1 over the course of 2 seconds.
  151. TweenLite.to(loader, 2, {volume:1});
  152. }
  153. function errorHandler(event:LoaderEvent):void {
  154. trace("error occured with " + event.target + ": " + event.text);
  155. }
  156. </listing>
  157. *
  158. * <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.
  159. *
  160. * @see com.greensock.loading.data.VideoLoaderVars
  161. *
  162. * @author Jack Doyle, jack@greensock.com
  163. */
  164. public class VideoLoader extends LoaderItem {
  165. /** @private **/
  166. private static var _classActivated:Boolean = _activateClass("VideoLoader", VideoLoader, "flv,f4v,mp4,mov");
  167. /** Event type constant for when the video completes. **/
  168. public static const VIDEO_COMPLETE:String="videoComplete";
  169. /** Event type constant for when the video's buffer is full. **/
  170. public static const VIDEO_BUFFER_FULL:String="videoBufferFull";
  171. /** Event type constant for when the video's buffer is empty. **/
  172. public static const VIDEO_BUFFER_EMPTY:String="videoBufferEmpty";
  173. /** Event type constant for when the video is paused. **/
  174. public static const VIDEO_PAUSE:String="videoPause";
  175. /** 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. **/
  176. public static const VIDEO_PLAY:String="videoPlay";
  177. /** Event type constant for when the video reaches a cue point in the playback of the NetStream. **/
  178. public static const VIDEO_CUE_POINT:String="videoCuePoint";
  179. /** Event type constant for when the playback progresses (only dispatched when the video is playing). **/
  180. public static const PLAY_PROGRESS:String="playProgress";
  181. /** @private **/
  182. protected var _ns:NetStream;
  183. /** @private **/
  184. protected var _nc:NetConnection;
  185. /** @private **/
  186. protected var _video:Video;
  187. /** @private **/
  188. protected var _sound:SoundTransform;
  189. /** @private **/
  190. protected var _videoPaused:Boolean;
  191. /** @private **/
  192. protected var _videoComplete:Boolean;
  193. /** @private **/
  194. protected var _forceTime:Number;
  195. /** @private **/
  196. protected var _duration:Number;
  197. /** @private **/
  198. protected var _pauseOnBufferFull:Boolean;
  199. /** @private **/
  200. protected var _volume:Number;
  201. /** @private **/
  202. protected var _sprite:Sprite;
  203. /** @private **/
  204. protected var _initted:Boolean;
  205. /** @private **/
  206. protected var _bufferMode:Boolean;
  207. /** @private **/
  208. protected var _repeatCount:uint;
  209. /** @private **/
  210. protected var _bufferFull:Boolean;
  211. /** @private **/
  212. protected var _dispatchPlayProgress:Boolean;
  213. /** @private **/
  214. protected var _prevTime:Number;
  215. /** @private **/
  216. protected var _firstCuePoint:CuePoint;
  217. /** @private we must wait until the NetStream buffers once (the first time) before we can pause() it, otherwise it may not load at all and/or the metaData won't be received. **/
  218. protected var _bufferedOnce:Boolean;
  219. /** 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. **/
  220. public var metaData:Object;
  221. /** 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. **/
  222. public var autoAdjustBuffer:Boolean;
  223. /**
  224. * Constructor
  225. *
  226. * @param urlOrRequest The url (<code>String</code>) or <code>URLRequest</code> from which the loader should get its content.
  227. * @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 />
  228. *
  229. * The following special properties can be passed into the constructor via the <code>vars</code> parameter
  230. * which can be either a generic object or a <code><a href="data/VideoLoaderVars.html">VideoLoaderVars</a></code> object:<br />
  231. * <ul>
  232. * <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>
  233. * <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>
  234. * <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>
  235. * <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>
  236. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  237. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  238. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  239. * <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>
  240. * <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):
  241. * <ul>
  242. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  243. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  244. * <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>
  245. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  246. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  247. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  248. * </ul></li>
  249. * <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):
  250. * <ul>
  251. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  252. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  253. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  254. * </ul></li>
  255. * <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):
  256. * <ul>
  257. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  258. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  259. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  260. * </ul></li>
  261. * <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>
  262. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  263. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  264. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  265. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  266. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  267. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  268. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  269. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  270. * <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>
  271. * <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>
  272. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  273. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  274. * <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>
  275. * <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>
  276. * <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>
  277. * <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>
  278. * <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>
  279. * <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>
  280. * <li><strong> noCache : Boolean</strong> - If <code>noCache</code> is <code>true</code>, a "cacheBusterID" 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>
  281. * <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>
  282. * <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>
  283. * <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>.
  284. *
  285. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  286. * <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>
  287. * <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>
  288. * <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>
  289. * <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>
  290. * <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>
  291. * <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>
  292. * <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>
  293. * <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>
  294. * </ul>
  295. * @see com.greensock.loading.data.VideoLoaderVars
  296. */
  297. public function VideoLoader(urlOrRequest:*, vars:Object=null) {
  298. super(urlOrRequest, vars);
  299. _type = "VideoLoader";
  300. _nc = new NetConnection();
  301. _nc.connect(null);
  302. _nc.addEventListener("asyncError", _failHandler, false, 0, true);
  303. _nc.addEventListener("securityError", _failHandler, false, 0, true);
  304. _video = _content = new Video(320, 160);
  305. _video.smoothing = Boolean(this.vars.smoothing != false);
  306. _video.deblocking = uint(this.vars.deblocking);
  307. _refreshNetStream();
  308. _duration = isNaN(this.vars.estimatedDuration) ? 200 : Number(this.vars.estimatedDuration); //just set it to a high number so that the progress starts out low.
  309. _bufferMode = _preferEstimatedBytesInAudit = Boolean(this.vars.bufferMode == true);
  310. _videoPaused = _pauseOnBufferFull = Boolean(this.vars.autoPlay == false);
  311. this.autoAdjustBuffer = !(this.vars.autoAdjustBuffer == false);
  312. this.volume = ("volume" in this.vars) ? Number(this.vars.volume) : 1;
  313. if (LoaderMax.contentDisplayClass is Class) {
  314. _sprite = new LoaderMax.contentDisplayClass(this);
  315. if (!_sprite.hasOwnProperty("rawContent")) {
  316. throw new Error("LoaderMax.contentDisplayClass must be set to a class with a 'rawContent' property, like com.greensock.loading.display.ContentDisplay");
  317. }
  318. } else {
  319. _sprite = new ContentDisplay(this);
  320. }
  321. }
  322. /** @private **/
  323. protected function _refreshNetStream():void {
  324. if (_ns != null) {
  325. _ns.pause();
  326. try {
  327. _ns.close();
  328. } catch (error:Error) {
  329. }
  330. _sprite.removeEventListener(Event.ENTER_FRAME, _playProgressHandler);
  331. _ns.client = {};
  332. _ns.removeEventListener(NetStatusEvent.NET_STATUS, _statusHandler);
  333. _ns.removeEventListener("ioError", _failHandler);
  334. _ns.removeEventListener("asyncError", _failHandler);
  335. }
  336. _prevTime = 0;
  337. _bufferedOnce = false;
  338. _ns = (this.vars.netStream is NetStream) ? this.vars.netStream : new NetStream(_nc);
  339. _ns.checkPolicyFile = Boolean(this.vars.checkPolicyFile == true);
  340. _ns.client = {onMetaData:_metaDataHandler, onCuePoint:_cuePointHandler};
  341. _ns.addEventListener(NetStatusEvent.NET_STATUS, _statusHandler, false, 0, true);
  342. _ns.addEventListener("ioError", _failHandler, false, 0, true);
  343. _ns.addEventListener("asyncError", _failHandler, false, 0, true);
  344. _ns.bufferTime = isNaN(this.vars.bufferTime) ? 5 : Number(this.vars.bufferTime);
  345. _video.attachNetStream(_ns);
  346. _sound = _ns.soundTransform;
  347. }
  348. /** @private **/
  349. override protected function _load():void {
  350. _prepRequest();
  351. _repeatCount = 0;
  352. _prevTime = 0;
  353. _bufferFull = false;
  354. _bufferedOnce = false;
  355. this.metaData = null;
  356. _pauseOnBufferFull = _videoPaused;
  357. if (_videoPaused) {
  358. _setForceTime(0);
  359. _sound.volume = 0;
  360. _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)
  361. } else {
  362. this.volume = _volume; //ensures the volume is back to normal in case it had been temporarily silenced while buffering
  363. }
  364. _sprite.addEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  365. _videoComplete = _initted = false;
  366. _ns.play(_request.url);
  367. }
  368. /** @private scrubLevel: 0 = cancel, 1 = unload, 2 = dispose, 3 = flush **/
  369. override protected function _dump(scrubLevel:int=0, newStatus:int=0, suppressEvents:Boolean=false):void {
  370. _sprite.removeEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  371. _sprite.removeEventListener(Event.ENTER_FRAME, _forceTimeHandler);
  372. _forceTime = NaN;
  373. _prevTime = 0;
  374. _initted = false;
  375. _bufferedOnce = false;
  376. this.metaData = null;
  377. if (scrubLevel != 2) {
  378. _refreshNetStream();
  379. (_sprite as Object).rawContent = null;
  380. if (_video.parent != null) {
  381. _video.parent.removeChild(_video);
  382. }
  383. }
  384. if (scrubLevel >= 2) {
  385. if (scrubLevel == 3) {
  386. _video.attachNetStream(null);
  387. (_sprite as Object).dispose(false, false);
  388. }
  389. _nc.removeEventListener("asyncError", _failHandler);
  390. _nc.removeEventListener("securityError", _failHandler);
  391. _ns.removeEventListener(NetStatusEvent.NET_STATUS, _statusHandler);
  392. _ns.removeEventListener("ioError", _failHandler);
  393. _ns.removeEventListener("asyncError", _failHandler);
  394. _firstCuePoint = null;
  395. (_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!
  396. _ns.client = {};
  397. _video = null;
  398. _ns = null;
  399. _nc = null;
  400. _sound = null;
  401. (_sprite as Object).loader = null;
  402. _sprite = null;
  403. }
  404. super._dump(scrubLevel, newStatus, suppressEvents);
  405. }
  406. /** @private Set inside ContentDisplay's or FlexContentDisplay's "loader" setter. **/
  407. public function setContentDisplay(contentDisplay:Sprite):void {
  408. _sprite = contentDisplay;
  409. }
  410. /** @inheritDoc **/
  411. override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void {
  412. if (type == PLAY_PROGRESS) {
  413. _dispatchPlayProgress = true;
  414. }
  415. super.addEventListener(type, listener, useCapture, priority, useWeakReference);
  416. }
  417. /** @private **/
  418. override protected function _calculateProgress():void {
  419. _cachedBytesLoaded = _ns.bytesLoaded;
  420. if (_cachedBytesLoaded > 1) {
  421. if (_bufferMode) {
  422. _cachedBytesTotal = _ns.bytesTotal * (_ns.bufferTime / _duration);
  423. if (_ns.bufferLength > 0) {
  424. _cachedBytesLoaded = (_ns.bufferLength / _ns.bufferTime) * _cachedBytesTotal;
  425. }
  426. if (_cachedBytesTotal <= _cachedBytesLoaded) {
  427. _cachedBytesTotal = (this.metaData == null) ? int(1.01 * _cachedBytesLoaded) + 1 : _cachedBytesLoaded;
  428. }
  429. } else {
  430. _cachedBytesTotal = _ns.bytesTotal;
  431. }
  432. if (!_auditedSize) {
  433. _auditedSize = true;
  434. dispatchEvent(new Event("auditedSize"));
  435. }
  436. }
  437. _cacheIsDirty = false;
  438. }
  439. /**
  440. * Adds an ActionScript cue point. Cue points are only triggered when the video is playing and passes
  441. * the cue point's position in the video (in the forwards direction - they are not triggered when you skip
  442. * to a previous time in the video with <code>gotoVideoTime()</code>). <br /><br />
  443. *
  444. * For example, to add a cue point named "coolPart" at the 5-second point of the video, do:<br /><br /><code>
  445. *
  446. * myVideoLoader.addASCuePoint(5, "coolPart", {message:"This is a cool part.", id:5}); <br />
  447. * myVideoLoader.addEventListener(VideoLoader.VIDEO_CUE_POINT, cuePointHandler); <br />
  448. * function cuePointHandler(event:LoaderEvent):void { <br />
  449. * trace("hit cue point " + event.data.name + ", message: " + event.data.paramaters.message); <br />
  450. * }</code>
  451. *
  452. * @param time The time (in seconds) at which the cue point should be placed in the video.
  453. * @param name The name of the cue point. It is acceptable to have multiple cue points with the same name.
  454. * @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>
  455. * @return The cue point that was added
  456. * @see #removeASCuePoint()
  457. */
  458. public function addASCuePoint(time:Number, name:String="", parameters:Object=null):Object {
  459. var prev:CuePoint = _firstCuePoint;
  460. if (prev != null && prev.time > time) {
  461. prev = null;
  462. } else {
  463. while (prev && prev.time <= time && prev.next && prev.next.time <= time) {
  464. prev = prev.next;
  465. }
  466. }
  467. var cp:CuePoint = new CuePoint(time, name, parameters, prev);
  468. if (prev == null) {
  469. if (_firstCuePoint != null) {
  470. _firstCuePoint.prev = cp;
  471. cp.next = _firstCuePoint;
  472. }
  473. _firstCuePoint = cp;
  474. }
  475. return cp;
  476. }
  477. /**
  478. * Removes an ActionScript cue point that was added with <code>addASCuePoint()</code>. If multiple ActionScript cue points match the search criteria, only one is removed.
  479. * To remove all, call this function repeatedly in a loop with the same parameters until it retu