#!/bin/sh
# HDR Time-Lapse Script
#
# Given a set of photographs in raw format, generates a video applying Mantiuk HDR Effect.
# Supports cutting of the original photographs to change video proportion and zoom
#
# Version: 1.0 (Dec 2010)
# Author: admin@anayet.org
#
#    This program 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 3 of the License.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
#

# Raw files to process
RAW_FILES=input_test/*.CR2

# Output directory
OUT=./output

# Position and size of the rectangle to cut in the original photographs
# The proportion should be fit with the VIDEO_WIDTH and VIDEO_HEIGHT parameters
LEFT=838
TOP=1374
WIDTH=2255
HEIGHT=1259

# Size of the output video. Recommended format for youtube HD 1290x720
VIDEO_WIDTH=1290
VIDEO_HEIGHT=720

# Frames per second
VIDEO_FPS=16


rm -Rf $OUT
mkdir $OUT $OUT/img

files=`ls $RAW_FILES -1`
totalFiles=`ls $RAW_FILES -1 | wc -l`
counter=0
for fRaw in $files ; do
	echo "Processing image... ${counter}/${totalFiles}"
	
	strCounter=`printf %04d $counter`
	fMantiuk=${OUT}/img/mantiuk_${strCounter}.tiff
	fOrig=${OUT}/img/orig_${strCounter}.tiff
	fFinal=${OUT}/img/final_${strCounter}.tiff
	
	# HDR Mantiuk generation
	dcraw2hdrgen $fRaw > hdrgen.txt
	pfsinhdrgen hdrgen.txt | pfsout pfs.hdr
	pfsin pfs.hdr \
		| pfscut --left ${LEFT} --top ${TOP} --width ${WIDTH} --height ${HEIGHT} \
		| pfssize -x ${VIDEO_WIDTH} -y ${VIDEO_HEIGHT} \
		| pfstmo_mantiuk06 -e 1 -s 1 \
		| pfsgamma --gamma 1.8 \
		| pfsoutimgmagick ${fMantiuk} 2>/dev/null

	# Original image generation
	ufraw-batch $fRaw \
		--wb=camera \
		--crop-left=${LEFT} \
		--crop-right=$((LEFT+WIDTH)) \
		--crop-top=${TOP} \
		--crop-bottom=$((TOP+HEIGHT)) \
		--overwrite \
		--size=${VIDEO_WIDTH} \
		--output=${fOrig} \
		--out-type=tiff \
		--exposure=0 2>/dev/null
	
	# Final image generation
	composite -dissolve 80% ${fMantiuk} ${fOrig} ${fFinal} 2>/dev/null
	
	# Optimization (increase of color saturation)
	convert -modulate 100,110,100 ${fFinal} ${fFinal}

	counter=$(( $counter + 1 ))  
done

# Video encoding
mencoder -nosound -ovc x264 -x264encopts pass=1:bitrate=3000 -o ${OUT}/output.avi -mf type=tif:fps=${VIDEO_FPS} "mf://${OUT}/img/final_*.tiff"




