mediacontent.java

来自「基于MPEG 7 标准,符合未来语义网架构,很值得参考」· Java 代码 · 共 573 行 · 第 1/2 页

JAVA
573
字号
/*
 * This file is part of Caliph & Emir.
 *
 * Caliph & Emir is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Caliph & Emir is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Caliph & Emir; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Copyright statement:
 * --------------------
 * (c) 2002-2005 by VizIR project.
 * Please contact Horst Eidenberger (hme@ims.tuwien.ac.at)
 * for more information.
 *
 * Mathias Lux, mathias@juggle.at, http://www.juggle.at
 */

package org.vizir.media;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * Description: This class encapsulates visual media (video, images) for frame-based retrieval.
 * The media is read from an URL passed to the constructor and internally accessed
 * by Java2D/JMF to retrieve the pixel data. Various methods can be used for
 * convenient retrieval of raw pixel data in the desired color model.
 *
 * @author flo ledermann ledermann@ims.tuwien.ac.at
 * @version $Id: MediaContent.java,v 1.2 2005/05/17 22:00:47 motte Exp $
 */
public class MediaContent {
    /**
     * set to false to supress debugging output
     */
    private static final boolean DEBUG = true;

    /**
     * Constant for unknown color or media format
     */
    public static final int UNKNOWN = -1;

    /**
     * Media type: image
     */
    public static final int IMAGE = 0;
    /**
     * Media type: video
     */
    public static final int VIDEO = 1;

    /**
     * Media type, IMAGE, VIDEO or UNKNOWN
     */
    private int mediaType = UNKNOWN;

    /**
     * Color model, RGB, YUV or UNKNOWN
     */
    private ColorModel colorModel = null;

    // image stuff

    /**
     * The image to read pixel data from.
     */
    BufferedImage image = null;

    // video stuff

    /**
     * An object used for synchronization with the processor.
     */
    Object stateSync = null;

    /**
     * Flag indicating successful completion of last state transition by the processor.
     */
    boolean stateTransitionOK = true;

    /** Processor for video data. */
//	Processor p = null;
    /** Control for accessing individual frames. */
//	FramePositioningControl fpc = null;
    /** The video format details. */
//	VideoFormat videoFormat = null;

    /** A Buffer containing the last frame that was successfully captured by our codec. */
//	Buffer frameData = null;

    /**
     * Number of frames to be skipped when calling getNext().
     */
    int keyframeInterval = 1;


    /**
     * Constructor to read media from a given url. If the url has one of the well-known
     * image extensions (jpg, jpeg, gif, bmp, tiff, svg), it tries to load an image from
     * the URL, otherwise a video processor is created from the url.
     *
     * @param url The URL of the media file to load.
     * @throws IOException Something went wrong when trying to load the contents.
     * @throws Exception   Something went wron when trying to initialize the JMF video
     *                     processor.
     */
    public MediaContent(URL url) throws IOException, Exception {

        String ext = url.getFile();
        ext = ext.substring(ext.lastIndexOf('.') + 1);
        if (ext.equalsIgnoreCase("jpg") ||
                ext.equalsIgnoreCase("jpeg") ||
                ext.equalsIgnoreCase("gif")) {
            image = javax.imageio.ImageIO.read(url);
        }
        if (image != null) {
            mediaType = IMAGE;
            colorModel = new ColorModel(ColorModel.RGB);
        }
/*
		else {
			stateSync = new Object();

			try {
				p = Manager.createProcessor(url);
			}
			catch (Exception e) {
				throw new IOException("Source could not be loaded from " + url.toString());
			}
			p.addControllerListener(this);

			p.configure();
			if (!waitForState(Processor.Configured)) {
				throw new Exception("Failed to configure the processor.");
			}
			// we want to use our processor as a player, so disable output
			p.setContentDescriptor(null);

			TrackControl[] tc = p.getTrackControls();
			if (tc == null) {
				throw new Exception("Failed to obtain track controls from the processor.");
			}

			// Search for the track control for the video track.
			TrackControl videoTrack = null;

			for  (int i = 0; i < tc.length; i++) {
				if (tc[i].getFormat() instanceof VideoFormat) {
				videoTrack = tc[i];
				videoFormat = (VideoFormat) videoTrack.getFormat();
				break;
				}
			}


			if (videoTrack == null) {
				throw new Exception("The input media does not contain a video track.");
			}

			frameData = new Buffer();

			if (DEBUG) System.err.println("Video format: " + videoFormat);

			// Instantiate and set the frame access codec to the data flow path.
			try {
				Codec codec[] = { new FrameAccessCodec()};
				videoTrack.setCodecChain(codec);
			} catch (UnsupportedPlugInException e) {
				throw new Exception("The processor does not support codec Plug-Ins.");
			}

			// Try to retrieve a FramePositioningControl from the player.
			fpc = (FramePositioningControl)p.getControl("javax.media.control.FramePositioningControl");

			if (fpc == null) {
				throw new Exception("The player does not support FramePositioningControl.");
			}

			// Realize the processor.
			p.prefetch();
			if (!waitForState(Processor.Prefetched)) {
				throw new Exception("Failed to realize the processor.");
			}

			mediaType = VIDEO;
			colorModel = new ColorModel(ColorModel.RGB);

		}*/
    }

