Java Code Examples for com.xuggle.xuggler.IPixelFormat

The following are top voted examples for showing how to use com.xuggle.xuggler.IPixelFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JHelioviewer-SWHV   File: XuggleExporter.java   Source Code and License 6 votes vote down vote up
@Override
public void open(String path, int w, int h, int fps) throws Exception {
    int bitRate = (int) Math.max(w * h * fps * BPP, MIN_BITRATE);
    IRational frameRate = IRational.make(fps, 1);
    deltat = 1e6 / frameRate.getDouble();

    movieWriter = ToolFactory.makeWriter(path);
    movieWriter.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, w, h);

    IPixelFormat.Type pixFmt = IPixelFormat.Type.YUV420P;
    converter = ConverterFactory.createConverter(ConverterFactory.XUGGLER_BGR_24, pixFmt, w, h);

    IStreamCoder coder = movieWriter.getContainer().getStream(0).getStreamCoder();
    coder.setBitRate(bitRate);
    coder.setFrameRate(frameRate);
    coder.setTimeBase(IRational.make(frameRate.getDenominator(), frameRate.getNumerator()));
    coder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, true);
    coder.setGlobalQuality(0);
    // coder.setNumPicturesInGroupOfPictures(fps);
    coder.setPixelType(pixFmt);

    frameNo = 0;
}
 
Example 2
Project: openimaj   File: XuggleVideo.java   Source Code and License 6 votes vote down vote up
public MBFImageConverter(
		final IPixelFormat.Type pictureType, final int pictureWidth,
		final int pictureHeight, final int imageWidth, final int imageHeight)
{
	super(pictureType, pictureWidth, pictureHeight, imageWidth, imageHeight);

	this.bimg.img = new MBFImage(imageWidth, imageHeight, ColourSpace.RGB);
	this.buffer = new byte[imageWidth * imageHeight * 3];
}
 
Example 3
Project: video-batch   File: XugglerInputStream.java   Source Code and License 6 votes vote down vote up
private void setResampler(IStreamCoder videoCoder) {
    if (videoCoder.getCodecType() != ICodec.Type.CODEC_TYPE_VIDEO)
        return;

    resampler = null;
    if (videoCoder.getPixelType() != IPixelFormat.Type.BGR24) {
        // if this stream is not in BGR24, we're going to need to
        // convert it. The VideoResampler does that for us.
        resampler = IVideoResampler.make(videoCoder.getWidth(),
                videoCoder.getHeight(), IPixelFormat.Type.BGR24,
                videoCoder.getWidth(), videoCoder.getHeight(),
                videoCoder.getPixelType());
        if (resampler == null)
            throw new RuntimeException("could not create color space "
                    + "resampler for: " + videoCoder);
    }
}
 
Example 4
Project: video-engines   File: XuggleVideoRecorder.java   Source Code and License 6 votes vote down vote up
/**
  * Encodes an image and writes it to the output stream.
  * 
  * @param image the image to encode (must be BufferedImage.TYPE_3BYTE_BGR)
  * @param pixelType the pixel type
  * @param timeStamp the time stamp in microseconds
  * @throws IOException
  */
private boolean encodeImage(BufferedImage image, IPixelFormat.Type pixelType, long timeStamp) 
		throws IOException {
	// convert image to xuggle picture
	IVideoPicture picture = getPicture(image, pixelType, timeStamp);
	if (picture==null)
		throw new RuntimeException("could not convert to picture"); //$NON-NLS-1$
	// make a packet
	IPacket packet = IPacket.make();
	if (outStreamCoder.encodeVideo(packet, picture, 0) < 0) {
		throw new RuntimeException("could not encode video"); //$NON-NLS-1$
	}
	if (packet.isComplete()) {
		boolean forceInterleave = true;
		if (outContainer.writePacket(packet, forceInterleave) < 0) {
			throw new RuntimeException("could not save packet to container"); //$NON-NLS-1$
		}
		return true;
	}
	return false;		
}
 
