Preload flash .flv files into browser cache

« Apache Web Server Speed Configuration HacksFight Blog Spam with Apache »

Jan 30, 07

Found a great way to preload and cache flash .flv video files. Recently I was hired as the lead web-designer for an insurance company website with over 30 online videos to be placed throughout the site.

My areas of expertise are XHTML strict, CSS, and javascript, NOT flash. But for this project the site had around 30 videos to be placed in various places around the site.


After using the site for a month I noticed that 8 of the 30 videos on the site were being using by almost every site visitor. To speed up the site I created a very small swf (flash 7) file that uses very minimal actionscript to preload flvs specified in a preloadlist.xml file

Any page that I want the flv files to be preloaded I have to have an element with an id of “preloading” or the javascript does not load the swf file. So I set it up so that the preloading only happens when visitors goto the homepage, and also only when visitors haven’t already preloaded the flvs. To check for this I set a cookie when the flvs are preloaded.

CSS for preloading

#preloading {position:absolute; bottom:0;left:0; display:block; width:1px; height:1px; overflow:hidden !important; z-index:1;}

XHTML for preloading

<body onload="preloadflv();">
<span id="preloading"></span>

Actionscript for preloadflv.fla

var netPath:NetConnection = new NetConnection();
netPath.connect(null);
var ncPreLD:NetStream = new NetStream(netPath);
var i:Number = 1;
var preloaderXML:XML = new XML();
preloaderXML.ignoreWhite = true;
preloaderXML.onLoad = function(success:Boolean):Void  {
  if (success) {
    var flvFiles:Array = preloaderXML.firstChild.childNodes;
    var flvDir:String = preloaderXML.firstChild.attributes.basedir;
    ncPreLD.play(flvDir+preloaderXML.firstChild.childNodes[0].attributes.path+".flv");
    ncPreLD.onStatus = function(infoObject:Object):Void  {
      if (infoObject.code == "NetStream.Play.Start") {
        ncPreLD.pause();
        if (i<flvFiles.length) {
          ncPreLD.play(flvDir+preloaderXML.firstChild.childNodes[i].attributes.path+".flv");
          i++;
        }
      }
    };
  }
};
preloaderXML.load("preloadlist.xml");

XML file preloadlist.xml

<?xml version="1.0" encoding="UTF-8"?>
<preloader basedir="http://z.askapache.com/f/l/">
  <flv path="movie1" />
  <flv path="Marya6" />
  <flv path="Denn1" />
  <flv path="Cindy1" />
  <flv path="Jack2" />
  <flv path="Mich2" />
  <flv path="Bran1" />
  <flv path="Tere2" />
  <flv path="Tod1" />
  <flv path="Tere1" />
  <flv path="Marya4" />
  <flv path="Denn2" />
  <flv path="Mich3" />
  <flv path="isb2" />
</preloader>

NetStream

The NetStream.onStatus

NetStream.Buffer.Empty
statusData is not being received quickly enough to fill the buffer. Data flow will be interrupted until the buffer refills, at which time a NetStream.Buffer.Full message will be sent and the stream will begin playing again.
NetStream.Buffer.Full
status The buffer is full and the stream will begin playing.
NetStream.Buffer.Flush
status Data has finished streaming, and the remaining buffer will be emptied.
NetStream.Play.Start
status Playback has started.
NetStream.Play.Stop
status Playback has stopped.
NetStream.Play.StreamNotFound
error The FLV passed to the play() method can’t be found.
NetStream.Seek.InvalidTime
error For video downloaded with progressive download, the user has tried to seek or play past the end of the video data that has downloaded thus far, or past the end of the video once the entire file has downloaded. The message.details property contains a time code that indicates the last valid position to which the user can seek.
NetStream.Seek.Notify
status The seek operation is complete.

.htaccess/httpd setup

Make sure apache sends the correct content-type headers with the swf and flv files

AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf

Implement a caching scheme

# 1 YEAR
<FilesMatch "\.(ico|pdf|flv)$">
Header set Expires "Mon, 27 Mar 2038 20:59:12 GMT"
Header set Cache-Control "max-age=29030400"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
# 3 HOUR
<FilesMatch "\.(css|xml|txt|js|html)$">
Header set Cache-Control "max-age=10800,public"
</FilesMatch>
# NEVER CACHE
<FilesMatch "\.(htm|php|pl|cgi)$">
Header set Cache-Control "private, must-revalidate, no-cache"
Header set Expires "Mon, 27 Mar 1978 20:59:12 GMT"
</FilesMatch>

Flash “scale” Attribute

noBorder

