PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/nickro/greensock/loading/VideoLoader.as

http://my-project-nickro.googlecode.com/
ActionScript | 676 lines | 335 code | 48 blank | 293 comment | 80 complexity | 1c7ee05689e13223fa233bf894caefde MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. * VERSION: 1.192
  3. * DATE: 2010-07-14
  4. * AS3
  5. * UPDATES AND DOCS AT: http://www.greensock.com/loadermax/
  6. **/
  7. package org.nickro.greensock.loading {
  8. import org.nickro.greensock.events.LoaderEvent;
  9. import org.nickro.greensock.loading.core.LoaderItem;
  10. import org.nickro.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. [Event(name="httpStatus", type="org.nickro.greensock.events.LoaderEvent")]
  21. [Event(name="videoComplete", type="org.nickro.greensock.loading.VideoLoader")]
  22. [Event(name="videoBufferFull", type="org.nickro.greensock.loading.VideoLoader")]
  23. [Event(name="videoBufferEmpty", type="org.nickro.greensock.loading.VideoLoader")]
  24. [Event(name="videoPause", type="org.nickro.greensock.loading.VideoLoader")]
  25. [Event(name="videoPlay", type="org.nickro.greensock.loading.VideoLoader")]
  26. [Event(name="netStatus", type="flash.events.NetStatusEvent")]
  27. /**
  28. * Loads an FLV or MP4 video file using a NetStream and also provides convenient playback methods
  29. * and properties like <code>pauseVideo(), playVideo(), gotoVideoTime(), bufferProgress, playProgress, volume,
  30. * duration, metaData, </code> and <code>videoTime</code>. Just like ImageLoader and SWFLoader, VideoLoader's <code>content</code>
  31. * property refers to a <code>ContentDisplay</code> object (a Sprite) that gets created immediately so that you can
  32. * add it to the display list before the video has finished loading. You don't need to worry about creating
  33. * a NetConnection, a Video object, attaching the NetStream, or any of the typical hassles. VideoLoader can even
  34. * scale the video into the area you specify using scaleModes like <code>"stretch", "proportionalInside",
  35. * "proportionalOutside",</code> and more. It packs a surprising amount of functionality
  36. * into a very small amount of kb.<br /><br />
  37. *
  38. * <strong>OPTIONAL VARS PROPERTIES</strong><br />
  39. * The following special properties can be passed into the VideoLoader constructor via its <code>vars</code> parameter:<br />
  40. * <ul>
  41. * <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>
  42. * <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>
  43. * <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>
  44. * <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>
  45. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  46. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  47. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  48. * <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>
  49. * <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>org.nickro.greensock.layout.ScaleMode</code> constants if you prefer):
  50. * <ul>
  51. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  52. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  53. * <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>
  54. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  55. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  56. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  57. * </ul></li>
  58. * <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>org.nickro.greensock.layout.AlignMode</code> constants if you prefer):
  59. * <ul>
  60. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  61. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  62. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  63. * </ul></li>
  64. * <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>org.nickro.greensock.layout.AlignMode</code> constants if you prefer):
  65. * <ul>
  66. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  67. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  68. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  69. * </ul></li>
  70. * <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>
  71. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  72. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  73. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  74. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  75. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  76. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  77. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  78. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  79. * <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>bgColor</code> if you prefer.</li>
  80. * <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>
  81. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  82. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  83. * <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>
  84. * <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>
  85. * <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>
  86. * <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>
  87. * <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>
  88. * <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>
  89. * <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>
  90. * <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>
  91. * <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>.
  92. *
  93. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  94. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  95. * <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>
  96. * <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>org.nickro.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>
  97. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  98. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  99. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  100. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  101. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  102. * </ul><br />
  103. *
  104. * @example Example AS3 code:<listing version="3.0">
  105. import org.nickro.greensock.loading.~~;
  106. import org.nickro.greensock.loading.display.~~;
  107. import org.nickro.greensock.~~;
  108. import org.nickro.greensock.events.LoaderEvent;
  109. //create a VideoLoader
  110. var loader: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});
  111. //start loading
  112. loader.load();
  113. //Or you could put the VideoLoader into a LoaderMax. Create one first...
  114. var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
  115. //append the VideoLoader and several other loaders
  116. queue.append( loader );
  117. queue.append( new DataLoader("assets/data.txt", {name:"myText"}) );
  118. queue.append( new ImageLoader("assets/image1.png", {name:"myImage", estimatedBytes:3500}) );
  119. //start loading the LoaderMax queue
  120. queue.load();
  121. function progressHandler(event:LoaderEvent):void {
  122. trace("progress: " + event.target.progress);
  123. }
  124. function completeHandler(event:LoaderEvent):void {
  125. //play the video
  126. loader.playVideo();
  127. //tween the volume up to 1 over the course of 2 seconds.
  128. TweenLite.to(loader, 2, {volume:1});
  129. }
  130. function errorHandler(event:LoaderEvent):void {
  131. trace("error occured with " + event.target + ": " + event.text);
  132. }
  133. </listing>
  134. *
  135. * <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.
  136. *
  137. * @author Jack Doyle, jack@greensock.com
  138. */
  139. public class VideoLoader extends LoaderItem {
  140. /** @private **/
  141. private static var _classActivated:Boolean = _activateClass("VideoLoader", VideoLoader, "flv,f4v,mp4,mov");
  142. /** Event type constant for when the video completes. **/
  143. public static const VIDEO_COMPLETE:String="videoComplete";
  144. /** Event type constant for when the video's buffer is full. **/
  145. public static const VIDEO_BUFFER_FULL:String="videoBufferFull";
  146. /** Event type constant for when the video's buffer is empty. **/
  147. public static const VIDEO_BUFFER_EMPTY:String="videoBufferEmpty";
  148. /** Event type constant for when the video is paused. **/
  149. public static const VIDEO_PAUSE:String="videoPause";
  150. /** Event type constant for when the video begins or resumes playing. **/
  151. public static const VIDEO_PLAY:String="videoPlay";
  152. /** Event type constant for when the video reaches a cue point in the playback of the NetStream. **/
  153. public static const VIDEO_CUE_POINT:String="videoCuePoint";
  154. /** @private **/
  155. protected var _ns:NetStream;
  156. /** @private **/
  157. protected var _nc:NetConnection;
  158. /** @private **/
  159. protected var _video:Video;
  160. /** @private **/
  161. protected var _sound:SoundTransform;
  162. /** @private **/
  163. protected var _videoPaused:Boolean;
  164. /** @private **/
  165. protected var _videoComplete:Boolean;
  166. /** @private **/
  167. protected var _forceTime:Number;
  168. /** @private **/
  169. protected var _duration:Number;
  170. /** @private **/
  171. protected var _pauseOnBufferFull:Boolean;
  172. /** @private **/
  173. protected var _volume:Number;
  174. /** @private **/
  175. protected var _sprite:Sprite;
  176. /** @private **/
  177. protected var _initted:Boolean;
  178. /** @private **/
  179. protected var _bufferMode:Boolean;
  180. /** @private **/
  181. protected var _repeatCount:uint;
  182. /** @private **/
  183. protected var _bufferFull:Boolean;
  184. /** 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. **/
  185. public var metaData:Object;
  186. /**
  187. * Constructor
  188. *
  189. * @param urlOrRequest The url (<code>String</code>) or <code>URLRequest</code> from which the loader should get its content.
  190. * @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 />
  191. *
  192. * The following special properties can be passed into the constructor via the <code>vars</code> parameter:<br />
  193. * <ul>
  194. * <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>
  195. * <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>
  196. * <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>
  197. * <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>
  198. * <li><strong> container : DisplayObjectContainer</strong> - A DisplayObjectContainer into which the <code>ContentDisplay</code> should be added immediately.</li>
  199. * <li><strong> width : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>width</code> property (applied before rotation, scaleX, and scaleY).</li>
  200. * <li><strong> height : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>height</code> property (applied before rotation, scaleX, and scaleY).</li>
  201. * <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>
  202. * <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>org.nickro.greensock.layout.ScaleMode</code> constants if you prefer):
  203. * <ul>
  204. * <li><code>"stretch"</code> (the default) - The video will fill the width/height exactly.</li>
  205. * <li><code>"proportionalInside"</code> - The video will be scaled proportionally to fit inside the area defined by the width/height</li>
  206. * <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>
  207. * <li><code>"widthOnly"</code> - Only the width of the video will be adjusted to fit.</li>
  208. * <li><code>"heightOnly"</code> - Only the height of the video will be adjusted to fit.</li>
  209. * <li><code>"none"</code> - No scaling of the video will occur.</li>
  210. * </ul></li>
  211. * <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>org.nickro.greensock.layout.AlignMode</code> constants if you prefer):
  212. * <ul>
  213. * <li><code>"center"</code> (the default) - The video will be centered horizontally in the area</li>
  214. * <li><code>"left"</code> - The video will be aligned with the left side of the area</li>
  215. * <li><code>"right"</code> - The video will be aligned with the right side of the area</li>
  216. * </ul></li>
  217. * <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>org.nickro.greensock.layout.AlignMode</code> constants if you prefer):
  218. * <ul>
  219. * <li><code>"center"</code> (the default) - The video will be centered vertically in the area</li>
  220. * <li><code>"top"</code> - The video will be aligned with the top of the area</li>
  221. * <li><code>"bottom"</code> - The video will be aligned with the bottom of the area</li>
  222. * </ul></li>
  223. * <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>
  224. * <li><strong> x : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>x</code> property (for positioning on the stage).</li>
  225. * <li><strong> y : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>y</code> property (for positioning on the stage).</li>
  226. * <li><strong> scaleX : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleX</code> property.</li>
  227. * <li><strong> scaleY : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>scaleY</code> property.</li>
  228. * <li><strong> rotation : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>rotation</code> property.</li>
  229. * <li><strong> alpha : Number</strong> - Sets the <code>ContentDisplay</code>'s <code>alpha</code> property.</li>
  230. * <li><strong> visible : Boolean</strong> - Sets the <code>ContentDisplay</code>'s <code>visible</code> property.</li>
  231. * <li><strong> blendMode : String</strong> - Sets the <code>ContentDisplay</code>'s <code>blendMode</code> property.</li>
  232. * <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>bgColor</code> if you prefer.</li>
  233. * <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>
  234. * <li><strong> volume : Number</strong> - A value between 0 and 1 indicating the volume at which the video should play (default is 1).</li>
  235. * <li><strong> repeat : int</strong> - Number of times that the video should repeat. To repeat indefinitely, use -1. Default is 0.</li>
  236. * <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>
  237. * <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>
  238. * <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>
  239. * <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>
  240. * <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>
  241. * <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>
  242. * <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>
  243. * <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>
  244. * <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>.
  245. *
  246. * <br /><br />----EVENT HANDLER SHORTCUTS----</li>
  247. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  248. * <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>
  249. * <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>org.nickro.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>
  250. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  251. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  252. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  253. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  254. * <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>org.nickro.greensock.events.LoaderEvent</code>).</li>
  255. * </ul>
  256. */
  257. public function VideoLoader(urlOrRequest:*, vars:Object=null) {
  258. super(urlOrRequest, vars);
  259. _type = "VideoLoader";
  260. _nc = new NetConnection();
  261. _nc.connect(null);
  262. _nc.addEventListener("asyncError", _failHandler, false, 0, true);
  263. _nc.addEventListener("securityError", _failHandler, false, 0, true);
  264. _ns = (this.vars.netStream is NetStream) ? this.vars.netStream : new NetStream(_nc);
  265. _ns.checkPolicyFile = Boolean(this.vars.checkPolicyFile == true);
  266. _ns.client = {onMetaData:_metaDataHandler, onCuePoint:_cuePointHandler};
  267. _ns.addEventListener(NetStatusEvent.NET_STATUS, _statusHandler, false, 0, true);
  268. _ns.addEventListener("ioError", _failHandler, false, 0, true);
  269. _ns.addEventListener("asyncError", _failHandler, false, 0, true);
  270. _video = _content = new Video(320, 160);
  271. _video.smoothing = Boolean(this.vars.smoothing != false);
  272. _video.deblocking = uint(this.vars.deblocking);
  273. _video.attachNetStream(_ns);
  274. _sound = _ns.soundTransform;
  275. _duration = ("estimatedDuration" in this.vars) ? Number(this.vars.estimatedDuration) : 200; //just set it to a high number so that the progress starts out low.
  276. _bufferMode = _preferEstimatedBytesInAudit = Boolean(this.vars.bufferMode == true);
  277. _ns.bufferTime = ("bufferTime" in this.vars) ? Number(this.vars.bufferTime) : 5;
  278. _videoPaused = _pauseOnBufferFull = Boolean(this.vars.autoPlay != true);
  279. this.volume = ("volume" in this.vars) ? Number(this.vars.volume) : 1;
  280. if (LoaderMax.contentDisplayClass is Class) {
  281. _sprite = new LoaderMax.contentDisplayClass(this);
  282. if (!_sprite.hasOwnProperty("rawContent")) {
  283. throw new Error("LoaderMax.contentDisplayClass must be set to a class with a 'rawContent' property, like org.nickro.greensock.loading.display.ContentDisplay");
  284. }
  285. } else {
  286. _sprite = new ContentDisplay(this);
  287. }
  288. }
  289. /** @private **/
  290. override protected function _load():void {
  291. _prepRequest();
  292. _repeatCount = 0;
  293. _bufferFull = false;
  294. this.metaData = null;
  295. _pauseOnBufferFull = _videoPaused;
  296. if (_videoPaused) {
  297. _sound.volume = 0;
  298. _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)
  299. } else {
  300. this.volume = _volume; //ensures the volume is back to normal in case it had been temporarily silenced while buffering
  301. }
  302. _sprite.addEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  303. _videoComplete = _initted = false;
  304. _ns.play(_request.url);
  305. }
  306. /** @private scrubLevel: 0 = cancel, 1 = unload, 2 = dispose, 3 = flush **/
  307. override protected function _dump(scrubLevel:int=0, newStatus:int=0, suppressEvents:Boolean=false):void {
  308. _sprite.removeEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  309. _sprite.removeEventListener(Event.ENTER_FRAME, _forceTimeHandler);
  310. _forceTime = NaN;
  311. _initted = false;
  312. this.metaData = null;
  313. if (scrubLevel != 2) {
  314. _ns.pause();
  315. try {
  316. _ns.close();
  317. } catch (error:Error) {
  318. }
  319. (_sprite as Object).rawContent = null;
  320. if (_video.parent != null) {
  321. _video.parent.removeChild(_video);
  322. }
  323. }
  324. if (scrubLevel >= 2) {
  325. if (scrubLevel == 3) {
  326. (_sprite as Object).dispose(false, false);
  327. }
  328. _nc.removeEventListener("asyncError", _failHandler);
  329. _nc.removeEventListener("securityError", _failHandler);
  330. _ns.removeEventListener(NetStatusEvent.NET_STATUS, _statusHandler);
  331. _ns.removeEventListener("ioError", _failHandler);
  332. _ns.removeEventListener("asyncError", _failHandler);
  333. (_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!
  334. _ns.client = {};
  335. _video = null;
  336. _ns = null;
  337. _nc = null;
  338. _sound = null;
  339. (_sprite as Object).loader = null;
  340. _sprite = null;
  341. }
  342. super._dump(scrubLevel, newStatus, suppressEvents);
  343. }
  344. /** @private Set inside ContentDisplay's or FlexContentDisplay's "loader" setter. **/
  345. public function setContentDisplay(contentDisplay:Sprite):void {
  346. _sprite = contentDisplay;
  347. }
  348. /** @private **/
  349. protected function _onBufferFull():void {
  350. if (_pauseOnBufferFull) {
  351. _pauseOnBufferFull = false;
  352. this.volume = _volume; //Just resets the volume to where it should be because we temporarily made it silent during the buffer.
  353. gotoVideoTime(0, false);
  354. _ns.pause(); //don't just do this.videoPaused = true because sometimes Flash fires NetStream.Play.Start BEFORE the buffer is full, and we must check inside the videoPaused setter to see if if the buffer is full and wait to pause until it is.
  355. }
  356. if (!_bufferFull) {
  357. _bufferFull = true;
  358. dispatchEvent(new LoaderEvent(VIDEO_BUFFER_FULL, this));
  359. }
  360. }
  361. /** @private **/
  362. override protected function _calculateProgress():void {
  363. _cachedBytesLoaded = _ns.bytesLoaded;
  364. if (_cachedBytesLoaded > 1) {
  365. if (_bufferMode) {
  366. _cachedBytesTotal = _ns.bytesTotal * (_ns.bufferTime / _duration);
  367. if (_ns.bufferLength > 0) {
  368. _cachedBytesLoaded = (_ns.bufferLength / _ns.bufferTime) * _cachedBytesTotal;
  369. }
  370. if (_cachedBytesTotal <= _cachedBytesLoaded) {
  371. _cachedBytesTotal = (this.metaData == null) ? int(1.01 * _cachedBytesLoaded) + 1 : _cachedBytesLoaded;
  372. }
  373. } else {
  374. _cachedBytesTotal = _ns.bytesTotal;
  375. }
  376. _auditedSize = true;
  377. }
  378. _cacheIsDirty = false;
  379. }
  380. /**
  381. * Pauses playback of the video.
  382. *
  383. * @param event An optional event which simply makes it easier to use the method as a handler for mouse clicks or other events.
  384. *
  385. * @see #videoPaused
  386. * @see #gotoVideoTime()
  387. * @see #playVideo()
  388. * @see #videoTime
  389. * @see #playProgress
  390. **/
  391. public function pauseVideo(event:Event=null):void {
  392. this.videoPaused = true;
  393. }
  394. /**
  395. * Plays the video (if the buffer isn't full yet, playback will wait until the buffer is full).
  396. *
  397. * @param event An optional event which simply makes it easier to use the method as a handler for mouse clicks or other events.
  398. *
  399. * @see #videoPaused
  400. * @see #pauseVideo()
  401. * @see #gotoVideoTime()
  402. * @see #videoTime
  403. * @see #playProgress
  404. **/
  405. public function playVideo(event:Event=null):void {
  406. this.videoPaused = false;
  407. }
  408. /**
  409. * Attempts to jump to a certain time in the video. If the video hasn't downloaded enough to get to
  410. * the new time or if there is no keyframe at that time value, it will get as close as possible.
  411. * For example, to jump to exactly 3-seconds into the video and play from there:<br /><br /><code>
  412. *
  413. * loader.gotoVideoTime(3, true);<br /><br /></code>
  414. *
  415. * @param time The time (in seconds, offset from the very beginning) at which to place the virtual playhead on the video.
  416. * @param forcePlay If <code>true</code>, the video will resume playback immediately after seeking to the new position.
  417. * @see #pauseVideo()
  418. * @see #playVideo()
  419. * @see #videoTime
  420. * @see #playProgress
  421. **/
  422. public function gotoVideoTime(time:Number, forcePlay:Boolean=false):void {
  423. if (time > _duration) {
  424. time = _duration;
  425. }
  426. _ns.seek(time);
  427. _videoComplete = false;
  428. _forceTime = time;
  429. _sprite.addEventListener(Event.ENTER_FRAME, _forceTimeHandler, false, 0, true); //If for example, after a video has finished playing, we seek(0) the video and immediately check the playProgress, it returns 1 instead of 0 because it takes a short time to render the first frame and accurately reflect the _ns.time variable. So we use a single ENTER_FRAME to help us override the _ns.time value briefly.
  430. if (forcePlay) {
  431. playVideo();
  432. }
  433. }
  434. //---- EVENT HANDLERS ------------------------------------------------------------------------------------
  435. /** @private **/
  436. protected function _metaDataHandler(info:Object):void {
  437. this.metaData = info;
  438. _duration = info.duration;
  439. if (_ns.bufferTime > _duration) {
  440. _ns.bufferTime = _duration;
  441. }
  442. if ("width" in info) {
  443. _video.scaleX = info.width / 320;
  444. _video.scaleY = info.height / 160; //MUST use 160 as the base width and adjust the scale because of the way Flash reports width/height/scaleX/scaleY on Video objects (it can cause problems when using the scrollRect otherwise)
  445. }
  446. _initted = true;
  447. (_sprite as Object).rawContent = _video; //resizes it appropriately
  448. dispatchEvent(new LoaderEvent(LoaderEvent.INIT, this));
  449. }
  450. protected function _cuePointHandler(info:Object):void {
  451. dispatchEvent(new LoaderEvent(VIDEO_CUE_POINT, this));
  452. }
  453. /** @private **/
  454. protected function _statusHandler(event:NetStatusEvent):void {
  455. var code:String = event.info.code;
  456. if (code == "NetStream.Play.Start") {
  457. var prevPauseOnBufferFull:Boolean = _pauseOnBufferFull;
  458. _onBufferFull(); //Flash sometimes triggers play even before the buffer is completely full, but it wouldn't make sense to report it as such.
  459. if (!prevPauseOnBufferFull) {
  460. dispatchEvent(new LoaderEvent(VIDEO_PLAY, this));
  461. }
  462. }
  463. dispatchEvent(new LoaderEvent(NetStatusEvent.NET_STATUS, this, code));
  464. if (code == "NetStream.Play.Stop") {
  465. if (this.vars.repeat == -1 || uint(this.vars.repeat) > _repeatCount) {
  466. _repeatCount++;
  467. dispatchEvent(new LoaderEvent(VIDEO_COMPLETE, this));
  468. gotoVideoTime(0, true);
  469. } else {
  470. _videoComplete = true;
  471. this.videoPaused = true;
  472. dispatchEvent(new LoaderEvent(VIDEO_COMPLETE, this));
  473. }
  474. } else if (code == "NetStream.Buffer.Full") {
  475. _onBufferFull();
  476. } else if (code == "NetStream.Buffer.Empty") {
  477. _bufferFull = false;
  478. dispatchEvent(new LoaderEvent(VIDEO_BUFFER_EMPTY, this));
  479. } else if (code == "NetStream.Play.StreamNotFound" ||
  480. code == "NetConnection.Connect.Failed" ||
  481. code == "NetStream.Play.Failed" ||
  482. code == "NetStream.Play.FileStructureInvalid" ||
  483. code == "The MP4 doesn't contain any supported tracks") {
  484. _failHandler(new LoaderEvent(LoaderEvent.ERROR, this, code));
  485. }
  486. }
  487. /** @private **/
  488. protected function _enterFrameHandler(event:Event):void {
  489. var bl:uint = _cachedBytesLoaded;
  490. var bt:uint = _cachedBytesTotal;
  491. _calculateProgress();
  492. if (!_bufferFull && _ns.bufferLength >= _ns.bufferTime) {
  493. _onBufferFull();
  494. }
  495. if (_cachedBytesLoaded == _cachedBytesTotal && _ns.bytesTotal > 5 && (this.metaData != null || getTimer() - _time > 5000)) { //make sure the metaData has been received because if the NetStream file is cached locally sometimes the bytesLoaded == bytesTotal BEFORE the metaData arrives. Or timeout after 5 seconds.
  496. _sprite.removeEventListener(Event.ENTER_FRAME, _enterFrameHandler);
  497. if (!_initted) {
  498. (_sprite as Object).rawContent = _video; //resizes it appropriately
  499. }
  500. _completeHandler(event);
  501. } else if (_dispatchProgress && (_cachedBytesLoaded / _cachedBytesTotal) != (bl / bt)) {
  502. dispatchEvent(new LoaderEvent(LoaderEvent.PROGRESS, this));
  503. }
  504. }
  505. /** @private **/
  506. override protected function _auditStreamHandler(event:Event):void {
  507. if (event is ProgressEvent && _bufferMode) {
  508. (event as ProgressEvent).bytesTotal *= (_ns.bufferTime / _duration);
  509. }
  510. super._auditStreamHandler(event);
  511. }
  512. /** @private **/
  513. protected function _forceTimeHandler(event:Event):void {
  514. _forceTime = NaN;
  515. event.target.removeEventListener(Event.ENTER_FRAME, _forceTimeHandler);
  516. }
  517. //---- GETTERS / SETTERS -------------------------------------------------------------------------
  518. /** A ContentDisplay (a Sprite) that contains a Video object to which the NetStream is attached. This ContentDisplay Sprite can be accessed immediately; you do not need to wait for the video to load. **/
  519. override public function get content():* {
  520. return _sprite;
  521. }
  522. /** The <code>Video</code> object to which the NetStream was attached (automatically created by VideoLoader internally) **/
  523. public function get rawContent():Video {
  524. return _content as Video;
  525. }
  526. /** The <code>NetStream</code> object used to load the video **/
  527. public function get netStream():NetStream {
  528. return _ns;
  529. }
  530. /** The playback status of the video: <code>true</code> if the video's playback is paused, <code>false</code> if it isn't. **/
  531. public function get videoPaused():Boolean {
  532. return _videoPaused;
  533. }
  534. public function set videoPaused(value:Boolean):void {
  535. var changed:Boolean = Boolean(value != _videoPaused);
  536. _videoPaused = value;
  537. if (_videoPaused) {
  538. //If we're trying to pause a NetStream that hasn't even been buffered yet, we run into problems where it won't load. So we need to set the _pauseOnBufferFull to true and then when it's buffered, it'll pause it at the beginning.
  539. if (this.bufferProgress < 1 && this.playProgress == 0) {
  540. _pauseOnBufferFull = true;
  541. _sound.volume = 0; //temporarily make …

Large files files are truncated, but you can click here to view the full file