package zall.transcoder;

import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.event.*;
import com.xuggle.xuggler.*;

/**
 *
 */
class VideoTranscoderListener extends MediaToolAdapter {
	private int width;
	private int height;

	public VideoTranscoderListener(int width, int height) {
        this.width = width;
        this.height = height;
    }

	private IVideoResampler videoResampler = null;
	private IAudioResampler audioResampler = null;

	@Override
	public void onAddStream(IAddStreamEvent event) {
		int streamIndex = event.getStreamIndex();
		IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
		if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
			streamCoder.setSampleRate( 44100 );
            //streamCoder.setCodec( ICodec.ID.CODEC_ID_AAC );
			//streamCoder.setBitRate( 128 );
		}
        else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
            streamCoder.setWidth( width );
			streamCoder.setHeight( height );

			//streamCoder.setCodec(ICodec.findEncodingCodec( ICodec.ID.CODEC_ID_H264 ));
			//streamCoder.setBitRate( 800000 );
            /*
			int retval = Configuration.configure("/usr/local/xuggler/share/ffmpeg/libx264-superfast.ffpreset", streamCoder);
			if (retval<0)
				throw new RuntimeException("cound not cofigure coder from preset file");
			*/
		}
		super.onAddStream(event);
	}

	@Override
	public void onVideoPicture(IVideoPictureEvent event) {
		IVideoPicture pic = event.getPicture();
		if (videoResampler == null) {
			videoResampler = IVideoResampler.make(width, height, pic.getPixelType(), pic.getWidth(), pic.getHeight(), pic.getPixelType());
		}
		IVideoPicture out = IVideoPicture.make(pic.getPixelType(), width, height);
		videoResampler.resample(out, pic);

		IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
		super.onVideoPicture(asc);
		out.delete();
	}

	@Override
	public void onAudioSamples(IAudioSamplesEvent event) {
		IAudioSamples samples = event.getAudioSamples();
		if (audioResampler == null) {
			audioResampler = IAudioResampler.make(2, samples.getChannels(), 44100, samples.getSampleRate());
		}
		if (event.getAudioSamples().getNumSamples() > 0) {
			IAudioSamples out = IAudioSamples.make(samples.getNumSamples(), samples.getChannels());
			audioResampler.resample(out, samples, samples.getNumSamples());

			AudioSamplesEvent asc = new AudioSamplesEvent(event.getSource(), out, event.getStreamIndex());
			super.onAudioSamples(asc);
			out.delete();
		}
	}

}
