package org.jerrymouse.cc.site.convert.video;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.VideoAttributes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.jerrymouse.cc.site.bean.Format;
import org.jerrymouse.cc.site.bean.Type;

public class ToOgvConvertor extends AbstractVideoConvertor {

	@Override
	public byte[] couvert(byte[] src, Type from, Format to) {
		Type toType = to.getType();
		byte[] target = null;
		try {
			Encoder encoder = new Encoder();
			String filename = "cc" + (int) (Math.random() * 1000);
			File srcFile = File.createTempFile(filename, from.getSuffix());
			IOUtils.write(src, new FileOutputStream(srcFile));
			File targetFile = File.createTempFile(filename, toType.getSuffix());
			EncodingAttributes attrs = new EncodingAttributes();
			attrs.setFormat("ogg");
			VideoAttributes video = new VideoAttributes();
			video.setCodec("libtheora");
			AudioAttributes audio = new AudioAttributes();
			audio.setCodec("libvorbis");
			attrs.setAudioAttributes(audio);
			attrs.setVideoAttributes(video);
			encoder.encode(srcFile, targetFile, attrs);
			target = IOUtils.toByteArray(new FileInputStream(targetFile));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InputFormatException e) {
			e.printStackTrace();
		} catch (EncoderException e) {
			e.printStackTrace();
		}
		return target;
	}

	@Override
	protected List<Type> output() {
		String[] s = { "ogv" };
		return Type.createTypes(s);
	}

}
