/*
  PlayAVI.java
  Demonstrates the use of AVI_Reader of ImageJ to
  play an uncompressed .avi file. 
*/
import java.io.*;
import java.awt.Frame;
import java.awt.image.*;
import java.awt.image.ColorModel;
import java.awt.color.ColorSpace;
import java.awt.*;
import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.*;
import ij.plugin.AVI_Reader;

public class PlayAVI {
 
  public static void main(String[] args) throws InterruptedException {
    if (args.length != 1) {
      System.out.println("Usage: java "  + "PlayAVI " +
                                    "AVI_input_image_filename");
      System.out.println("       e.g. java PlayAVI ../data/jvideo.avi");
      System.exit(-1);
    }

    AVI_Reader avi = new AVI_Reader();
    //read images from AVI file to virtual stack
    avi.makeStack ( args[0], 0, 0, true, false, false  ); 
    
    int vsize = avi.getSize();     //number of images in the virtual stack
    int width = avi.getWidth();    //image width
    int height = avi.getHeight();  //image height
    System.out.printf("Total number of frames=%d, width=%d, height=%d \n", 
                                                  vsize, width, height );

    //create a TiledImage using a ColorModel and a SampleModel 
    ColorSpace colorspace = ColorSpace.getInstance ( ColorSpace.CS_sRGB );
    int[] bits = { 8, 8, 8 };
    ColorModel  colormodel = new ComponentColorModel( colorspace, bits, 
        false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE );
    TiledImage outImage;
    SampleModel  samplemodel = new BandedSampleModel(DataBuffer.TYPE_BYTE,
                                                         width, height, 3);
    outImage = new TiledImage(0,0,width,height,0,0,samplemodel,colormodel);
    ScrollingImagePanel panel = new ScrollingImagePanel(outImage,width,height);
    Frame window = new Frame("AVI_Reader Demo");
    window.add(panel);
    window.pack();
    window.show();
   
    //render the AVI images  
    for ( int s = 1; s < vsize; ++s ) { 
      Object obj = avi.getPixels ( s ); 
      if ( obj instanceof int[] ) {  
        int[] pixels = (int[]) obj;
        int k = 0;
        for (int y = 0; y < height; y++) {
          for (int x = 0; x < width; x++) {
            int c, n = 16;
            //consider colors R, G, B
            for ( int i = 0; i < 3; ++i ) {
              c = (int)( 0x000000ff & (pixels[k]>>n) ); 
              outImage.setSample(x, y, i, c );
              n -= 8;
            }
            k++;
          }
        }
        panel.set ( outImage );
        Thread.sleep ( 60 );
      } else {
        System.out.println("Only supports integer pixels\n");
        System.exit ( -1 );
      }
    } 
    Thread.sleep( 4000 ); //sleep for four seconds
    window.dispose();     //close the frame
  }
}