    /**
     * Function to return the image as BufferedImage. If the mediaType is not IMAGE, the function return null.
     *
     * @return image as BufferedImage, null if mediaType is not IMAGE.
     */
    public BufferedImage getImage() {
        if (mediaType == IMAGE)
            return image;
        else
            return null;
    }

    /**
     * Block until the processor has transitioned to the given state.
     * @return false if the transition failed.
     */
    /*boolean waitForState(int state) {
        synchronized (stateSync) {
            try {
                while (p.getState() != state && stateTransitionOK)
                    stateSync.wait();
            } catch (Exception e) {}
        }
        return stateTransitionOK;
    }*/

    /**
     * Returns the first frame of the media.
     *
     * @return MediaFrame object, representing the first frame of the media.
     */

    public MediaFrame getFirst() {
        return null;
    }
/*		if (mediaType == VIDEO && fpc != null){
			int fnum = fpc.seek(0);
			if (DEBUG) System.err.println("seeked to frame " + fnum);
			return getFrameData();
		}
		if (mediaType == IMAGE){
			return getImageData();
		}
		return null;

	}
*/

    /**
     * Helper function to return the pixel data of an image.
     *
     * @return MediaFrame object of the image.
     * @throws UnsupportedOperationException if the frame data could not be grabbed
     */
    private MediaFrame getImageData() {
        int conversion = Pixel.NO_CONVERSION;
        if (colorModel.getColorSpace() == ColorModel.YUV) conversion = Pixel.RGB2YUV;
        return new MediaFrame(image);
    }

    /**
     * Helper function to return the pixel data of a video frame.
     * @return MediaFrame object of the video frame.
     * @throws UnsupportedOperationException if the frame data could not be grabbed
     */
/*
	private MediaFrame getFrameData()  throws UnsupportedOperationException{
          Format test=frameData.getFormat();
		if (! (frameData.getFormat() instanceof RGBFormat))
			throw new UnsupportedOperationException("unknown frame data format");

		int conversion = Pixel.NO_CONVERSION;
		if (colorModel.getColorSpace() == ColorModel.YUV) conversion = Pixel.RGB2YUV;

		Object data = frameData.getData();
		RGBFormat rgbf = (RGBFormat)frameData.getFormat();

		Dimension2D d = rgbf.getSize();

		if (DEBUG) System.err.println("Buffer length: " + frameData.getLength());

		if (rgbf.getDataType() == Format.byteArray) {
                  return new MediaFrame((byte[])data,(int)d.getWidth(),(int)d.getHeight());
		}
		if (rgbf.getDataType() == Format.shortArray) {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?