@echo off
setlocal EnableDelayedExpansion

set CQ=23
set a_bitrate=320
set workingdir=D:\Temp
rem set minfilesize=1000000000

if not exist %workingdir% mkdir %workingdir%
copy ffmpeg.exe %workingdir% /Y > NUL
copy ffprobe.exe %workingdir% /Y > NUL

for /R %%f in (*.mkv,*.mp4) do (
		
				
		echo processing file %%f
		
		REM init
		set convert=1
		
		REM default quality
		set CQ=23
		
		REM minimum file size to convert
		set minfilesize=30000000
		
		rem 0 = copy all audio, 1 = bulk process all audio, 2. custom mapping
		set audio_processing_mode=2
		
		REM set mapping
		rem set mapping=-map v:0 -map a -map -0:a:m:language:eng -map s? -map d? -map t?
		set mapping=
		set video_mapping=-map v:0
		set audio_mapping=-map a
		set other_mapping=-map s? -map d? -map t?
		set bulk_audio_streams=2
		
		REM set x265 params
		set x265params=:rc-lookahead=35:ssim-rd=1:ctu=32:pbratio=1.22:subme=3:aq-mode=3:level-idc=5.1:high-tier=1:aq-strength=1.2:qcomp=0.64:no-sao=1:rd=4:psy-rd=2.5:psy-rdoq=3.5:rdoq-level=2:bframes=8:no-strong-intra-smoothing=1:weightb=1:b-intra=1:rect=1:limit-modes=1
		
		REM set 10 Bit Mode
		set 10Bit=1
		
		REM enable HDR metadata input
		set HDR=0
		
		REM get file size		
		set size=%%~zf
		set size=!size:~0,-3!
		echo file size is !size!MB
		
		if !size! leq !minfilesize! (
			echo skipping "%%~pf%%~nf.mkv" as file is smaller than !minfilesize!MB
			rem pause
			set convert=0
		)	
		
		if exist "%%~pf%%~nf.lck" (
			echo skipping "%%~pf%%~nf.mkv" as folder already processing
		    set convert=0
		) 
		
		if exist "%%~pf%%~nf_x265_10Bit_.mkv" (
			echo skipping "%%~pf%%~nf.mkv" as export file exists
			set convert=0
		)
		
	    if exist "%%~pf%%~nf_x265_10Bit.mkv" (
			echo skipping "%%~pf%%~nf.mkv" as export file exists
			set convert=0
		)
					
		
		if exist "%%~pf%%~nf_x265.mkv" (
			echo skipping "%%~pf%%~nf.mkv" as export file exists
			set convert=0
		)
		
		if exist "%%~pfdone.txt" (
			echo skipping "%%~pf%%~nf.mkv" as export file exists
			set convert=0
		)
		
	
		echo convert is !convert!
		
		if !convert!==1 (
		
			if !audio_processing_mode!==0 (
			REM copy all audio
				set audio_mapping=-map a
				set audio_param=-c:a copy
			)

			if !audio_processing_mode!==1 (
			REM bulk process audio
								
				
				set audio_param=
				set audio_mapping=
				del tracks.txt
				
				call ffprobe -loglevel error -select_streams a -show_entries stream_tags=language -of default=nw=1:nk=1 "%%f" > tracks.txt
				
				set count=0
				for /f "tokens=*" %%a in (tracks.txt) do set /a count += 1	
				
				if !count! LSS !bulk_audio_streams!	set bulk_audio_streams=!count!
				
				set /a bulk_audio_streams -= 1
				
				set count=0
				
				for /L %%a in (0,1,!bulk_audio_streams!) do (    
					REM analyse Audio Channels and set Bitrate
						
					del temp.txt
					set channels=
					set bitrate=
						
							
					REM add mapping
					set audio_mapping=!audio_mapping! -map a:!count!
							
					call ffprobe -loglevel error -select_streams a:!count! -show_entries stream=channels -of default=nw=1:nk=1 "%%f" > temp.txt
					set /p channels=<temp.txt
					
						
					echo amount of audio channels stream !count!: !channels!
						
					if !channels! LEQ 2 set bitrate=128
					if !channels! gtr 2 set bitrate=192
					if !channels! gtr 5 set bitrate=256
					if !channels! gtr 7 set bitrate=320

						
					REM opus audio on audio encode (choose one, OPUS default)
					rem if defined bitrate set audio_param= -c:a libfdk_aac -profile:a aac_he -vbr 5
						
					REM opus audio on audio encode		
					
					rem set audio_param=!audio_param! -c:a:!count! libopus -b:a:!count! !bitrate!k -af:a:!count! aformat=channel_layouts="7.1|5.1|stereo" -vbr:a:!count! on -compression_level:a:!count! 10
						
					rem set audio_param=!audio_param! -c:a:!count! libfdk_aac -profile:a:!count! aac_he -vbr:a:!count! 5
					
					
					set audio_param=!audio_param! -c:a:!count! libfdk_aac -profile:a:!count! aac_he -vbr:a:!count! 5
					REM calculate bitrate		
						
					set /a count += 1	
				
				)
	
			)
			
					
			if !audio_processing_mode!==2 (
			
				REM custom autio processing
				
				set audio_param=
				set audio_mapping=
				del tracks.txt
								
				call ffprobe -loglevel error -select_streams a -show_entries stream_tags=language -of default=nw=1:nk=1 "%%f" > tracks.txt
				
				set titel=
				set /a count = 0
				for /f "tokens=*" %%a in (tracks.txt) do (
					
					echo.
					echo Track Information:
					call ffprobe -loglevel error -select_streams a:!count! -show_streams -print_format json "%%f" 
					echo.
					echo How should this track number !count! be processed? 0=copy, 1=convert, 2=delete
					set /p tmp=||set tmp=0
					echo.
					if !tmp!==0 (
					
						set audio_mapping=!audio_mapping! -map a:!count!
						set audio_param=!audio_param! -c:a:!count! copy
						
					)
					
					if !tmp!==1 (
					
						REM analyse Audio Channels and set Bitrate
						
						del temp.txt
						set channels=
						set bitrate=
						
							
						REM add mapping
						set audio_mapping=!audio_mapping! -map a:!count!
							
						call ffprobe -loglevel error -select_streams a:!count! -show_entries stream=channels -of default=nw=1:nk=1 "%%f" > temp.txt
						set /p channels=<temp.txt
					
						
						echo amount of audio channels stream !count!: !channels!
						
						if !channels! LEQ 2 set bitrate=128
						if !channels! gtr 2 set bitrate=192
						if !channels! gtr 5 set bitrate=256
						if !channels! gtr 7 set bitrate=320

						
						REM opus audio on audio encode (choose one, OPUS default)
						rem if defined bitrate set audio_param= -c:a libfdk_aac -profile:a aac_he -vbr 5
						
						REM opus audio on audio encode		
						REM set audio_param=!audio_param! -c:a:!count! libopus -b:a:!count! !bitrate!k -af:a:!count! aformat=channel_layouts="7.1|5.1|stereo" -vbr:a:!count! on -compression_level:a:!count! 10
						
						set audio_param=!audio_param! -c:a:!count! libfdk_aac -profile:a:!count! aac_he -vbr:a:!count! 5
						REM calculate bitrate		
						
						
					)
					
									
					set /a count += 1
					
				)
						
							
			)	
			
			set mapping=!video_mapping! !audio_mapping! !other_mapping!
			
			echo Mapping Parameters: !mapping!
			echo Audio Parameters: !audio_param!

			
			REM set pixel format
			set pixelformat=
			if !10Bit!==1 set pixelformat= -pix_fmt yuv420p10le
			
			set HDRparam=
			if !HDR!==1 (
			
				REM set HDR values (use media Info to analyse)
				echo Mastering display luminance max:
				set /p mdmax=||set mdmax=4000
				
				echo max luminance was set to !mdmax!	
				echo.
				echo Mastering display luminance min:
				set /p mdmin=||set mdmin=50
			
				echo min luminance was set to !mdmin!	
				echo.
				echo Maximum Content Light Level MaxCLL:
				set /p MaxCLL=||set MaxCLL=0
				
				echo Maximum Content Light Level MaxCLL was set to !MaxCLL!	
				echo.
				echo Maximum Frame-Average Light Level MaxFALL:
				set /p MaxFALL=||set MaxFALL=0
			
				echo Maximum Frame-Average Light Level MaxFALL was set to !MaxFALL!	
				
				set luminance_params=
				
				if !MaxCLL! gtr 0 set luminance_params=:max-cll=!MaxCLL!,!MaxFALL!
				
				set HDRparam=:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G^(13250,34500^)B^(7500,3000^)R^(34000,16000^)WP(15635,16450^)L^(!mdmax!0000,!mdmin!^)!luminance_params!
			)
			
			
			REM copy ffmpeg to encoding dir
			copy ffmpeg.exe %workingdir% /Y > NUL
			echo converting required
			
			REM create lock file so multiple batches can be ran the same time
			echo lock file
			echo lock > "%%~pf%%~nf.lck"
			
			echo creating 1 minute sample of "%%f" with CFR at !CQ!
			
			REM create sample starting at min 25 for 1 minute
			
			echo start /low /wait %workingdir%/ffmpeg -y -i "%%f" -ss 00:25:00 -t 00:01:00 -max_muxing_queue_size 9999!pixelformat! !mapping! -c:v libx265 -x265-params "crf=!CQ!!x265params!!HDRparam!"!audio_param! -c:s copy "%workingdir%\%%~nf_sample.mkv"
			
			start /low /wait %workingdir%/ffmpeg -y -i "%%f" -ss 00:25:00 -t 00:01:00 -max_muxing_queue_size 9999!pixelformat! !mapping! -c:v libx265 -x265-params "crf=!CQ!!x265params!!HDRparam!"!audio_param! -c:s copy "%workingdir%\%%~nf_sample.mkv"
			
			echo converted to x265 with CQ !CQ! and audio at %a_bitrate%k
			
			REM set final quality mode depending on sample size
			for %%a in ("%workingdir%\%%~nf_sample.mkv") do (
				echo sample size is %%~za 
				
				if %%~za lss 30000000 set CQ=20
				if %%~za gtr 30000000 set CQ=21
				if %%~za gtr 45000000 set CQ=22
				if %%~za gtr 60000000 set CQ=22
				if %%~za gtr 75000000 set CQ=23
				if %%~za gtr 125000000 set CQ=24
				if %%~za gtr 220000000 set CQ=25
				if %%~za gtr 300000000 set CQ=26
				if %%~za gtr 450000000 set CQ=27
			)
			echo using quality mode ou !CQ! for "%%f"
			
			set dir=%%~pf
			set dir=!dir:~0,-1!
			
			echo copy "%%f"" to working dir from !dir!
			robocopy  "!dir!" "%workingdir%" "%%~nf.mkv"
			
			if not exist "%workingdir%\%%~nf_x265_10Bit.mkv" (

				start /low /wait %workingdir%/ffmpeg -y -i "%workingdir%\%%~nf.mkv" -max_muxing_queue_size 9999!pixelformat! !mapping! -c:v libx265 -x265-params "crf=!CQ!!x265params!!HDRparam!"!audio_param_0!!audio_param_1! -c:s copy "%workingdir%\%%~nf_x265_10Bit.mkv"
				if %errorlevel% == 0 (
					echo convert successfull
					del "%%~pf%%~nf.lck"
					del "%workingdir%\%%~nf.mkv"
					echo converted to x265 with CQ !CQ! and OPUS audio at !audio_param_0! !audio_param_1!   > %workingdir%\%%~nf_convert.txt
					move "%workingdir%\%%~nf_x265_10Bit.mkv" "!dir!" 
					echo move "%workingdir%\%%~nf_x265_10Bit.mkv" "!dir!" 
					echo unlocking folder
				) else (
					echo Converting failed 
					rem del "%workingdir%\%%~nf_x265.mkv"
					echo converted to x265 with CQ !CQ! and OPUS audio at !audio_param_0! !audio_param_1!  > %workingdir%\%%~nf_convert_failed.txt
					echo unlocking folder
					del "%%~pf%%~nf.lck"
					pause
					goto :break
				)
			
			) else ( 
				echo skipping "%workingdir%\%%~nf_x265_10Bit.mkv" as export file in specified quality exists
				echo unlocking folder
				del "%%~pf%%~nf.lck"		
				
			)

			echo copy converted file back to original folder
			del "%%~pf%%~nf.lck"
		)
			
)		
goto :eof