Example 5
Project: video-engines   File: XuggleVideoRecorder.java   Source Code and License 6 votes vote down vote up
/**
  * Gets the converter for converting images to pictures. 
  *
  * @param bgrImage the source image (must be type TYPE_3BYTE_BGR)
  * @param pixelType the desired pixel type
  */
private IConverter getConverter(BufferedImage bgrImage, IPixelFormat.Type pixelType){
	int w = bgrImage.getWidth();
	int h = bgrImage.getHeight();
	if (converterDim==null) {
		converterDim = new Dimension(w, h);
	}
	if (outConverter==null || w!=converterDim.width || h!=converterDim.height
			|| outConverter.getPictureType()!= pixelType) {
		try {
			outConverter = ConverterFactory.createConverter(bgrImage, pixelType);
			converterDim = new Dimension(w, h);
		} catch(UnsupportedOperationException e){
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}
	return outConverter;
}
 
Example 6
Project: ether   File: XuggleAccess.java   Source Code and License 5 votes vote down vote up
@Override
public IHostImage getHostImage(BlockingQueue<float[]> audioData) {
	IHostImage result = null;
	try {
		final int w = getWidth();
		final int h = getHeight();
		IVideoPicture newPic = currentPicture.get();
		if (resampler != null) {
			if(tmpPicture == null)
				tmpPicture = IVideoPicture.make(resampler.getOutputPixelFormat(), w, h); 
			newPic = tmpPicture;
			if (resampler.resample(newPic, currentPicture.get()) < 0) {
				log.warning("could not resample video");
				return null;
			}
		}
		if (newPic.getPixelType() != IPixelFormat.Type.RGB24) {
			log.warning("could not decode video as RGB24 bit data");
			return null;
		}
		ByteBuffer dstBuffer = BufferUtils.createByteBuffer(w * h * 3);
		flip(newPic.getByteBuffer(), dstBuffer, w, h);
		result = IHostImage.create(w, h, ComponentType.BYTE, ComponentFormat.RGB, dstBuffer);
		if(!(this.audioData.isEmpty())) {
			while(audioData.size() > (2  * this.audioData.size()) + 128)
				audioData.take();

			while(!(this.audioData.isEmpty())) 
				audioData.add(this.audioData.take());
		}
	} catch(Throwable t) {
		log.warning(t);
	}
	return result;
}
 
Example 7
Project: ShootOFF   File: RollingRecorder.java   Source Code and License 5 votes vote down vote up
public void recordFrame(BufferedImage frame) {
	final BufferedImage image = ConverterFactory.convertToType(frame, BufferedImage.TYPE_3BYTE_BGR);
	final IConverter converter = ConverterFactory.createConverter(image, IPixelFormat.Type.YUV420P);

	timestamp = (System.currentTimeMillis() - startTime) + timeOffset;

	final IVideoPicture f = converter.toPicture(image, timestamp * 1000);
	f.setKeyFrame(isFirstShotFrame);
	f.setQuality(0);

	if (forking) {
		synchronized (bufferedFrames) {
			bufferedFrames.add(f);
		}
	} else {
		isFirstShotFrame = false;

		synchronized (videoWriterLock) {
			if (recording)
				videoWriter.encodeVideo(0, f);
		}

		if (timestamp >= ShotRecorder.RECORD_LENGTH * 3) {
			logger.debug("Rolling video file {}, timestamp = {} ms", relativeVideoFile.getPath(), timestamp);
			fork(false);
		}
	}
}
 
Example 8
Project: ShootOFF   File: ShotRecorder.java   Source Code and License 5 votes vote down vote up
public void recordFrame(BufferedImage frame) {
	final BufferedImage image = ConverterFactory.convertToType(frame, BufferedImage.TYPE_3BYTE_BGR);
	final IConverter converter = ConverterFactory.createConverter(image, IPixelFormat.Type.YUV420P);

	final long timestamp = (System.currentTimeMillis() - startTime) + timeOffset;

	final IVideoPicture f = converter.toPicture(image, timestamp * 1000);
	f.setKeyFrame(isFirstShotFrame);
	f.setQuality(0);
	isFirstShotFrame = false;

	videoWriter.encodeVideo(0, f);
}
 
Example 9
Project: praisenter   File: XugglerMediaReaderThread.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes the reader thread with the given media.
 * @param container the media container
 * @param videoCoder the media video decoder
 * @param audioCoder the media audio decoder
 * @param audioConversions the flag(s) for any audio conversions to must take place
 */
public void initialize(IContainer container, IStreamCoder videoCoder, IStreamCoder audioCoder, int audioConversions) {
	// assign the local variables
	this.outputWidth = 0;
	this.outputHeight = 0;
	this.videoConversionEnabled = false;
	this.scale = false;
	this.container = container;
	this.videoCoder = videoCoder;
	this.audioCoder = audioCoder;
	this.audioConversions = audioConversions;
	
	// create a packet for reading
	this.packet = IPacket.make();
	
	// create the image converter for the video
	if (videoCoder != null) {
		this.width = this.videoCoder.getWidth();
		this.height = this.videoCoder.getHeight();
		IPixelFormat.Type type = this.videoCoder.getPixelType();
		this.picture = IVideoPicture.make(type, this.width, this.height);
		BufferedImage target = new BufferedImage(this.width, this.height, BufferedImage.TYPE_3BYTE_BGR);
		this.videoConverter = ConverterFactory.createConverter(target, type);
	}
	
	// create a resuable container for the samples
	if (audioCoder != null) {
		this.samples = IAudioSamples.make(1024, this.audioCoder.getChannels());
	}
}
 
Example 10
Project: video-batch   File: XugglerCompressor.java   Source Code and License 5 votes vote down vote up
/**
 * A quick hack. Encoding paramaters are hard-coded here.
 *
 * @throws IOException
 */
@Override
public void setEncodingParameters() throws IOException {
    containerFormat = IContainerFormat.make();
    containerFormat.setOutputFormat("avi", null, null);
    // ObjectOutputStream oos = new ObjectOutputStream();
    // oos.writeObject(containerFormat);

    streamCoders = new IStreamCoder[] { IStreamCoder
            .make(IStreamCoder.Direction.ENCODING) };

    ICodec codec = ICodec.guessEncodingCodec(containerFormat, null, null,
            null, ICodec.Type.CODEC_TYPE_VIDEO);

    streamCoders[0].setNumPicturesInGroupOfPictures(1);
    streamCoders[0].setCodec(codec);

    streamCoders[0].setBitRate(25000);
    streamCoders[0].setBitRateTolerance(9000);
    streamCoders[0].setPixelType(IPixelFormat.Type.YUV420P);
    streamCoders[0].setWidth(352);
    streamCoders[0].setHeight(288);
    streamCoders[0].setFlag(IStreamCoder.Flags.FLAG_QSCALE, true);
    streamCoders[0].setGlobalQuality(0);

    IRational frameRate = IRational.make(25, 1);
    streamCoders[0].setFrameRate(frameRate);
    streamCoders[0].setTimeBase(IRational.make(frameRate.getDenominator(),
            frameRate.getNumerator()));
}
 
Example 11
Project: JcvLib   File: VideoFileWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Add new image into video stream.
 */
@Override
public void addImage(final Image image) throws IOException {
    if (!isOpen()) {
        throw new IOException("Current object does not opened yet! Please call #open() method!");
    }

    final BufferedImage worksWithXugglerBufferedImage = convertToType(TypeConvert.toBufferedImage(image),
            BufferedImage.TYPE_3BYTE_BGR);
    final IPacket packet = IPacket.make();

    IConverter converter = null;
    try {
        converter = ConverterFactory.createConverter(worksWithXugglerBufferedImage, IPixelFormat.Type.YUV420P);
    } catch (final UnsupportedOperationException e) {
        throw new IOException(e.getMessage());
    }

    this.totalTimeStamp += this.incrementTimeStamp;
    final IVideoPicture outFrame = converter.toPicture(worksWithXugglerBufferedImage, this.totalTimeStamp);
    outFrame.setQuality(0);
    int retval = this.outStreamCoder.encodeVideo(packet, outFrame, 0);
    if (retval < 0) {
        throw new IOException("Could not encode video!");
    }

    if (packet.isComplete()) {
        retval = this.outContainer.writePacket(packet);
        if (retval < 0) {
            throw new IOException("Could not save packet to container!");
        }
    }
}
 
Example 12
Project: video-engines   File: XuggleVideoRecorder.java   Source Code and License 5 votes vote down vote up
/**
  * Saves the video to the current scratchFile.
  * 
  * @throws IOException
  */
@Override
protected void saveScratch() throws IOException {
	FileFilter fileFilter	=	videoType.getDefaultFileFilter();
	if (!hasContent || !(fileFilter instanceof VideoFileFilter))
		return;
	
	// set container format
	IContainerFormat format = IContainerFormat.make();
	VideoFileFilter xuggleFilter = (VideoFileFilter)fileFilter;
	format.setOutputFormat(xuggleFilter.getContainerType(), null, null);
	
	// set the pixel type--may depend on selected fileFilter?
	IPixelFormat.Type pixelType = IPixelFormat.Type.YUV420P;

	// open the output stream, write the images, close the stream
	openStream(format, pixelType);
	
	// open temp images and encode
	long timeStamp = 0;
	int n=0;
	synchronized (tempFiles) {
		for (File imageFile: tempFiles) {
			if (!imageFile.exists())
				throw new IOException("temp image file not found"); //$NON-NLS-1$
			BufferedImage image = ResourceLoader.getBufferedImage(imageFile.getAbsolutePath(), BufferedImage.TYPE_3BYTE_BGR);
			if (image==null || image.getType()!=BufferedImage.TYPE_3BYTE_BGR) {
				throw new IOException("unable to load temp image file"); //$NON-NLS-1$
			}
			
			encodeImage(image, pixelType, timeStamp);
			n++;
			timeStamp = Math.round(n*frameDuration*1000); // frameDuration in ms, timestamp in microsec
		}
	}
	closeStream();
	deleteTempFiles();
	hasContent = false;
	canRecord = false;
}
 
Example 13
Project: video-engines   File: XuggleVideoRecorder.java   Source Code and License 5 votes vote down vote up
/**
  * Converts a bgr source image to a xuggle picture.
  *
  * @param bgrImage the source image (must be type TYPE_3BYTE_BGR)
  * @param pixelType the pixel type
  * @param timeStamp the timestamp in microseconds
  * @return the xuggle picture
  */
private IVideoPicture getPicture(BufferedImage bgrImage, IPixelFormat.Type pixelType, long timeStamp) {
	
	IVideoPicture picture = null;
	try {
		IConverter converter = getConverter(bgrImage, pixelType);
		picture = converter.toPicture(bgrImage, timeStamp);
		picture.setQuality(0);		
	} catch (Exception ex) {
		ex.printStackTrace();
	} catch (Error err) {
		err.printStackTrace();
	}
	return picture;
 }
 
Example 14
Project: video-engines   File: XuggleVideo.java   Source Code and License 5 votes vote down vote up
/**
  * Gets the BufferedImage for a specified Xuggle picture.
  *
  * @param picture the picture
  * @return the image, or null if unable to resample
  */
private BufferedImage getBufferedImage(IVideoPicture picture) {
   // if needed, convert picture into BGR24 format
	if (picture.getPixelType() != IPixelFormat.Type.BGR24) {
		if (resampler == null) {
      resampler = IVideoResampler.make(
      		picture.getWidth(), picture.getHeight(), IPixelFormat.Type.BGR24,
      		picture.getWidth(), picture.getHeight(), picture.getPixelType());
      if (resampler == null) {
      	OSPLog.warning("Could not create color space resampler"); //$NON-NLS-1$
      	return null;
      }
		}
     IVideoPicture newPic = IVideoPicture.make(resampler.getOutputPixelFormat(),
         picture.getWidth(), picture.getHeight());
     if (resampler.resample(newPic, picture) < 0
     		|| newPic.getPixelType() != IPixelFormat.Type.BGR24) {
     	OSPLog.warning("Could not encode video as BGR24"); //$NON-NLS-1$
     	return null;
     }
     picture = newPic;
	}

	// use IConverter to convert picture to buffered image
	if (converter==null) {
		ConverterFactory.Type type = ConverterFactory.findRegisteredConverter(
				ConverterFactory.XUGGLER_BGR_24);	  	
		converter = ConverterFactory.createConverter(type.getDescriptor(), picture);			
	}
	BufferedImage image = converter.toImage(picture);
	// garbage collect to play smoothly--but slows down playback speed significantly!
	if (playSmoothly)
		System.gc();
 	return image;		
}
 
Example 15
Project: red5-hls-plugin   File: SegmentFacade.java   Source Code and License 5 votes vote down vote up
/**
 * @return the picture
 */
public IVideoPicture getVideoPicture() {
	IVideoPicture pic = IVideoPicture.make(IPixelFormat.Type.YUV420P, width, height);
	pic.put(picture, 0, 0, picture.length);
	pic.setComplete(true, IPixelFormat.Type.YUV420P, width, height, timeStamp);
	return pic;
}
 
Example 16
Project: ether   File: XuggleAccess.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("deprecation")
private void open(URLVideoSource src) throws IOException {
	try {
		if("file".equals(src.getURL().getProtocol())) {
			File f = new File(src.getURL().toURI());
			if (container.open(f.getAbsolutePath(), IContainer.Type.READ, null) < 0)
				throw new IOException("could not open " + f.getAbsolutePath());
		} else {
			String urlStr = TextUtilities.toString(src.getURL());
			if (container.open(urlStr, IContainer.Type.READ, null) < 0)
				throw new IOException("could not open " + urlStr);
		}
	} catch(URISyntaxException e) {
		throw new IOException(e);
	}
	// query how many streams the call to open found
	int numStreams = container.getNumStreams();
	// and iterate through the streams to find the first audio stream
	int videoStreamId = -1;
	int audioStreamId = -1;
	for(int i = 0; i < numStreams; i++) {
		// Find the stream object
		IStream stream = container.getStream(i);
		// Get the pre-configured decoder that can decode this stream;
		IStreamCoder coder = stream.getStreamCoder();

		if (videoStreamId == -1 && coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
			videoStreamId = i;
			videoStream   = stream;
			videoCoder    = coder;
		}
		else if (audioStreamId == -1 && coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
			audioStreamId = i;
			audioStream   = stream;
			audioCoder    = coder;
			audioFormat   = new AudioFormat(
					audioCoder.getSampleRate(),
					(int)IAudioSamples.findSampleBitDepth(audioCoder.getSampleFormat()),
					audioCoder.getChannels(),
					true, /* xuggler defaults to signed 16 bit samples */
					false);
		}
	}
	if (videoStreamId == -1 && audioStreamId == -1)
		throw new IOException("could not find audio or video stream in container in " + src);

	/*
	 * Check if we have a video stream in this file.  If so let's open up our decoder so it can
	 * do work.
	 */
	if (videoCoder != null) {
		if(videoCoder.open() < 0)
			throw new IOException("could not open audio decoder for container " + src);

		if (videoCoder.getPixelType() != IPixelFormat.Type.RGB24) {
			resampler = IVideoResampler.make(
					videoCoder.getWidth(), videoCoder.getHeight(), 
					IPixelFormat.Type.RGB24,
					videoCoder.getWidth(), videoCoder.getHeight(), 
					videoCoder.getPixelType());
			if (resampler == null)
				throw new IOException("could not create color space resampler for " + src);
		}
	}

	if (audioCoder != null) {
		if (audioCoder.open() < 0)
			throw new IOException("could not open audio decoder for container: " + src);
	}
	decoderThread = new Thread(this, src.getURL().toString());
	decoderThread.setPriority(Thread.MIN_PRIORITY);
	decoderThread.setDaemon(true);
	doDecode.set(true);
	decoderThread.start();
}
 
Example 17
Project: JcvLib   File: VideoFileWriter.java   Source Code and License 4 votes vote down vote up
/**
 * Create new object for write video into the file.
 *
 * @param filePath
 *            Path to file for output.
 * @param sizeOfVideo
 *            Size of video for saving.
 * @param FPS
 *            <a href="http://en.wikipedia.org/wiki/Frame_rate">Frame rate per second</a> in Hz.
 * @param numPicturesInGroupOfPictures
 *            Determines the number of interframes between each keyframe.
 * @param bitRate
 *            Bit rate of video in Kbit per second (kbps). You can use 32 kbps, 64 kbps, 128 kbps, 256 kbps and so
 *            on. The relationship between the bit rate and the size of your video is also not quite linear. I've
 *            found that setting the bit rate too low actually increases the size of the video. Why this is I don't
 *            know, but just as a precaution you might want to play with the bit rate a little bit.
 */
public VideoFileWriter(final String filePath, final Size sizeOfVideo, final int FPS,
        final int numPicturesInGroupOfPictures, final int bitRate) throws IOException {

    this.outContainer = IContainer.make();

    JCV.verifyIsNotNull(filePath);
    int retval = this.outContainer.open(filePath, IContainer.Type.WRITE, null);
    if (retval < 0) {
        throw new IOException("Could not open output file!");
    }

    final ICodec codec = ICodec.guessEncodingCodec(null, null, filePath, null, ICodec.Type.CODEC_TYPE_VIDEO);
    if (codec == null) {
        throw new IOException("Could not guess a codec!");
    }

    final IStream outStream = this.outContainer.addNewStream(codec);
    this.outStreamCoder = outStream.getStreamCoder();

    this.outStreamCoder.setNumPicturesInGroupOfPictures(numPicturesInGroupOfPictures);

    this.outStreamCoder.setBitRate(1000 * bitRate);

    this.outStreamCoder.setPixelType(IPixelFormat.Type.YUV420P);

    JCV.verifyIsNotNull(sizeOfVideo);
    this.outStreamCoder.setWidth(sizeOfVideo.getWidth());
    this.outStreamCoder.setHeight(sizeOfVideo.getHeight());

    this.outStreamCoder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, true);
    this.outStreamCoder.setGlobalQuality(0); // Sets the video encoding to the highest quality.

    if (FPS < 0) {
        throw new IllegalArgumentException("Parameter 'FPS' must be more than 0!");
    }
    final IRational frameRate = IRational.make(FPS, 1); // Number of images per second of your end result video.
    this.incrementTimeStamp = Math.round(1000000.0 / FPS);
    this.outStreamCoder.setFrameRate(frameRate);
    this.outStreamCoder.setTimeBase(IRational.make(frameRate.getDenominator(), frameRate.getNumerator()));

    retval = this.outStreamCoder.open(null, null);
    if (retval < 0) {
        throw new IOException("Could not open input decoder!");
    }

    retval = this.outContainer.writeHeader();
    if (retval < 0) {
        throw new IOException("Could not write file header!");
    }

    this.isOpen = false;
}
 
