FileDocCategorySizeDatePackage
SimpleMotionDetector.javaAPI DocExample9069Wed Nov 10 13:02:32 GMT 2004com.oreilly.qtjnotebook.ch06

SimpleMotionDetector.java

/*

Copyright (c) 2004, Chris Adamson

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
package com.oreilly.qtjnotebook.ch06;

import quicktime.*;
import quicktime.io.*;
import quicktime.std.*;
import quicktime.std.sg.*;
import quicktime.std.movies.*;
import quicktime.std.movies.media.*;
import quicktime.std.image.*;
import quicktime.qd.*;
import quicktime.sound.*;
import quicktime.app.view.*;
import quicktime.util.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.text.*;

import com.oreilly.qtjnotebook.ch01.QTSessionCheck;

public class SimpleMotionDetector extends Frame 
    implements ActionListener {

    SequenceGrabber grabber;
    SGVideoChannel videoChannel;
    QDGraphics gw;
    QDRect grabBounds;
    boolean grabbing;
    Button stopButton;
    Pict grabPict;
    byte[] importPictBytes;
    Component importerComponent;
    Label motionLabel;
    GraphicsImporter importer;
    RawEncodedImage lastImage;
    ImageDescription lastImageDescription;
    byte[] lastImageBytes;
    QDGraphics newImageGW;

    // int thumbcount = 0;

    // lesser numbers are more different (0 == totally different)
    // public static float trigger = 0.0002f;
    public static float trigger = 0.002f;

    // just for debugging?
    static NumberFormat formatter;
    static {
        formatter = NumberFormat.getInstance();
        formatter.setMaximumFractionDigits (10);
    }


    public SimpleMotionDetector() throws QTException {
        super ("Simple Motion Detector");
        QTSessionCheck.check();
        setLayout (new BorderLayout());
        motionLabel = new Label ();
        motionLabel.setForeground (Color.red);
        add (motionLabel, BorderLayout.NORTH);
        stopButton = new Button ("Stop");
        stopButton.addActionListener (this);
        add (stopButton, BorderLayout.SOUTH);
        importer = new GraphicsImporter (StdQTConstants.kQTFileTypePicture);
        importerComponent =
            QTFactory.makeQTComponent(importer).asComponent();
        add (importerComponent, BorderLayout.CENTER);
        setUpVideoGrab();
    }

    public void actionPerformed (ActionEvent e) {
        if (e.getSource() == stopButton) {
            System.out.println ("Stop grabbing");
            try {
                grabbing = false;
                if (grabber != null) {
                    grabber.stop();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                System.exit (0);
            }
        }
    }

    protected void setUpVideoGrab() throws QTException {
        grabber = new SequenceGrabber();
        System.out.println ("got grabber");

        // force an offscreen gworld
        grabBounds = new QDRect (320, 240);
        gw = new QDGraphics (grabBounds);
        grabber.setGWorld (gw, null);

        // get videoChannel and set its bounds
        videoChannel = new SGVideoChannel (grabber);
        System.out.println ("Got SGVideoChannel");
        videoChannel.setBounds (grabBounds);

        // get settings
        // yikes! this crashes java 1.4.2 on mac os x!
        // videoChannel.settingsDialog();

        // prepare and start previewing
        videoChannel.setUsage (StdQTConstants.seqGrabPreview);
        grabber.prepare(true, false);
        grabber.startPreview();

        // get first grab, so we're ready
        // to calc diff's and draw component
        scanForDifference();
        updateImportedPict();

        grabbing = true;

        // set up thread to idle
        ActionListener timerCallback =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (grabbing) {
                        try {
                            System.out.println ("idle");
                            grabber.idle();
                            grabber.update(null);
                            scanForDifference();
                            updateImportedPict();
                        } catch (QTException qte) {
                            qte.printStackTrace();
                        }
                    }
                }
            };
        Timer timer = new Timer (2000, timerCallback);
        timer.start();
    }

    protected void scanForDifference() throws QTException {
        // this seems like overkill, but the GW we give
        // the grabber doesn't get updated.  Picts returned
        // from grabber are different each time, so use 'em
        if (newImageGW == null)
            newImageGW = new QDGraphics (grabBounds);
        grabPict = grabber.grabPict (grabBounds, 0, 0);
        grabPict.draw (newImageGW, grabBounds);

        /* sanity check proved gw wasn't being drawn on
        try {
            newImageGW.setForeColor (quicktime.qd.QDColor.red);
            newImageGW.textSize (96);
            newImageGW.moveTo (100,100);
            String str = Integer.toString (thumbcount);
            newImageGW.drawText (str, 0, str.length());
            Pict sanityPict = newImageGW.makeThumbnail (grabBounds, 0);
            sanityPict.writeToFile (new java.io.File ("sanity" +
                                                      (thumbcount++) +
                                                      ".pict"));
        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();
        }
         */

        if (lastImage != null) {
            // compare to last image
            float similarity = QTImage.getSimilarity (newImageGW,
                                                      grabBounds,
                                                      lastImageDescription,
                                                      lastImage);
            System.out.println ("similarity == " +
                                formatter.format(similarity));
            if (similarity < trigger) {
                System.out.println ("*** Motion detect ***");
                motionLabel.setText ("motion detect");
            } else {
                motionLabel.setText ("");
            }
        }

        // create a new lastImage from grabber GWorld
        int bufSize =
            QTImage.getMaxCompressionSize (newImageGW,
                                           newImageGW.getBounds(),
                                           0,
                                           StdQTConstants.codecNormalQuality,
                                           StdQTConstants.kRawCodecType,
                                           CodecComponent.anyCodec);
        // make new last image
        lastImageBytes = new byte[bufSize];
        lastImage = new RawEncodedImage (lastImageBytes);
        lastImageDescription =
            QTImage.compress(newImageGW,
                             newImageGW.getBounds(),
                             StdQTConstants.codecNormalQuality,
                             StdQTConstants.kRawCodecType,
                             lastImage);
        System.out.println ("made new last image, size= " +
                            lastImage.getSize());
    }



    protected void updateImportedPict() throws QTException {
        importPictBytes = new byte [grabPict.getSize() + 512];
        grabPict.copyToArray (0,
                              importPictBytes,
                              512,
                              importPictBytes.length - 512);
        Pict wrapperPict = new Pict (importPictBytes);
        DataRef ref = new DataRef (wrapperPict,
                                   StdQTConstants.kDataRefQTFileTypeTag,
                                   "PICT");
        importer.setDataReference (ref);
        importer.draw();
        if (importerComponent != null)
            importerComponent.repaint();
        // wrapperPict.disposeQTObject();
    }


    public static void main (String[] args) {
        try {
            Frame f = new SimpleMotionDetector();
            f.pack();
            f.setVisible(true);
        } catch (QTException qte) {
            qte.printStackTrace();
        }
    }

}