The Stage.width and Stage.height values will remain constant and will reflect the values set in the Document Properties dialog box. The “noBorder” setting means that the SWF will be scaled, maintaining the original aspect ratio, but there may be some cropping. 3
The Update Dimensions button is there to keep us honest. The values in the width and height boxes are not automatically updated when the player window is resized, so you must click the button to update the displayed values of Stage.width and Stage.height. If you have resized the player window in “noScale” mode before switching to this mode, click the Update Dimensions button to see the width and height revert to the values defined in the Document Properties dialog box.

exactFit

The Stage.width and Stage.height values will remain constant and will reflect the values set in the Document Properties dialog box. The “exactFit” setting means that the Flash content will be scaled, without maintaining the original aspect ratio. All of the Flash content will be visible, but some distortion may occur.
The Update Dimensions button is there to keep us honest. The values in the width and height boxes are not automatically updated when the player window is resized, so you must click the button to update the displayed values of Stage.width and Stage.height. If you have resized the player window in “noScale” mode before switching to this mode, click the Update Dimensions button to see the width and height revert to the values defined in the Document Properties dialog box.

noScale

The Stage.width and Stage.height values will change as you resize the player window. The “noScale” setting means that the SWF will not be scaled when the size of the player window changes. Resize the player window and you’ll see what I mean.
There’s no need for an Update button with this setting because this is the only setting for which the onResize message is sent when the player window size changes. In other words, we can add code to the SWF to update the width and height whenever the player window size changes

showAll

The Stage.width and Stage.height values will remain constant and will reflect the values set in the Document Properties dialog box. The “showAll” setting means that the all Flash content will be visible and the original aspect ratio will be preserved, but borders may appear on two sides of the application.
The Update Dimensions button is there to keep us honest. The values in the width and height boxes are not automatically updated when the player window is resized, so you must click the button to update the displayed values of Stage.width and Stage.height. If you have resized the player window in “noScale” mode before switching to this mode, click the Update Dimensions button to see the width and height revert to the values defined in the Document Properties dialog box.

Parameters for embedding flash

Parameters and attributes
The following tag attributes and parameters describe the HTML code created by the Publish command. You can refer to this list as you write custom HTML to show Flash content. Unless noted, all items apply to both the object and embed tags. Optional entries are noted. Parameters are used with the object tag and are recognized by Internet Explorer, but the embed tag is recognized by Netscape. Attributes are used with both the object and embed tags. When you customize a template, you can substitute a template variable (identified in the Value section for each parameter in the list that follows) for the value. For more information, see Customizing HTML publishing templates.

NOTE

 The attributes and parameters listed in this section are shown in lowercase letters purposely to comply with the XHTML standard.

 
devicefont attribute/parameter
Value
true | false
 
Template variable: $DE
 
Description
(Optional) Specifies whether static text objects that the Device Font option has not been selected for will be drawn using device fonts anyway, if the necessary fonts are available from the operating system. 
 
src attribute 
Value
movieName.swf
 
Template variable: $MO
 
Description
Specifies the name of the SWF file to be loaded. Applies to the embed tag only. 
 
movie parameter
Value
movieName.swf
 
Template variable: $MO
 
Description
Specifies the name of the SWF file to be loaded. Applies to the object tag only.
 
classid attribute
Value
clsid:d27cdb6e-ae6d-11cf-96b8-444553540000
 
Description
Identifies the ActiveX control for the browser. The value must be entered exactly as shown. Applies to the object tag only.
 
width attribute
Value
n or n%
 
Template variable: $WI
 
Description
Specifies the width of the application either in pixels or as a percentage of the browser window.
 
 height attribute
Value
n or n%
 
Template variable: $HE
 
Description
Specifies the height of the application either in pixels or as a percentage of the browser window. 
 
NOTE

 Because Flash applications are scalable, quality doesn't degrade at different sizes if the aspect ratio is maintained. (For example, the following sizes all have a 4:3 aspect ratio: 640 x 480 pixels, 320 x 240 pixels, and 240 x 180 pixels.)

 
codebase attribute
Value
http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0
 
Description
Identifies the location of the Flash Player ActiveX control so that the browser can automatically download it if it is not already installed. The value must be entered exactly as shown. Applies to the object tag only.
 
pluginspage attribute
Value
http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash 
 
Description
Identifies the location of the Flash Player plug-in so that the user can download it if it is not already installed. The value must be entered exactly as shown. Applies to the embed tag only.
 
swliveconnect attribute
Value
true | false 
 
Description
(Optional) Specifies whether the browser should start Java when loading Flash Player for the first time. The default value is false if this attribute is omitted. If you use JavaScript and Flash on the same page, Java must be running for the fscommand() function to work. However, if you use JavaScript only for browser detection or another purpose unrelated to fscommand()actions, you can prevent Java from starting by setting SWLIVECONNECT to false. You can also force Java to start when you are not using JavaScript with Flash by explicitly setting the SWLIVECONNECT attribute to true. Starting Java substantially increases the time it takes to start a SWF file; set this tag to true only when necessary. Applies to the embed tag only.
 