Example 18
Project: video-engines   File: XuggleVideoRecorder.java   Source Code and License 4 votes vote down vote up
/**
   * Opens/initializes the output stream using a specified Xuggle format.
   * 
   * @param format the format
   * @param pixelType the pixel type
   * @throws IOException
   */
	private boolean openStream(IContainerFormat format, IPixelFormat.Type pixelType) 
			throws IOException {
		outContainer = IContainer.make();
		if (outContainer.open(scratchFile.getAbsolutePath(), IContainer.Type.WRITE, format)<0) {
			OSPLog.finer("Xuggle could not open output file"); //$NON-NLS-1$
			return false;
		}	
		String typicalName = "typical."+videoType.getDefaultExtension(); //$NON-NLS-1$
		ICodec codec = ICodec.guessEncodingCodec(format, null, typicalName, null, ICodec.Type.CODEC_TYPE_VIDEO);
		outStream = outContainer.addNewStream(0);
				
		outStreamCoder = outStream.getStreamCoder();	
		outStreamCoder.setNumPicturesInGroupOfPictures(10);		
  	outStreamCoder.setCodec(codec);
		outStreamCoder.setBitRate(250000);
//		outStreamCoder.setBitRateTolerance(9000);	
		outStreamCoder.setPixelType(pixelType);
	  if(dim==null && frameImage!=null) {
	    dim = new Dimension(frameImage.getWidth(null), frameImage.getHeight(null));
	  }
	  if(dim!=null) {
			outStreamCoder.setHeight(dim.height);
			outStreamCoder.setWidth(dim.width);
	  }
//		outStreamCoder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, true);
//		outStreamCoder.setGlobalQuality(0);

		IRational frameRate = IRational.make(1000/frameDuration);
		boolean hasTimeBaseLimit = typicalName.endsWith(".avi") || typicalName.endsWith(".mpg"); //$NON-NLS-1$ //$NON-NLS-2$
		if (hasTimeBaseLimit && frameRate.getDenominator()>65535) { // maximum timebase = 2^16 - 1
			double fps = 1000/frameDuration;
			int denom = 63000; // 7 x 9000
			int numer = Math.round(Math.round(fps*denom));
			frameRate = IRational.make(numer, denom);
		}
		
		
		outStreamCoder.setFrameRate(frameRate);
		// set time base to inverse of frame rate
    outStreamCoder.setTimeBase(IRational.make(frameRate.getDenominator(),
        frameRate.getNumerator()));
//    // some codecs require experimental mode to be set? (and all accept it??)    
//    if (outStreamCoder.setStandardsCompliance(IStreamCoder.CodecStandardsCompliance.COMPLIANCE_EXPERIMENTAL) < 0) {
//			OSPLog.finer("Xuggle could not set compliance mode to experimental"); //$NON-NLS-1$
//			return false;
//    }

  	if (outStreamCoder.open()<0) {
			OSPLog.finer("Xuggle could not open stream encoder"); //$NON-NLS-1$
			return false;
  	}
	
		if (outContainer.writeHeader()<0) {
			OSPLog.finer("Xuggle could not write file header"); //$NON-NLS-1$
			return false;
		}
		return true;
	}
 
