/*
Copyright (c) 2010, Geomatics and Cartographic Research Centre, Carleton
University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Geomatics and Cartographic Research Centre,
Carleton University nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
$Id$
*/
package ca.carleton.gcrc.onUpload;
import java.io.File;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import ca.carleton.gcrc.contributions.Contributions;
import ca.carleton.gcrc.contributions.ContributionComet;
import ca.carleton.gcrc.olkit.multimedia.ffmpeg.FFmpeg;
import ca.carleton.gcrc.olkit.multimedia.ffmpeg.VideoInfo;
import ca.carleton.gcrc.olkit.multimedia.file.SystemFile;
import ca.carleton.gcrc.olkit.multimedia.imageMagick.ImageInfo;
import ca.carleton.gcrc.olkit.multimedia.imageMagick.ImageMagick;
import ca.carleton.gcrc.olkit.multimedia.imageMagick.ImageMagickInfo;
import ca.carleton.gcrc.progress.ProgressInfo;
import ca.carleton.gcrc.progress.ProgressTracker;
public class ProcessFileThread extends Thread {
final protected Logger logger = Logger.getLogger(this.getClass());
final public int IMAGE_MAX_WIDTH = 500;
final public int IMAGE_MAX_HEIGHT = 500;
final public int IMAGE_THUMB_HEIGHT = 60;
final public int IMAGE_THUMB_WIDTH = 60;
private UploadedFileInfo fileInfo;
private String progressId;
private Map<String, List<String>> parameters;
private ContributionComet cometChannel;
private Principal userPrincipal;
private Contributions contributions;
public ProcessFileThread(
UploadedFileInfo fileInfo
,String parentProgressId
,Map<String, List<String>> parameters
,ContributionComet cometChannel
,Principal userPrincipal
,Contributions c
) {
this.fileInfo = fileInfo;
this.parameters = parameters;
this.cometChannel = cometChannel;
this.userPrincipal = userPrincipal;
this.contributions = c;
progressId = ProgressTracker.createIdentifier();
String desc = "Process file " + fileInfo.getOriginalFilename();
// Chain activity
ProgressTracker.initProgess(progressId, desc, 102);
ProgressInfo info = ProgressTracker.getProgess(progressId);
if( null != parentProgressId ) {
ProgressTracker.addProgessChain(parentProgressId, info);
}
}
public String getProgressId() {
return progressId;
}
public void run() {
try {
logger.info("Processing: "+fileInfo.getOriginalFilename());
// Perform file type checking
SystemFile sf = SystemFile.getSystemFile(fileInfo.getUploadedFile());
fileInfo.setMimeType( sf.getMimeType() );
fileInfo.setMimeEncoding( sf.getMimeEncoding() );
// Check type
String mimeType = sf.getMimeType();
if( null == mimeType ) {
fileInfo.setConvertedFile( fileInfo.getUploadedFile() );
} else if( mimeType.contains("video") ) {
// For video file, convert to appropriate file type
convertVideo();
} else if( mimeType.contains("audio") ) {
// For audio file, convert to appropriate file type
convertAudio();
} else if( mimeType.contains("image") ) {
// For image file, convert to appropriate file type
convertImage();
} else {
fileInfo.setConvertedFile( fileInfo.getUploadedFile() );
}
// Insert contribution in database
ContributionHandler t = new ContributionHandler(parameters, userPrincipal);
List<String> vec = parameters.get("isUpdate");
if (null == vec) {
throw new Exception("Required isUpdate parameter undefined.");
}
if ("true".equalsIgnoreCase(vec.get(0))) {
t.performDatabaseUpdate(fileInfo, contributions);
} else {
t.performDatabaseInsert(fileInfo, contributions);
}
// Report end of this activity
Map<String,String> data = new HashMap<String,String>();
data.put("file", fileInfo.getOriginalFilename());
data.put("mime-type", fileInfo.getMimeType());
data.put("mime-encoding", fileInfo.getMimeEncoding());
if( parameters.containsKey("place_id") && parameters.get("place_id").size() > 0 ) {
data.put("place_id", parameters.get("place_id").get(0));
}
ProgressTracker.updateProgessData(progressId, data);
ProgressTracker.completeProgess(progressId, null);
// Send completion on comet channel
if( null != cometChannel
&& parameters.containsKey("place_id")
&& parameters.get("place_id").size() > 0
) {
cometChannel.reportNewContribution(parameters.get("place_id").get(0),null);
}
} catch(Exception e) {
e.printStackTrace();
ProgressTracker.completeProgess(progressId, e.getMessage());
}
}
private void convertVideo() throws Exception {
// Get information about video
VideoInfo videoInfo = null;
{
FFmpeg ffmpeg = new FFmpeg();
videoInfo = ffmpeg.getVideoInfo( fileInfo.getUploadedFile() );
}
// Check if conversion is required
boolean conversionRequired = false;
if( null == videoInfo.bitRate ) {
conversionRequired = true;
} else if( videoInfo.bitRate.intValue() > 250000 ) {
conversionRequired = true;
}
if( false == "h264".equals( videoInfo.videoCodec ) ) {
conversionRequired = true;
}
if( false == "mpeg4aac".equals( videoInfo.audioCodec ) ) {
conversionRequired = true;
}
if( false == conversionRequired ) {
// Conversion not required, converted file is the uploaded file
fileInfo.setConvertedFile( fileInfo.getUploadedFile() );
} else {
File inputFile = fileInfo.getUploadedFile();
File parentDir = inputFile.getParentFile();
File outputFile = File.createTempFile("conv", ".mp4", parentDir);
FFmpegProgressImpl progress = new FFmpegProgressImpl(progressId,1);
FFmpeg ffmpeg = new FFmpeg(progress);
ffmpeg.convertVideo(videoInfo, outputFile);
fileInfo.setConvertedFile(outputFile);
}
// Create thumbnail
{
File inputFile = fileInfo.getConvertedFile();
File parentDir = inputFile.getParentFile();
String name = inputFile.getName();
int index = name.lastIndexOf('.');
if( index > 0 ) {
name = name.substring(0, index);
}
name = name+"_thumb.png";
File outputFile = new File(parentDir, name);
FFmpeg ffmpeg = new FFmpeg();
ffmpeg.createThumbnail(videoInfo, outputFile);
}
}
private void convertAudio() throws Exception {
// Get information about audio
VideoInfo audioInfo = null;
{
FFmpeg ffmpeg = new FFmpeg();
audioInfo = ffmpeg.getVideoInfo( fileInfo.getUploadedFile() );
}
// Check if conversion is required
boolean conversionRequired = false;
if( null == audioInfo.bitRate ) {
conversionRequired = true;
} else if( audioInfo.bitRate.intValue() > 250000 ) {
conversionRequired = true;
}
if( false == "mpeg4aac".equals( audioInfo.audioCodec ) ) {
conversionRequired = true;
}
if( false == conversionRequired ) {
// Conversion not required, converted file is the uploaded file
fileInfo.setConvertedFile( fileInfo.getUploadedFile() );
} else {
File inputFile = fileInfo.getUploadedFile();
File parentDir = inputFile.getParentFile();
File outputFile = File.createTempFile("conv", ".mp4", parentDir);
FFmpegProgressImpl progress = new FFmpegProgressImpl(progressId,1);
FFmpeg ffmpeg = new FFmpeg(progress);
ffmpeg.convertAudio(audioInfo, outputFile);
fileInfo.setConvertedFile(outputFile);
}
}
private void convertImage() throws Exception {
ImageMagickInfo imInfo = ImageMagick.getInfo();
// Get information about image
ImageInfo imageInfo = null;
if( imInfo.isAvailable ){
ImageMagick ffmpeg = new ImageMagick();
imageInfo = ffmpeg.getImageInfo( fileInfo.getUploadedFile() );
}
// Check if conversion is required
boolean conversionRequired = false;
boolean resizeRequired = false;
if( null != imageInfo ) {
if( imageInfo.width > IMAGE_MAX_WIDTH ) {
resizeRequired = true;
} else if( imageInfo.height > IMAGE_MAX_HEIGHT ) {
resizeRequired = true;
}
if( false == "JPEG".equals( imageInfo.format ) ) {
conversionRequired = true;
}
}
if( false == conversionRequired && false == resizeRequired ) {
// Conversion not required, converted file is the uploaded file
// Same applies if conversion is impossible because ImageMagick
// is not present.
fileInfo.setConvertedFile( fileInfo.getUploadedFile() );
} else {
File inputFile = fileInfo.getUploadedFile();
File parentDir = inputFile.getParentFile();
File outputFile = File.createTempFile("conv", ".jpg", parentDir);
FFmpegProgressImpl progress = new FFmpegProgressImpl(progressId,1);
ImageMagick im = new ImageMagick(progress);
if( resizeRequired ) {
im.resizeImage(imageInfo, outputFile, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
} else {
im.convertImage(imageInfo, outputFile);
}
fileInfo.setConvertedFile(outputFile);
}
// Create thumbnail
if( null != imageInfo ) {
File inputFile = fileInfo.getConvertedFile();
File parentDir = inputFile.getParentFile();
String name = inputFile.getName();
int index = name.lastIndexOf('.');
if( index > 0 ) {
name = name.substring(0, index);
}
name = name+"_thumb.png";
File outputFile = new File(parentDir, name);
ImageMagick im = new ImageMagick();
im.resizeImage(imageInfo, outputFile, IMAGE_THUMB_WIDTH, IMAGE_THUMB_HEIGHT);
}
}
}