Use the fscommand()action to start Java from a stand-alone projector file.
 
play attribute/parameter
Value
true | false
 
Template variable: $PL
 
Description
(Optional) Specifies whether the application begins playing immediately on loading in the web browser. If your Flash application is interactive, you might want to let the user initiate play by clicking a button or performing another task. In this case, set the play attribute to false to prevent the application from starting automatically. The default value is true if this attribute is omitted.
 
 loop attribute/parameter
Value
true | false
 
Template variable: $LO
 
Description
(Optional) Specifies whether the Flash content repeats indefinitely or stops when it reaches the last frame. The default value is true if this attribute is omitted.
 
quality attribute/parameter
Value
low | medium | high | autolow | autohigh | best
 
Template variable: $QU
 
Description
(Optional) Specifies the level of anti-aliasing to be used when your application plays. Because anti-aliasing requires a faster processor to smooth each frame of the SWF file before it is rendered on the viewer's screen, select one of the following values based on whether your priority is speed or appearance:
 
Low favors playback speed over appearance and never uses anti-aliasing.
 
Autolow emphasizes speed at first but improves appearance whenever possible. Playback begins with anti-aliasing turned off. If Flash Player detects that the processor can handle it, anti-aliasing is turned on.
 
Autohigh emphasizes playback speed and appearance equally at first but sacrifices appearance for playback speed if necessary. Playback begins with anti-aliasing turned on. If the frame rate drops below the specified frame rate, anti-aliasing is turned off to improve playback speed. Use this setting to emulate the Antialias command in Flash (View > Preview Mode > Antialias). 
 
Medium applies some anti-aliasing and does not smooth bitmaps. It produces a better quality than the Low setting but a lower quality than the High setting. 
 
High favors appearance over playback speed and always applies anti-aliasing. If the SWF file does not contain animation, bitmaps are smoothed; if the SWF file has animation, bitmaps are not smoothed. 
 
Best provides the best display quality and does not consider playback speed. All output is anti-aliased, and all bitmaps are smoothed.
 
The default value for quality is high if this attribute is omitted.
 
bgcolor attribute/parameter
Value
#RRGGBB (hexadecimal RGB value)
 
Template variable: $BG
 
Description
(Optional) Specifies the background color of the application. Use this attribute to override the background color setting specified in the Flash SWF file. This attribute does not affect the background color of the HTML page.
 
scale attribute/parameter
Value
showall | noborder | exactfit
 
Template variable: $SC
 
Description
(Optional) Defines how the application is placed within the browser window when width and height values are percentages.
 
Showall (Default) makes the entire Flash content visible in the specified area without distortion while maintaining the original aspect ratio of the application. Borders can appear on two sides of the application.
 
Noborder scales the Flash content to fill the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the application. 
 
Exactfit makes the entire Flash content visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur.
 
The default value is showall if this attribute is omitted (and width and height values are percentages).
 
align attribute
Value
Default | L | R | T | B 
 
Template variable: $HA
 
Description
Specifies the align value for the object, embed, and img tags and determines how the Flash SWF file is positioned within the browser window.
 
Default centers the application in the browser window and crops edges if the browser window is smaller than the application.
 
L, R, T, and B align the application along the left, right, top, and bottom edge, respectively, of the browser window and crop the remaining three sides as needed. 
 
 salign parameter
Value
L | R | T | B | TL | TR | BL | BR 
 
Template variable: $SA
 
Description
(Optional) Specifies where a scaled Flash SWF file is positioned within the area defined by the width and height settings. For more information about these conditions, see scale attribute/parameter. 
 
L, R, T, and B align the application along the left, right, top or bottom edge, respectively, of the browser window and crop the remaining three sides as needed.
 
TL and TR align the application to the top left and top right corner, respectively, of the browser window and crop the bottom and remaining right or left side as needed.
 
BL and BR align the application to the bottom left and bottom right corner, respectively, of the browser window and crop the top and remaining right or left side as needed.
 
If this attribute is omitted, the Flash content is centered in the browser window.
 
base attribute
Value
base directory or URL
 
Description
(Optional) Specifies the base directory or URL used to resolve all relative path statements in the Flash SWF file. This attribute is helpful when your SWF files are kept in a different folder from your other files.
 
menu attribute/parameter
Value
true | false
 
Template variable: $ME
 
Description
(Optional) Specifies what type of menu appears when the viewer right-clicks (Windows) or Command-clicks (Macintosh) the application area in the browser.
 
true shows the full menu, which gives the user several options to enhance or control playback.
 
false shows a menu that contains only the About Macromedia Flash Player 6 option and the Settings option.
 
The default value is true if this attribute is omitted.
wmode attribute/parameter
Value
Window | Opaque | Transparent
 