Example 19
Project: LibGDXVideoSample   File: VideoTextureProvider.java   Source Code and License 4 votes vote down vote up
/**
 * Plays the video stream, or resumes it if it was paused
 */
public void play() {
	
	if(container == null) {
		// Create a Xuggler container object
		container = IContainer.make();
	}
	
	if(!container.isOpened()) {
		// Open up the container
		if (container.open(inputStream, null) < 0) {
			throw new RuntimeException("Could not open video file: " + videoPath);
		}

		// Query how many streams the call to open found
		int numStreams = container.getNumStreams();

		// Iterate through the streams to find the first video stream
		for (int i = 0; i < numStreams; i++) {
			// Find the stream object
			IStream stream = container.getStream(i);
			
			// Get the pre-configured decoder that can decode this stream;
			IStreamCoder coder = stream.getStreamCoder();
			
			if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
				videoStreamId = i;
				videoCoder = coder;
				break;
			}
		}
		
		if (videoStreamId == -1) {
			throw new RuntimeException("Could not find video stream in container: " + videoPath);
		}
		
		/* Now we have found the video stream in this file. Let's open up our
		 * decoder so it can do work
		 */
		if (videoCoder.open() < 0) {
			throw new RuntimeException("Could not open video decoder for container: " + videoPath);
		}
		
		if (videoCoder.getPixelType() != IPixelFormat.Type.BGR24) {
			// If this stream is not in BGR24, we're going to need to convert it
			resampler = IVideoResampler.make(
				videoCoder.getWidth(),
				videoCoder.getHeight(),
				IPixelFormat.Type.BGR24,
				videoCoder.getWidth(),
				videoCoder.getHeight(),
				videoCoder.getPixelType()
			);
			
			if (resampler == null) {
				throw new RuntimeException("Could not create color space resampler");
			}
		}
		
		/* Query the first timestamp in the stream
		 * Timestamps are in microseconds - convert to milli
		 */
		firstTimestampMilliseconds = container.getStartTime() / 1000;
	}
	
	playState = PlayState.PLAYING;
}