Template variable: $WM

Description
(Optional) Lets you use the transparent Flash content, absolute positioning, and layering capabilities available in Internet Explorer 4.0. This attribute/parameter works only in Windows with the Flash Player ActiveX control.

Window plays the application in its own rectangular window on a web page. Window indicates that the Flash application has no interaction with HTML layers and is always the topmost item.

Opaque makes the application hide everything behind it on the page.

Transparent makes the background of the HTML page show through all the transparent portions of the application and can slow animation performance.

Opaque windowless and Transparent windowless both interact with HTML layers, letting layers above the SWF file block out the application. The difference between the two is that Transparent allows transparency so that HTML layers below the SWF file might show through if a section of the SWF file has transparency; opaque does not.

The default value is Window if this attribute is omitted. Applies to object only.

allowscriptaccess attribute/parameter
Value
always | never | samedomain

Description
Use allowscriptaccess to let your Flash application communicate with the HTML page hosting it. This is required because fscommand() and getURL() operations can cause JavaScript to use the permissions of the HTML page, which can be different from the permissions of your Flash application. This has important implications for cross-domain security.

always permits scripting operations at all times. never forbids all scripting operations. samedomain permits scripting operations only if the Flash application is from the same domain as the HTML page. The default value used by all HTML publish templates is samedomain.

SeamlessTabbing parameter
Value
true | false

Description

(Optional) Lets you set the ActiveX control to perform seamless tabbing, so that the user can tab out of a Flash application. This parameter works only in Windows with the Flash Player ActiveX control, version 7 and higher.

true (or omitted) sets the ActiveX control will perform seamless tabbing: after users tab through the Flash application, the next tab keypress will move the focus out of the Flash application and into the surrounding HTML content or to the browser status bar if there is nothing that can have focus in the HTML following the Flash application.

false sets the ActiveX control to behave as it did in version 6 and earlier: After users tab through the Flash application, the next tab keypress will wrap the focus around to the beginning of the Flash application. In this mode, the focus cannot be advanced past the Flash application by using the tab key.

Nice one askapache! Which browsers does this work in?

If it’s all of them: you know how to fix a bug even the owners of Flash don’t. Sadly I expect that to just be IE7 for Windows.

Very aggravating for the rest of us. :)

This is a trick that I learned towards the end of 05′ for a site that I was developing. I’m obsessed with cross-browser functionality and I got the flash element to disappear behind other content by using the zIndex css attribute with javascript.

I had 5 elements to control, 5 divs that held various content, including flash video. By apsolutely positioning each of the 5 divs within 1 relative parent div I was able to manipulate the stacking order of the divs by applying a className.

.z6 {z-index:9119;}
.z0 {z-index:459;}
.z1 {z-index:449;}
.z2 {z-index:439;}
.z3 {z-index:429;}
.z4 {z-index:419;}

From the official flash documentation:

wmode attribute/parameter
Value:
Window | Opaque | Transparent

Description:
(Optional) Lets you use the transparent Flash content, absolute positioning, and layering capabilities available in Internet Explorer 4.0. This attribute/parameter works only in Windows with the Flash Player ActiveX control.

Window plays the application in its own rectangular window on a web page. [B]Window indicates that the Flash application has no interaction with HTML layers and is always the topmost item.

Opaque makes the application hide everything behind it on the page.

Transparent makes the background of the HTML page show through all the transparent portions of the application and can slow animation performance.

Opaque windowless and Transparent windowless both interact with HTML layers, letting layers above the SWF file block out the application. The difference between the two is that Transparent allows transparency so that HTML layers below the SWF file might show through if a section of the SWF file has transparency; opaque does not.

[B]The default value is Window if this attribute is omitted. Applies to object only.

« Apache Web Server Speed Configuration HacksFight Blog Spam with Apache »


Reader Comments

Skip to form
  1. Venu says:June 10, 0h

    My question is “Can we load a flash file into pdf so that the action script is working?”

  2. Chris Adams says:November 28, 18h

    Thanks a lot. Very helpful, esp. setting up the Apache headers.

  3. Liam says:September 10, 16h

    I’m embedding .flv files (which are just encoded mp3) files so I have better control over preloading into my flash. After using your “Preload and cache flash flv files” script, how can I call them in the flash?

Like honey.. We Keep em' Buzzin

Be polite, my .htaccess anti-spam is crazy-tight..
Please wrap any code blocks in <pre>...</pre> tags, code words in <code>...</code> tags.

WebDev Technology

Someone's Reading

Related Articles

Popular

I'm Reading

Technology Articles

Online Tools

.htaccess Forum

Ask Apache News

Random Articles

Other Articles

This work by AskApache.com is licensed under the most accommodating license type available, just credit source according to license. .htaccess examples


Search