JustPaste.it

:Workflow.1

 ::batch generate dv with cm analyze
 echo.
 echo.
echo \033[36m          ================== | "%cmdcolor%"
echo \033[36m          - DoVi_Generator - | "%cmdcolor%"
echo \033[36m          ================== | "%cmdcolor%"
echo.
echo \033[92m-------------------------------------------------------------------------------------------------------------------- | "%cmdcolor%"
if /i "%Mode_31%"=="CM" echo -- CM_Analyze: This workflow will convert an HDR10 video to DoVi using official Dolby Vision tools
if /i "%Mode_31%"=="CM" echo -- Require Dolby metafier.exe , cm_analyze.exe, lavfilter, madvr and avisynth^+
if /i "%Mode_31%"=="RESOLVE" echo -- DaVinci Resolve: This workflow will convert an HDR10 video to DoVi using official Dolby Vision algorithm
if /i "%Mode_31%"=="RESOLVE" echo -- Require Dolby metafier.exe , Resolve.exe and avisynth^+
echo -- CM and Metafier can be found here: https://customer.dolby.com/content-creation-and-delivery/dolby-vision-professional-tools
echo -- Input must be HDR MKV/TS/M2TS/MP4/MOV(prores) ^for the video and ^for the shotlist external files: MDL5-bat/xml/rpu/json/txt
echo -- Can Batch: Input can be a folder with files or a single file
echo -- if no external shotlist and ^if input has dynamic metadata, it will use its scene cuts.
if /i "%Mode_31%"=="CM" echo -- If input has no dynamic metadata and no external list, madvr will be used for the shot list
if /i "%Mode_31%"=="CM" echo -- You can perform frame by frame analysis at line 294 but this is lower quality than shot by shot metadata
echo -- if you dont provide external external config, the same L5/MDL will be used for all the videos in batch mode (see ''MD-L5 config example ^for 3-1.bat'' ^in tool folder)
echo -- External files: must be same path/filename as input. (bat/xml/rpu/json/txt). External files are prioritized.
echo -- "IGNOREMETADATA" ^in the filename will ignore the metadata within the video and force scene cuts detection
echo \033[92m--------------------------------------------------------------------------------------------------------------------- | "%cmdcolor%"
echo.
set batch.info=y
if /i "%Mode_31%"=="CM" if not exist "%~dp0tools\cm_analyze.exe" echo \033[31m cm_analyze.exe is missing from the tools folder, download it here: https://customer.dolby.com/content-creation-and-delivery/dolby-vision-professional-tools| "%cmdcolor%" & pause & exit
if not exist "%~dp0tools\metafier.exe" echo \033[31m metafier.exe is missing from the tools folder, download it here: https://customer.dolby.com/content-creation-and-delivery/dolby-vision-professional-tools| "%cmdcolor%"& pause & exit

if exist "%temp_folder%temp.folder77" rmdir /Q /S "%temp_folder%temp.folder77"
MD "%temp_folder%temp.folder77"
set TEMP=%temp_folder%temp.folder77\

:: folder with files input
echo Drag and drop folder with HEVC video files or a single file and press enter...
set /p folder=

setlocal enabledelayedexpansion
set count=0
:: find how many files there are to process
for /r %folder% %%F in (*) do (
    set /a "count+=1"
    set "file!count!=%%~fF"
)
:: set files to variables
>variables.txt (
    for /l %%i in (1,1,%count%) do (
        echo file%%i=!file%%i!
    )
)

for /f "usebackq tokens=1,* delims==" %%a in ("variables.txt") do (
    set "%%a=%%b"
)

del variables.txt
:: set filenames filepaths and file extensions to variables
for /l %%i in (1,1,%count%) do (
    for %%j in ("!file%%i!") do (
        set "filename%%i=%%~nj"
        set "filepath%%i=%%~dpj"
        set "fileext%%i=%%~xj"
        set f%%i=y
    )
)

set single.file=n
if [%fileext1%]==[] (
     for %%i in (!folder!) do set filename1=%%~ni
     for %%i in (!folder!) do set filepath1=%%~di%%~pi
     for %%i in (!folder!) do set fileext1=%%~xi
     set single.file=y
)

::####################################################################################
::################################# check first input #########################################
::####################################################################################

"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=JSON > "%TEMP%mediainfo.JSON"

if /i "%fileext1%"==".mov" echo prores not supported in Resolve mode, switching to CM_Analyze...& set Mode_31=CM& goto :LL5
if /i "%fileext1%"==".hevc" echo raw hevc not supported. Input must be: MKV/TS/M2TS/MP4/MOV(prores) ... & pause & exit
if /i "%fileext1%"==".h265" echo raw h265 not supported. Input must be: MKV/TS/M2TS/MP4/MOV(prores) ... & pause & exit

"%JQ_path%" .media.track[1].MasteringDisplay_Luminance "%TEMP%mediainfo.JSON" > "%TEMP%masteringDL.txt"
"%JQ_path%" .media.track[1].MasteringDisplay_ColorPrimaries "%TEMP%mediainfo.JSON" > "%TEMP%col.txt"
"%JQ_path%" .media.track[1].HDR_Format_Profile "%TEMP%mediainfo.JSON" > "%TEMP%check.DV.txt"

for /f "delims=" %%x in (%TEMP%masteringDL.txt) do set MDL3=%%x
for /f "delims=" %%x in (%TEMP%col.txt) do set col=%%x
set col=%col:~1,-1%& set MDL3=%MDL3:~1,-1%& set HLG=n& set P5BL=n& set P7input=n& set FELinput=n

type "%TEMP%mediainfo.JSON" | findstr HLG >"%TEMP%pq.txt"
findstr /m "HLG" "%TEMP%pq.txt" >Nul
if %errorlevel%==0 set HLG=y& set col=& set MDL3=Hybrid Log Gamma

findstr /c:"05" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 set P5BL=y& set col=& set MDL3=Profile 5 DV

findstr /c:"07" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 set P7input=y

::check for FEL input
if /i "%Bake_FEL_31%"=="NO" goto :skipbakefelcheck
if /i "%P7input%"=="n" goto :skipbakefelcheck

"%ffmpeg_path%" -i "%filepath1%%filename1%%fileext1%" -c:v copy -to 3 -bsf:v hevc_mp4toannexb -f hevc -loglevel quiet - | "%dovi_tool_path%" extract-rpu -o "%TEMP%%filename1%_RPU.bin" - > nul
"%dovi_tool_path%" info --input "%TEMP%%filename1%_RPU.bin" -f 20 > "%TEMP%temp.rpu.json"
type "%TEMP%temp.rpu.json" | findstr el_type > "%TEMP%subprofile.json"
findstr /c:"FEL" "%TEMP%subprofile.json" >Nul
if %errorlevel%==0 set FELinput=y

:skipbakefelcheck

if /i "%encode_DDP%"=="NO" goto :skipaudio
if /i "%container%"=="MP4" goto :skipaudio

::####################################################################################
::################################# audio prompt ############################################
::####################################################################################

:: check if lossless audio present, if not skip the user prompt.
"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=Audio;%%Format%% --LogFile="%TEMP%audio.format.txt" >Nul
findstr /i /c:"MLP" "%TEMP%audio.format.txt" >Nul
if not %errorlevel%==0 set mlp=n
findstr /i /c:"DTS" "%TEMP%audio.format.txt" >Nul
if not %errorlevel%==0 set dts=n
findstr /i /c:"PCM" "%TEMP%audio.format.txt" >Nul
if not %errorlevel%==0 set pcm.au=n
if "%mlp%"=="n" if "%dts%"=="n"  if "%pcm.au%"=="n" goto :skip
echo.&echo.
echo \033[36m  =============== | "%cmdcolor%"
echo \033[36m  - INPUT INFO  - | "%cmdcolor%"
echo \033[36m  =============== | "%cmdcolor%"
echo.
:: check audio tracks info
"%ffprobe_path%" -v error -select_streams a -show_entries stream=index,codec_name,channel_layout:stream_tags=language -of default=noprint_wrappers=1 "%filepath1%%filename1%%fileext1%"
echo.
:convertaudio
:: user input for triggering audio encoding
echo   Do you want to convert the audio to DDP^? (default= n ) 
echo.
echo --^> YES= y
echo --^> NO= n
set /p convert_audio=
if "%convert_audio%"=="" set convert_audio=n
if /i "%convert_audio%"=="y" set convert_audio=y
if /i "%convert_audio%"=="n" set convert_audio=n
if /i "%convert_audio%"=="yes" set convert_audio=y
if /i "%convert_audio%"=="no" set convert_audio=n
if not "%convert_audio%"=="n" if not "%convert_audio%"=="y" set convert_audio=n
:skipaudio

if exist "%filepath1%%filename1%.bat" goto :skip.manual.l5
if not "%fileext1%"==".mkv" if not "%fileext1%"==".ts" if not "%fileext1%"==".m2ts" if not "%fileext1%"==".mp4" if not "%fileext1%"==".mov" goto :skip.manual.l5
if /i "%FELinput%"=="y" if /i "%Bake_FEL_31%"=="YES" goto :croppingL5
if /i "%P5BL%"=="y" goto :croppingL5

::####################################################################################
::################################# MDL prompt ############################################
::####################################################################################

echo.
echo \033[92m ------------------------------------------------ | "%cmdcolor%"
echo    BL Mastering Display Luminance and Colors:
echo --^> %MDL3% %col%
echo \033[92m ------------------------------------------------ | "%cmdcolor%"
echo.
:LL5
echo What is the Mastering Display Luminance/primaries^? (default=20)
echo.

echo --^> 1000nits(P3)= 20
echo --^> 2000nits(P3)= 30
echo --^> 4000nits(P3)= 7
echo.
echo --^> 1000nits(BT2020)= 21
echo --^> 2000nits(BT2020)= 31
echo --^> 4000nits(BT2020)= 8

set /p MDL=
if not "%MDL%"=="20" if not "%MDL%"=="21" if not "%MDL%"=="30" if not "%MDL%"=="31" if not "%MDL%"=="7" if not "%MDL%"=="8" set MDL=20
echo.

:croppingL5

if /i "%auto.crop%"=="NO" goto :skip.crop
::check bl resolution and crop if nescessary
"%JQ_path%" .media.track[1].Height "%TEMP%mediainfo.JSON" > "%TEMP%Height.c.txt"
for /f "delims=" %%x in (%TEMP%Height.c.txt) do set H=%%x
set H=%H:~1,-1%
if not "%H%"=="2160" if not "%H%"=="1080" set cropped=YES& set autoL5=m& set left=0& set right=0& set top=0& set bottom=0& set crop_left=0& set crop_right=0& set crop_top=0& set crop_bottom=0& goto :skip.manual.l5

:skip.crop

::####################################################################################
::################################# L5 prompt ############################################
::####################################################################################

echo   Manual or Auto Level 5^? (default= m)
echo.
echo --^> AUTO= a 
echo --^> MANUAL= m
echo.
set /p autoL5=
if /i "%autoL5%"=="" set autoL5=m
if /i "%autoL5%"=="m" set autoL5=m
if /i "%autoL5%"=="a" set autoL5=a
if not "%autoL5%"=="a" if not "%autoL5%"=="m" set autoL5=m
if /i "%autoL5%"=="a" goto :skip.manual.l5

set cropcheck="%filepath1%%filename1%%fileext1%"
if not "%fileext1%"==".ts" if not "%fileext1%"==".m2ts" goto :skip.sample

echo.
echo Raw HEVC or TS/M2TS input, making a MKV sample to allow avspmod to read the input...
"%mkvmerge_path%" --output ^"%TEMP%sample.mkv^" --compression 0:none --no-audio --no-subtitles ^"^(^" ^"%filepath1%%filename1%%fileext1%^" ^"^)^" --split parts:00:00:00-00:05:00 > Nul
set cropcheck="%TEMP%sample.mkv"

:skip.sample
echo DirectShowSource(%cropcheck%) > "%TEMP%%filename1%.avs"
echo Levels(0, 2.5, 255, 0, 255, coring=false) >> "%TEMP%%filename1%.avs"

start "" "%AvsPmod_path%" "%TEMP%%filename1%.avs"

set left=0& set right=0& set top=0& set bottom=0
set crop_left=0& set crop_right=0& set crop_top=0& set crop_bottom=0

echo Enter the Left L5 offset (default = 0) & set /p left=
echo Enter the Right L5 offset (default = 0) & set /p right=
echo Enter the Top L5 offset (default = 0) & set /p top=
echo Enter the Bottom L5 offset (default = 0) & set /p bottom=

set crop_left=%left%
set crop_right=%right%
set crop_top=%top%
set crop_bottom=%bottom%

set /a "check=left %% 2"
if %check% equ 1 (
    set /a "crop_left+=1"
)
set /a "check=right %% 2"
if %check% equ 1 (
    set /a "crop_right+=1"
)
set /a "check=top %% 2"
if %check% equ 1 (
    set /a "crop_top+=1"
)
set /a "check=bottom %% 2"
if %check% equ 1 (
    set /a "crop_bottom+=1"
)

:skip.manual.l5

if /i "%Mode_31%"=="RESOLVE" (
    :: Check if Resolve is already running
    tasklist /FI "IMAGENAME eq Resolve.exe" 2>Nul | findstr /i "Resolve.exe" >Nul
    if errorlevel 1 (
        :: Resolve not running, launch it
        echo \033[92m  Launching Resolve, please wait... | "%cmdcolor%"
        start "" "%resolve_exe%"
        timeout /t 10 /nobreak >Nul

        :: Pause and ask user to open a project
        echo Open a Resolve project and press any key to continue...
        pause >Nul
    )
)

::######################################################################################
::################################# Analysis Tuning ############################################
::######################################################################################

echo Which Tuning do you want to use^? (default=%default_tuning%) (0= darkest / 5= brightest)
echo.
echo --^>  0= Old legacy mode  (^not recommended)
echo --^>  1= Most Highlight Detail/Most Mapping (Safest, no clipping)
echo --^>  2= More Highlight Detail/More Mapping
echo --^>  3= Balanced (May clip ^if the content is brighter than your TV)
echo --^>  4= Less Highlight Detail/Less Mapping (will have clipping ^if the content is brighter than your TV)
echo --^>  5= Least Highlight Detail/Least Mapping (will have clipping ^if the content is brighter than your TV)

echo.
set /p L1_Tuning=
if /i "%L1_Tuning%"=="" set L1_Tuning=%default_tuning%
if not "%L1_Tuning%"=="0" if not "%L1_Tuning%"=="1" if not "%L1_Tuning%"=="2" if not "%L1_Tuning%"=="3" if not "%L1_Tuning%"=="4" if not "%L1_Tuning%"=="5" set L1_Tuning=%default_tuning%

::###########################################################################################
::########################################## LOOP #############################################
::###########################################################################################

:loop.CM

if exist "%temp_folder%temp.folder77" rmdir /Q /S "%temp_folder%temp.folder77"
MD "%temp_folder%temp.folder77"
set TEMP=%temp_folder%temp.folder77\

if exist "%filepath1%%filename1%.bin" copy /y "%filepath1%%filename1%.bin" "%TEMP%" >Nul 
if exist "%filepath1%%filename1%.bin" rename "%TEMP%%filename1%.bin"  "%filename1%_original.bin"  >Nul 
if exist "%filepath1%%filename1%.bin" set RPU="%TEMP%%filename1%_original.bin"

if exist "%filepath1%%filename1%.xml" copy /y "%filepath1%%filename1%.xml" "%TEMP%" >Nul 
if exist "%filepath1%%filename1%.xml" rename "%TEMP%%filename1%.xml"  "%filename1%_original.xml"  >Nul

if exist "%filepath1%%filename1%.json" copy /y "%filepath1%%filename1%.json" "%TEMP%" >Nul 
if exist "%filepath1%%filename1%.json" rename "%TEMP%%filename1%.json"  "%filename1%_original.json"  >Nul 


::reset variables
set OSC=
set DV=n
set felinput=n
set P7BL=n
set P8BL=n
set P5BL=n
set HLG=n

echo Processing:  "%filename1%%fileext1%"

::workaround for input with )
set oldfilename=%filename1%
set newfilename=%filename1:)=%
rename "%filepath1%%filename1%%fileext1%" "%newfilename%%fileext1%"
set filename1=%newfilename%

if /i  "%fileext1%"==".bat" goto :end
if /i  "%fileext1%"==".bin" goto :end
if not "%fileext1%"==".mkv" if not "%fileext1%"==".ts" if not "%fileext1%"==".m2ts" if not "%fileext1%"==".mp4" if not "%fileext1%"==".mov" echo Invalid extension, skipping "%filename1%%fileext1%" & goto :end
if /i "%same_input_output%"=="YES" set output_path=%filepath1%

::#########################################################################################
::################################# READ INPUT TYPE ############################################
::#########################################################################################


"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=JSON > "%TEMP%mediainfo.JSON"

echo %filename1% > "%TEMP%filename1.txt"
::check if BL has keywords in the filename
findstr /i /c:"KEEPAUDIO" "%TEMP%filename1.txt" >Nul
if %errorlevel%==0 set mux_all_audio=YES& set mux_all_sub=YES
findstr /i /c:"DONTMUX" "%TEMP%filename1.txt" >Nul
if %errorlevel%==0 set MUX=NO
findstr /i /c:"KEEPPRORES" "%TEMP%filename1.txt" >Nul
if %errorlevel%==0 set keep_prores=YES
findstr /i /c:"]" "%TEMP%filename1.txt" >Nul
if %errorlevel%==0 Echo Special Character ''^]'' in filename/path is not allowed...& pause & exit
findstr /i /c:"[" "%TEMP%filename1.txt" >Nul
if %errorlevel%==0 Echo Special Character ''^]'' in filename/path is not allowed...& pause & exit

:: Read BL input properties
"%JQ_path%" .media.track[1].HDR_Format "%TEMP%mediainfo.JSON" > "%TEMP%check.HDR10plus.txt"
"%JQ_path%" .media.track[1].HDR_Format_Profile "%TEMP%mediainfo.JSON" > "%TEMP%check.DV.txt"
"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=JSON > "%TEMP%mediainfoinput.JSON"
"%JQ_path%" .media.track[1].FrameCount "%TEMP%mediainfoinput.JSON" > "%TEMP%FrameCountinput.txt"
"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=Video;%%Width%%\r\n ^ *.ts *.mp4 *.mkv *.m2ts *.mov *.hevc *.h265 *.avi >"%TEMP%Width.txt" 
"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=Video;%%Height%%\r\n ^ *.ts *.mp4 *.mkv *.m2ts *.mov *.hevc *.h265 *.avi >"%TEMP%Height.txt" 
"%mediainfo_path%" "%filepath1%%filename1%%fileext1%" --output=Video;%%FrameRate%%\r\n ^ *.ts *.mp4 *.mkv *.m2ts *.mov *.hevc *.h265 *.avi >"%TEMP%Framerate.txt" 

for /f "tokens=1 delims=" %%a in ('type "%TEMP%Width.txt"') do ( set "Width_input=%%a" ) 
for /f "tokens=1 delims=" %%a in ('type "%TEMP%Height.txt"') do ( set "Height_input=%%a" ) 
for /f "tokens=1 delims=(,)" %%a in ('type "%TEMP%Framerate.txt"') do ( set "FPS=%%a" )
for /f "tokens=1 delims=" %%a in ('type "%TEMP%FrameCountinput.txt"') do ( set "frameCount1=%%a" )
set frameCount1=%frameCount1:"=%

set requirelibplacebo=n
::check for HLG
type "%TEMP%mediainfo.JSON" | findstr HLG >"%TEMP%pq.txt"
findstr /m "HLG" "%TEMP%pq.txt" >Nul
if %errorlevel%==0 set HLG=y& set requirelibplacebo=y

::check for P5
findstr /c:"05" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 set P5BL=y& set requirelibplacebo=y

::check for P8
findstr /c:"08" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 set P8BL=y

::check for P7
findstr /c:"07" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 set P7BL=y

if not "%fileext1%"==".mov" set job=job.3.1& goto :tracks.Info
:job.3.1

::####################################################################################
::################################# AUTO L5 #############################################
::####################################################################################

if exist "%filepath1%%filename1%.bat" goto :skip.measure
if not "%autoL5%"=="a" goto :skip.measure
echo.
echo Making a small sample from the input...
echo.

::make a 3 min sample. (in case input is ts/m2ts which doesnt work in detect borders)
"%mkvmerge_path%" --output ^"%TEMP%chunk.mkv^" --compression 0:none --no-audio --no-subtitles ^"^(^" ^"%filepath1%%filename1%%fileext1%^" ^"^)^" --split parts:00:00:00-00:05:00 > Nul
echo Done!
echo.
:: measure letterbox with detectborders
echo Measuring the letterbox...
echo.

set left=0& set right=0& set top=0& set bottom=0
set crop_left=0& set crop_right=0& set crop_top=0& set crop_bottom=0
"%detectborders_path%" --ffmpeg-path="%ffmpeg_path%" --input-file="%TEMP%chunk.mkv" --log-file="%TEMP%\borders.txt"
echo.
echo Done!
:: read borders detection results
for /f "tokens=2 delims=(,-)" %%a in ('type "%TEMP%borders.txt"') do (
    set "left=%%a"
)
for /f "tokens=4 delims=(,-)" %%a in ('type "%TEMP%borders.txt"') do (
    set "right=%%a"
)
for /f "tokens=3 delims=(,-)" %%a in ('type "%TEMP%borders.txt"') do (
    set "top=%%a"
)
for /f "tokens=5 delims=(,-)" %%a in ('type "%TEMP%borders.txt"') do (
    set "bottom=%%a"
)

:: set borders to 0 in case l5 variables are empty (better than having wrong value).
if [%right%]==[] set right=0
if [%left%]==[] set left=0
if [%right%]==[] set right=0
if [%bottom%]==[] set bottom=0

set crop_left=%left%
set crop_right=%right%
set crop_top=%top%
set crop_bottom=%bottom%

echo.
::echo borders measurements for verification.
echo ---------------------------------
echo --^> left border: %left%
echo --^> right border: %right%
echo --^> top border: %top%
echo --^> bottom border: %bottom%
echo ---------------------------------
echo.

:skip.measure

::################################### prores crop ###########################################

if exist "%filepath1%%filename1%.bat" call "%filepath1%%filename1%.bat"

if /i "%Mode_31%"=="RESOLVE"  if not exist "%~dp0tools\write_resolve_dv_generate.py" echo "write_resolve_dv_generate.py" is missing from the tools folder... Update your folder... & pause & exit

set crop_left=%left%
set crop_right=%right%
set crop_top=%top%
set crop_bottom=%bottom%

set /a "check=left %% 2"
if %check% equ 1 (
    set /a "crop_left+=1"
)
set /a "check=right %% 2"
if %check% equ 1 (
    set /a "crop_right+=1"
)
set /a "check=top %% 2"
if %check% equ 1 (
    set /a "crop_top+=1"
)
set /a "check=bottom %% 2"
if %check% equ 1 (
    set /a "crop_bottom+=1"
)


::#############################################################################
::################################ DEMUX ########################################
::#############################################################################

if /i "%fileext1%"==".mov" goto :skipdemux
if not "%fileext1%"==".mkv" goto :notmkv
if /i "%container%"=="MKV" if /i "%export.subs%"=="NO" if /i "%mux_all_audio%"=="YES" if /i "%mux_all_sub%"=="YES" "%mkvextract_path%" "%filepath1%%filename1%%fileext1%" tracks 0:"%TEMP%BL_input.hevc" & set HDR="%TEMP%BL_input.hevc"& goto :skipdemux
"%mkvextract_path%" "%filepath1%%filename1%%fileext1%" tracks 0:"%TEMP%BL_input.hevc" %AUDIO1% %AUDIO2% %AUDIO3% %AUDIO4% %AUDIO5% %SM1% %SM2% %SM3% %SM4% %SM5% %SM6% %SM7% %SM8% %SM9% %SM10% %SM11% %SM12% %SM13% %SM14% %SM15% %SM16% %SM17% %SM18% %SM19% %SM20% %SM21% %SM22% %SM23% %SM24% %SM25% %SM26%
set HDR="%TEMP%BL_input.hevc"& goto :skipdemux
     
:notmkv
     echo MUXOPT --no-pcr-on-video-pid --new-audio-pes --hdmv-descriptors --vbr --demux --vbv-len=500 > "%TEMP%1.meta"
     echo V_MPEGH/ISO/HEVC, "%filepath1%%filename1%%fileext1%", track=%T1.ID% >> "%TEMP%1.meta"
     for /L %%i in (2,1,%count2%) do ( 
     if not "!T%%i.Format!"=="FLAC" if not "!T%%i.Format!"=="null" if not "!T%%i.sub!"=="y" echo !TSmuxer%%i.Format!, "%filepath1%%filename1%%fileext1%", track=!T%%i.ID!, lang=!T%%i.Lang! >> "%TEMP%1.meta"
     if "!T%%i.Format!"=="Timed Text" echo S_TEXT/UTF8, "%filepath1%%filename1%%fileext1%",font-name="Arial",font-size=65,font-color=0xffffffff,bottom-offset=24,font-border=5,text-align=center,video-width=1920,video-height=1080,fps=%FPS%, track=!T%%i.ID!, lang=!T%%i.Lang! >> "%TEMP%1.meta"
     if "!T%%i.Format!"=="UTF-8" echo S_TEXT/UTF8, "%filepath1%%filename1%%fileext1%",font-name="Arial",font-size=65,font-color=0xffffffff,bottom-offset=24,font-border=5,text-align=center,video-width=1920,video-height=1080,fps=%FPS%, track=!T%%i.ID!, lang=!T%%i.Lang! >> "%TEMP%1.meta" 
     if "!T%%i.Format!"=="PGS" echo S_HDMV/PGS, "%filepath1%%filename1%%fileext1%",fps=%FPS%, track=!T%%i.ID!, lang=!T%%i.Lang! >> "%TEMP%1.meta"
)
"%tsmuxer_path%" "%TEMP%1.meta" "%TEMP%"
set HDR="%TEMP%%filename1%.track_%T1.ID%.hevc"

:skipdemux

::###############################################################################
::################################ BAKE FEL #########################################
::###############################################################################

if /i "%P7BL%"=="n" goto :skipbakefel

"%ffmpeg_path%" -i "%filepath1%%filename1%%fileext1%" -c:v copy -to 3 -bsf:v hevc_mp4toannexb -f hevc -loglevel quiet - | "%dovi_tool_path%" extract-rpu -o "%TEMP%check_RPU.bin" - > nul
"%dovi_tool_path%" info --input "%TEMP%check_RPU.bin" -f 20 > "%TEMP%temp.rpu.json"
type "%TEMP%temp.rpu.json" | findstr el_type > "%TEMP%subprofile.json"
findstr /c:"MEL" "%TEMP%subprofile.json" >Nul
if %errorlevel%==0 goto :skipbakefel

set felinput=y
if /i "%Bake_FEL_31%"=="NO" echo FEL DETECTED... The script is configured to discard FEL and create metadata that will be valid for the HDR10 layer only, see line 300 ...& pause & goto :skipbakefel

cd /d "%TEMP%"
echo.
echo Demuxing layers from P7 FEL input...
echo.

"%dovi_tool_path%" demux -i %HDR%

echo.
if exist "%filepath1%%filename1%.bin" (
    echo External RPU found. Will use it instead of extracting it from the video..... "%filepath1%%filename1%.bin"
) else (
    echo Extracting RPU from P7 FEL input...
)
echo.

if not exist "%filepath1%%filename1%.bin" "%dovi_tool_path%" extract-rpu "%TEMP%EL.hevc" -o "%TEMP%%filename1%_original.bin"
if not exist "%filepath1%%filename1%.bin" copy /y "%TEMP%%filename1%_original.bin" "%output_path%" >Nul
if not exist "%filepath1%%filename1%.bin" set RPU="%TEMP%%filename1%_original.bin"

if /i "%no_nvidia_check%"=="YES" goto :nvidiacheck
nvidia-smi  > "%TEMP%checknvidia.txt" 2> Nul
findstr /c:"NVIDIA" "%TEMP%checknvidia.txt" > Nul
if %errorlevel%==1 echo No Nvidia GPU detected, will use FFMS2... & set force_ffms2=YES

:nvidiacheck

echo.
cd /d "%output_path%"
if /i "%force_ffms2%"=="NO" "%DGIndexNV_path%" -i "%TEMP%BL.hevc" -o "%TEMP%BL.dgi" -h -a
if /i "%force_ffms2%"=="NO" "%DGIndexNV_path%" -i "%TEMP%EL.hevc" -o "%TEMP%EL.dgi" -h -a
if /i "%force_ffms2%"=="YES" "%mkvmerge_path%" --output ^"%TEMP%BL.mkv^" --compression 0:none --no-audio --no-subtitles ^"^(^" ^""%TEMP%BL.hevc"^" ^"^)^"
if /i "%force_ffms2%"=="YES" "%mkvmerge_path%" --output ^"%TEMP%EL.mkv^" --compression 0:none --no-audio --no-subtitles ^"^(^" ^""%TEMP%EL.hevc"^" ^"^)^"
if /i "%force_ffms2%"=="YES" "%ffmsindex%" "%TEMP%BL.mkv" "%TEMP%BL.ffindex"
if /i "%force_ffms2%"=="YES" "%ffmsindex%" "%TEMP%EL.mkv" "%TEMP%EL.ffindex"

:skipdgdemux
if /i "%force_ffms2%"=="NO" echo LoadPlugin("%DGDecodeNV.dll%") > "%TEMP%script.avs" 
if /i "%force_ffms2%"=="YES" echo LoadPlugin("%ffms2%")  > "%TEMP%script.avs" 
echo LoadPlugin("%DoViBaker%") >> "%TEMP%script.avs"
echo LoadPlugin("%~dp0tools\avsresize_r21\x64\Release\avsresize.dll") >> "%TEMP%script.avs"
if /i "%force_ffms2%"=="YES" echo bl = FFVideoSource("%TEMP%BL.mkv", threads=1, cachefile="%TEMP%BL.ffindex") >> "%TEMP%script.avs"
if /i "%force_ffms2%"=="YES" echo el = FFVideoSource("%TEMP%EL.mkv", threads=1, cachefile="%TEMP%EL.ffindex") >> "%TEMP%script.avs"
if /i "%force_ffms2%"=="NO" echo bl = DGSource("%TEMP%BL.dgi") >> "%TEMP%script.avs" 
if /i "%force_ffms2%"=="NO" echo el = DGSource("%TEMP%EL.dgi") >> "%TEMP%script.avs"
echo SetFilterMTMode("DoViBaker",2)  >> "%TEMP%script.avs"
if /i "%force_ffms2%"=="NO" echo DoViBaker(bl, el, rpu=%RPU%) >> "%TEMP%script.avs"
if /i "%force_ffms2%"=="YES" echo DoViBaker(bl, el) >> "%TEMP%script.avs"
echo %Prefetch% >> "%TEMP%script.avs"
echo z_ConvertFormat(pixel_type="YUV422P10",colorspace_op="rgb:st2084:2020:full=>2020ncl:st2084:2020:limited",dither_type="error_diffusion",resample_filter="spline36",resample_filter_uv="spline36",chromaloc_op="left=>top_left") >> "%TEMP%script.avs"
echo Crop(%crop_right%, %crop_top%, -%crop_left%, -%crop_bottom%) >>  "%TEMP%script.avs"

set index="%TEMP%script.avs"

"%dovi_tool_path%" info --input %RPU% -f 24 > "%TEMP%raw.txt"

set MDP_fel=P3
set MDL=20& set min=1& set MDL1=1000
::MD color
echo %col% >  "%TEMP%primaries.txt"
findstr /c:"2020" "%TEMP%primaries.txt" >nul
if !errorlevel!==0 set MDP_fel=2020

::1000nits MDL
findstr /c:"\"source_max_pq\": 3079" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=20& set min=1& set MDL1=1000
::2000nits MDL
findstr /c:"\"source_max_pq\": 3388" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=30& set min=1& set MDL1=2000
::4000nits MDL
findstr /c:"\"source_max_pq\": 3696" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=7& set min=50& set MDL1=4000
::10000nits MDL (should not be possible)
findstr /c:"\"source_max_pq\": 4095" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=7& set min=50& set MDL1=10000

if /i "%MDP_fel%"=="2020" if /i "%MDL%"=="20" set MDL=21
if /i "%MDP_fel%"=="2020" if /i "%MDL%"=="30" set MDL=31
if /i "%MDP_fel%"=="2020" if /i "%MDL%"=="7" set MDL=8

set DV=y
set OSC=_OSC
goto :adjust_shotlist

:skipbakefel

::remove EL
if /i "%P7BL%"=="y" (
    cd /d "%TEMP%"
    "%dovi_tool_path%" demux -i %HDR%
    if "%container%"=="TS" if "%mlp%"=="y" set MUX=NO
    set HDR="%TEMP%BL.hevc"
    cd /d "%output_path%"
)

::L6 json for rpu generation from json
(
echo {
echo    "min_pq": 3079,
echo    "max_pq": 7,
echo    "remove_cmv4": false,
echo    "level6": {
echo        "max_display_mastering_luminance": 1000,
echo        "min_display_mastering_luminance": 50,
echo        "max_content_light_level": 0,
echo        "max_frame_average_light_level": 0
echo    }
echo }
) > "%TEMP%L66.json"

::########################################################################################
::################################# External shot list ############################################
::########################################################################################

if /i "%FIXapple%"=="YES" "%ffmpeg_path%" -vsync drop -i %HDR% -c copy -bsf:v hevc_metadata=tick_rate=24000/1001:num_ticks_poc_diff_one=1 "%TEMP%HDR.fixed.hevc" & set HDR="%TEMP%HDR.fixed.hevc"

if /i "%HLG%"=="y" goto :encode.prores
if not "%P5BL%"=="y" findstr /i /c:"ignoremetadata" "%TEMP%filename1.txt" >nul && goto :skipinternalshotlist
if not "%P5BL%"=="y" if /i "%force.FBF%"=="YES" set shotlist=--longplay-analysis& goto :encode.prores
if exist "%filepath1%%filename1%.txt" goto :encode.prores

::external rpu
if exist "%TEMP%%filename1%_original.bin" (
     set RPU="%TEMP%%filename1%_original.bin"
     set DV=y& echo Exporting shots list from an external DV RPU...
     set OSC=_OSC
     goto :adjust_shotlist
)

::external XML
if exist "%TEMP%%filename1%_original.xml" (
     "%dovi_tool_path%" generate --xml "%TEMP%%filename1%_original.xml" --canvas-width %Width_input% --canvas-height %Height_input% --rpu-out "%TEMP%%filename1%_original.bin" >Nul
     set RPU="%TEMP%%filename1%_original.bin"
     set DV=y& echo Exporting shots list from a DV XML...
     goto :adjust_shotlist
)

:: external json hdr10plus
if exist "%TEMP%%filename1%_original.json" (
     "%dovi_tool_path%" generate --hdr10plus-json "%TEMP%%filename1%_original.json" --json "%TEMP%L66.json" --rpu-out "%TEMP%rpu.hdr10plus.bin" >Nul
     set RPU="%TEMP%rpu.hdr10plus.bin"
     set DV=y& echo Exporting shots list from an external HDR10plus JSON...
     set OSC=_OSC
     goto :adjust_shotlist
)

::internal P7 RPU
if /i "%P7BL%"=="y" (
     "%dovi_tool_path%" extract-rpu -i "%TEMP%EL.hevc" -o "%TEMP%%filename1%_original.bin" 
     set RPU="%TEMP%%filename1%_original.bin"
     copy /y  "%TEMP%%filename1%_original.bin" "%output_path%" >Nul
     set DV=y& echo Exporting shots list from a DV RPU...
     set OSC=_OSC
     goto :adjust_shotlist
)

::internal P8/P5 RPU
findstr /c:"dvhe" "%TEMP%check.DV.txt" >Nul
if %errorlevel%==0 (
     "%dovi_tool_path%" extract-rpu -i %HDR% -o "%TEMP%%filename1%_original.bin" 
     set RPU="%TEMP%%filename1%_original.bin"
     copy /y  "%TEMP%%filename1%_original.bin" "%output_path%" >Nul
     set DV=y& echo Exporting shots list from a DV RPU...
     set OSC=_OSC
     goto :adjust_shotlist
)

::HDR10plus HEVC
findstr /c:"2094" "%TEMP%check.HDR10plus.txt" >Nul
if %errorlevel%==0 (
     "%hdr10plus_parser_path%" --skip-validation extract -i %HDR% -o "%TEMP%HDR10plus.json"
     "%dovi_tool_path%" generate --hdr10plus-json "%TEMP%HDR10plus.json" --json "%TEMP%L66.json" --rpu-out "%TEMP%rpu.h.bin" >Nul
     set RPU="%TEMP%rpu.h.bin"
     set DV=y& echo Exporting shots list from a HDR10plus JSON...
     set OSC=_OSC
     goto :adjust_shotlist
)

::###########################################################################################
::################################# MADVR scene cut detect ############################################
::###########################################################################################

:skipinternalshotlist
if /i "%Mode_31%"=="RESOLVE" goto :encode.prores
set OSC=_MadVR_SC
if /i "%madvr_workaround%"=="NO" goto :skipworkaround
if /i "%fileext1%"==".mov" goto :skipworkaround

:: encode prores first and then detect scene cuts with madvr
:tryworkaround9
set madvr_workaround=YES
echo.
"%ffmsindex%" "%filepath1%%filename1%%fileext1%" "%TEMP%index.ffindex"
echo.
echo LoadPlugin("%ffms2%") > "%TEMP%script.avs"
echo FFVideoSource("%filepath1%%filename1%%fileext1%", cachefile="%TEMP%index.ffindex") >> "%TEMP%script.avs"
echo Crop(%crop_right%, %crop_top%, -%crop_left%, -%crop_bottom%^) >>  "%TEMP%script.avs"

"%ffmpeg_path%" -i "%TEMP%script.avs" -c:v prores_ks -profile:v 3 -vendor apl0 -qscale:v %qscale% -color_primaries bt2020 -color_trc smpte2084 -colorspace bt2020nc -pix_fmt yuv422p10le -an -y -hide_banner  "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov"
set prores="%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov"
echo.

"%madvr_path%" "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov"
"%dovi_tool_path%" generate -j "%TEMP%L66.json" --madvr-file "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov.measurements" -o "%TEMP%generated_rpu.bin"

"%dovi_tool_path%" export -i "%TEMP%generated_rpu.bin" -d scenes="%TEMP%%filename1%.scene.cuts.txt"
if NOT ["%errorlevel%"]==["0"] echo MadVR failed to make the scene cuts.. & pause & exit

set shotlist=--shot-list "%TEMP%%filename1%.scene.cuts.txt"
goto :CM_Analyze

:skipworkaround

if /i "%fileext1%"==".mov" rename "%filepath1%%filename1%%fileext1%" "%filename1%_transfer=hdr_matrix=2020.mov"
if /i "%fileext1%"==".mov" set filename1=%filename1%_transfer=hdr_matrix=2020

:: generate scene cuts with madvr
"%madvr_path%" "%filepath1%%filename1%%fileext1%"
"%dovi_tool_path%" generate -j "%TEMP%L66.json" --madvr-file "%filepath1%%filename1%%fileext1%.measurements" -o "%TEMP%generated_rpu.bin"
move "%filepath1%%filename1%%fileext1%.measurements" "%output_path%"

"%dovi_tool_path%" export -i "%TEMP%generated_rpu.bin" -d scenes="%TEMP%%filename1%.scene.cuts.txt"
if NOT ["%errorlevel%"]==["0"] echo. & echo MadVR failed to make the scene cuts, will convert to prores first... & goto :tryworkaround9

set shotlist=--shot-list "%TEMP%%filename1%.scene.cuts.txt"
goto :encode.prores

::##########################################################################################
::################################# ADJUST SHOTLIST ############################################
::##########################################################################################

:adjust_shotlist

if not "%P5BL%"=="y" goto :skipfindP5MDL
"%dovi_tool_path%" info --input %RPU% -f 24 > "%TEMP%raw.txt"

set MDL=20& set min=1& set MDL1=1000
::1000nits MDL
findstr /c:"\"source_max_pq\": 3079" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=20& set min=1& set MDL1=1000
::2000nits MDL
findstr /c:"\"source_max_pq\": 3388" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=30& set min=1& set MDL1=2000
::4000nits MDL
findstr /c:"\"source_max_pq\": 3696" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=7& set min=50& set MDL1=4000
::10000nits MDL (should not be possible)
findstr /c:"\"source_max_pq\": 4095" "%TEMP%raw.txt" >nul
if !errorlevel!==0 set MDL=7& set min=50& set MDL1=10000

:skipfindP5MDL
:: add scene cut flag to the first frame in case it's missing
(
    echo {
    echo     "mode": 0,
    echo     "scene_cuts": {
    echo         "0-0": true
    echo     }
    echo }
) > "%TEMP%scene.json"

"%dovi_tool_path%" editor -i %RPU% -j "%TEMP%scene.json" --rpu-out "%TEMP%RPU-flag.added.bin" >Nul
"%dovi_tool_path%" export -i "%TEMP%RPU-flag.added.bin" -d scenes="%TEMP%%filename1%.scene.cuts.txt" >Nul 
set shotlist=--shot-list "%TEMP%%filename1%.scene.cuts.txt"

::######################################################################################
::####################################### Indexing #########################################
::######################################################################################

:encode.prores
if "%fileext1%"==".mov" set prores="%filepath1%%filename1%%fileext1%"& goto :CM_Analyze
if /i "%Bake_FEL_31%"=="YES" if /i "%felinput%"=="y"  goto :skip.indexing

if /i "%disable_indexing%"=="YES" set index="%filepath1%%filename1%%fileext1%"& goto :skip.indexing

"%ffmsindex%" "%filepath1%%filename1%%fileext1%" "%TEMP%index.ffindex"

echo LoadPlugin("%ffms2%") > "%TEMP%script.avs"
if /i "%requirelibplacebo%"=="y" echo LoadPlugin("%~dp0tools\avs_libplacebo.dll") >> "%TEMP%script.avs"
if /i "%requirelibplacebo%"=="y" echo LoadPlugin("%~dp0tools\avsresize_r21\x64\Release\avsresize.dll") >> "%TEMP%script.avs"

echo FFVideoSource("%filepath1%%filename1%%fileext1%", cachefile="%TEMP%index.ffindex") >> "%TEMP%script.avs"

if /i "%requirelibplacebo%"=="y" echo ConvertBits(16) >> "%TEMP%script.avs"

if /i "%HLG%"=="y" echo libplacebo_Tonemap(src_csp=2, dst_csp=1, dst_max=%HLG_target_nits%)  >> "%TEMP%script.avs"
if /i "%HLG%"=="y" echo z_ConvertFormat(pixel_type="YUV422P10",colorspace_op="2020ncl:st2084:2020:limited=>2020ncl:st2084:2020:limited",dither_type="error_diffusion",chromaloc_op="left=>top_left") >> "%TEMP%script.avs"

if /i "%P5BL%"=="y" echo libplacebo_Tonemap(src_csp=3, dst_csp=1)  >> "%TEMP%script.avs"
if /i "%P5BL%"=="y" echo z_ConvertFormat(pixel_type="YUV422P10",colorspace_op="2020ncl:st2084:2020:full=>2020ncl:st2084:2020:limited",dither_type="error_diffusion",chromaloc_op="left=>top_left") >> "%TEMP%script.avs"

if /i "%requirelibplacebo%"=="y" echo Prefetch(2) >> "%TEMP%script.avs"

:: crop
echo Crop(%crop_right%, %crop_top%, -%crop_left%, -%crop_bottom%^) >>  "%TEMP%script.avs"

set index="%TEMP%script.avs"

:skip.indexing

::######################################################################################
::################################### prores encoding #########################################
::######################################################################################

     echo.
     echo =============================SCRIPT===================================================
     type  "%TEMP%script.avs"
     echo.
     echo INPUT:  "%filepath1%%filename1%%fileext1%"
     echo.
     echo ============================COMMAND=================================================
     echo "%ffmpeg_path%" -i %index% -c:v prores_ks -profile:v 3 -vendor apl0 -qscale:v %qscale% -color_primaries bt2020 -color_trc smpte2084 -colorspace bt2020nc -pix_fmt yuv422p10le -an -y -hide_banner -loglevel error -stats "%TEMP%%filename1%_prores.422.mov"
     echo =======================================================================================
     echo.
     
echo frame=%frameCount1% (total)
"%ffmpeg_path%" -i %index% -c:v prores_ks -profile:v 3 -vendor apl0 -qscale:v %qscale% -color_primaries bt2020 -color_trc smpte2084 -colorspace bt2020nc -pix_fmt yuv422p10le -an -y -hide_banner -loglevel error -stats "%TEMP%%filename1%_prores.422.mov"
set prores="%TEMP%%filename1%_prores.422.mov"

::################## HLG SC ###################################
if not "%HLG%"=="y" goto :skip.hlg.SC
if /i "%Mode_31%"=="RESOLVE" goto :RESOLVE
if /i "%force.FBF%"=="YES" set shotlist=--longplay-analysis& goto :CM_Analyze

rename "%TEMP%%filename1%_prores.422.mov" "%filename1%_prores.422_transfer=HDR.matrix=2020.mov" & set prores="%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov"
"%madvr_path%" "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov"

"%dovi_tool_path%" generate -j "%TEMP%L66.json" --madvr-file "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov.measurements" -o "%TEMP%generated_rpu.bin"
move "%TEMP%%filename1%_prores.422_transfer=HDR.matrix=2020.mov.measurements" "%output_path%"

"%dovi_tool_path%" export -i "%TEMP%generated_rpu.bin" -d scenes="%TEMP%%filename1%.scene.cuts.txt"
if NOT ["%errorlevel%"]==["0"] echo madvr failed to make the scene cuts & pause & exit

set shotlist=--shot-list "%TEMP%%filename1%.scene.cuts.txt"
if /i "%Mode_31%"=="CM" goto :CM_Analyze

:skip.hlg.SC
::######################################################################################
::################################### RESOLVE  ############################################
::######################################################################################

:RESOLVE
if /i "%Mode_31%"=="CM" goto :CM_Analyze

::make edl for resolve
set EDL_Mode=resolve_detect& set OSC=_Resolve_SC
if /i "%DV%"=="y"  "%RPU.to.XML%" convert %RPU% "%TEMP%temp.xml" > nul
if /i "%DV%"=="y" "%metafier_path%" --shot-list-duration "%TEMP%%filename1%.scene.cuts.txt" "%TEMP%temp.xml" >Nul
if /i "%DV%"=="y" %python% "%~dp0tools\EDL_maker.py" -i "%TEMP%%filename1%.scene.cuts.txt" -o "%TEMP%EDL.edl" -f %FPS% & set EDL_Mode=y& set OSC=_OSC& set EDL=%TEMP%EDL.edl

:: Read encoded prores resolution
"%mediainfo_path%" %prores% --output=Video;%%Width%%\r\n ^ *.ts *.mp4 *.mkv *.m2ts *.mov *.hevc *.h265 *.avi >"%TEMP%Width.txt" 
"%mediainfo_path%" %prores% --output=Video;%%Height%%\r\n ^ *.ts *.mp4 *.mkv *.m2ts *.mov *.hevc *.h265 *.avi >"%TEMP%Height.txt" 

for /f "tokens=1 delims=" %%a in ('type "%TEMP%Width.txt"') do ( set "Width_prores=%%a" ) 
for /f "tokens=1 delims=" %%a in ('type "%TEMP%Height.txt"') do ( set "Height_prores=%%a" ) 

if /i "%L1_Tuning%"=="0" set L1_Tuning_RS=Legacy
if /i "%L1_Tuning%"=="1" set L1_Tuning_RS=Most Mapping
if /i "%L1_Tuning%"=="2" set L1_Tuning_RS=More Mapping
if /i "%L1_Tuning%"=="3" set L1_Tuning_RS=Balanced
if /i "%L1_Tuning%"=="4" set L1_Tuning_RS=Less Mapping
if /i "%L1_Tuning%"=="5" set L1_Tuning_RS=Least Mapping
if [%MDL%]==[] set MDL=20
if "%MDL%"=="21" set min=1& set MDL1=1000& set MDP=BT.2020
if "%MDL%"=="7" set min=50& set MDL1=4000& set MDP=P3 D65
if "%MDL%"=="20" set min=1& set MDL1=1000& set MDP=P3 D65
if "%MDL%"=="8" set min=50& set MDL1=4000& set MDP=BT.2020
if "%MDL%"=="30" set min=1& set MDL1=2000& set MDP=P3 D65
if "%MDL%"=="31" set min=1& set MDL1=2000& set MDP=BT.2020

set FPS_resolve=%FPS%
if "%FPS%"=="24.000" set FPS_resolve=24
if "%FPS%"=="25.000" set FPS_resolve=25
if "%FPS%"=="30.000" set FPS_resolve=30
if "%FPS%"=="50.000" set FPS_resolve=50
if "%FPS%"=="60.000" set FPS_resolve=60

echo.
:: write and run Resolve DV generate script
echo \033[92m  Writing Resolve DV Generate script... | "%cmdcolor%"
echo.
%python% "%~dp0tools\write_resolve_dv_generate.py" "%TEMP%resolve_dv_generate.py" %prores% "%EDL%" "%TEMP%%filename1%_DV.xml" "%MDP%" "%MDL1%" "%Width_prores%" "%Height_prores%" "%FPS_resolve%" "%PROGRAMDATA%" "%L1_Tuning_RS%" "" "%EDL_MODE%"
if %errorlevel% neq 0 (
    echo ERROR: Could not write Resolve DV Generate script.
    pause & exit
)

echo.
echo \033[92m  Running Resolve API... | "%cmdcolor%"
echo.
%python% "%TEMP%resolve_dv_generate.py"

set XML="%TEMP%%filename1%_DV.xml"

goto :generate

::######################################################################################
::################################# CM ANALYZE ############################################
::######################################################################################

:CM_Analyze

if [%MDL%]==[] set MDL=20
if "%MDL%"=="21" set min=1& set MDL1=1000& set MDP=BT.2020
if "%MDL%"=="7" set min=50& set MDL1=4000& set MDP=P3 D65
if "%MDL%"=="20" set min=1& set MDL1=1000& set MDP=P3 D65
if "%MDL%"=="8" set min=50& set MDL1=4000& set MDP=BT.2020
if "%MDL%"=="30" set min=1& set MDL1=2000& set MDP=P3 D65
if "%MDL%"=="31" set min=1& set MDL1=2000& set MDP=BT.2020
if [%right%]==[] set right=0
if [%left%]==[] set left=0
if [%right%]==[] set right=0
if [%bottom%]==[] set bottom=0
if not "%fileext1%"==".mov"  set right_resolve=0& set left_resolve=0& set top_resolve=0& set bottom_resolve=0
if /i "%fileext1%"==".mov" set right_resolve=%right%& set left_resolve=%left%& set top_resolve=%top%& set bottom_resolve=%bottom%

if /i "%force.FBF%"=="YES" goto :skipframecount

"%mediainfo_path%" %prores% --output=JSON > "%TEMP%mediainfoprores.JSON"
"%JQ_path%" .media.track[1].FrameCount "%TEMP%mediainfoprores.JSON" > "%TEMP%FrameCountprores.txt"
for /f "tokens=1 delims=" %%a in ('type "%TEMP%FrameCountprores.txt"') do (
    set "frameCount=%%a"
)
set frameCount=%frameCount:"=%

if exist "%filepath1%%filename1%.txt" (
     echo %frameCount% >> "%filepath1%%filename1%.txt"
     set shotlist=--shot-list "%filepath1%%filename1%.txt"
     goto :skipframecount
)

echo %frameCount% >> "%TEMP%%filename1%.scene.cuts.txt"

:skipframecount
if /i "%CM_CPU%"=="YES" set cpu.only=--cpu-only

if exist "%filepath1%%filename1%.bat" call "%filepath1%%filename1%.bat"

if "%FPS%"=="23.976" set FPS=24000/1001
if "%FPS%"=="24.000" set FPS=24
if "%FPS%"=="25.000" set FPS=25
if "%FPS%"=="29.970" set FPS=30000/1001
if "%FPS%"=="30.000" set FPS=30
if "%FPS%"=="50.000" set FPS=50
if "%FPS%"=="59.940" set FPS=60000/1001
if "%FPS%"=="60.000" set FPS=60

:: cm analyze, dv generation
"%cm_analyzer_path%" %shotlist% -m %MDL% -r %FPS% --source-format "pq bt2020" --letterbox %left_resolve% %right_resolve% %top_resolve% %bottom_resolve% --bda --analysis-tuning %L1_Tuning% %cpu.only% %prores% "%TEMP%%filename1%_DV.xml"
set XML="%TEMP%%filename1%_DV.xml"

::################################# Generate RPU ############################################

:generate
::generate rpu from generated xml
"%dovi_tool_path%" generate --xml %XML% --canvas-width %Width_input% --canvas-height %Height_input% --rpu-out "%TEMP%rpu_XML_generated.bin"
set RPU="%TEMP%rpu_XML_generated.bin"

::################################# EDIT FINAL RPU ############################################

::check for maxcll /fall and framecount
"%dovi_tool_path%" info -s %RPU% >"%TEMP%sum.rpu.json"
type "%TEMP%sum.rpu.json" | findstr Frames: > "%TEMP%frames.txt"
type "%TEMP%sum.rpu.json" | findstr L1 > "%TEMP%L1.txt"

for /f "tokens=4 delims=(:.)" %%a in ('type "%TEMP%L1.txt"') do (
    set "maxcll_L1=%%a"
)
for /f "tokens=6 delims=(:.)" %%a in ('type "%TEMP%L1.txt"') do (
    set "maxfall_L1=%%a"
)
for /f "tokens=2 delims=:" %%a in ('type "%TEMP%frames.txt"') do (
    set "framecount_rpu=%%a"
)

if /i "%cropped%"=="YES" set left=0& set right=0& set top=0& set bottom=0
set mode=0

::######################## Generate blank L8 ####################################################

set L8_300nits=24& set L9_value=0
if /i "%MDP%"=="BT.2020" set L8_300nits=25& set L9_value=2
(
echo {
echo     "cm_version": "V40",
echo     "length": %framecount_rpu%,
echo     "default_metadata_blocks": [
echo         {
echo             "Level2": {
echo                 "target_max_pq": 2081
echo             }
echo         },
echo         {
echo             "Level2": {
echo                 "target_max_pq": 2851
echo             }
echo         },
echo         {
echo             "Level2": {
echo                 "target_max_pq": 3079
echo             }
echo         },
echo         {
echo             "Level3": {
echo             }
echo         },
echo         {
echo             "Level8": {
echo                 "target_display_index": 1,
echo                 "trim_slope": %L8_100nits_slope%,
echo                 "trim_offset": %L8_100nits_offset%,
echo                 "trim_power": %L8_100nits_power%,
echo                 "trim_chroma_weight": %L8_100nits_chroma_weight%,
echo                 "trim_saturation_gain": %L8_100nits_saturation_gain%,
echo                 "ms_weight": %L8_100nits_ms_weight%
echo             }
echo         },
echo         {
echo             "Level8": {
echo                 "target_display_index": %L8_300nits%,
echo                 "trim_slope": %L8_300nits_slope%,
echo                 "trim_offset": %L8_300nits_offset%,
echo                 "trim_power": %L8_300nits_power%,
echo                 "trim_chroma_weight": %L8_300nits_chroma_weight%,
echo                 "trim_saturation_gain": %L8_300nits_saturation_gain%,
echo                 "ms_weight": %L8_300nits_ms_weight%
echo             }
echo         },
echo         {
echo             "Level9": {
echo                 "source_primary_index": %L9_value%
echo             }
echo         },
echo         {
echo             "Level10": {
echo                 "target_display_index": %L8_300nits%,
echo                 "target_max_pq": 2547,
echo                 "target_min_pq": 0,
echo                 "target_primary_index": %L9_value%
echo             }
echo         }
echo     ]
echo }
) > "%TEMP%L8_template.json"

"%dovi_tool_path%" generate -j "%TEMP%L8_template.json" -o "%TEMP%L8_template.bin" >Nul

cd /d "%TEMP%"
(
echo {
echo     "allow_cmv4_transfer": true,
echo     "source_rpu": "L8_template.bin",
echo     "rpu_levels": [8,10]
echo }
) > "%TEMP%transfer.json"

"%dovi_tool_path%" editor -j "%TEMP%transfer.json" -i %RPU% --rpu-out "%TEMP%L8gen.bin" >Nul
set RPU="%TEMP%L8gen.bin"

cd /d "%output_path%"

if "%HLG%"=="y" Echo HLG Base layer detected, adjusting the color reshaping metadata...& set mode=4
echo.

::####################### L5 ##########################
::L5 json
(
    echo {
    echo    "mode": %mode%,
    echo    "active_area": {
    echo        "crop": false,
    echo        "presets": [
    echo            {
    echo                "id": 0,
    echo                "left": %left%,
    echo                "right": %right%,
    echo                "top": %top%,
    echo                "bottom": %bottom%
    echo            }
    echo        ],
    echo        "edits": {
    echo            "all": 0
    echo        }
    echo    }
    echo }
) > "%TEMP%L5_edit.json"

echo Editing L5, Top: %top%, Bottom: %bottom%, Left: %left%, Right: %right%
echo.
"%dovi_tool_path%" editor -i %RPU% -j "%TEMP%L5_edit.json" --rpu-out "%TEMP%L5edited.bin" > nul
set RPU="%TEMP%L5edited.bin"

::############################# transfer generated metadata to original P7 / P5 rpu ###########################################

if /i "%P5BL%"=="y" goto :transferlevels
if /i "%Bake_FEL_31%"=="NO" goto :skipp7rpu
if /i "%felinput%"=="n" goto :skipp7rpu
if /i "%P7BL%"=="n" goto :skipp7rpu

:transferlevels
if /i "%P5BL%"=="y" echo Transferring the generated levels into the original Profile 5 RPU...
if /i "%P7BL%"=="y" echo Transferring the generated levels into the original Profile 7 FEL RPU...
echo.

cd /d "%TEMP%"
(
echo {
echo     "allow_cmv4_transfer": true,
echo     "source_rpu": "L5edited.bin",
echo     "rpu_levels": [1, 2, 3, 5, 8, 9, 10]
echo }
) > "%TEMP%transferRPU.json"

"%dovi_tool_path%" editor -i "%TEMP%%filename1%_original.bin" -j "%TEMP%transferRPU.json" -o "%TEMP%p5p7transferred.bin" >Nul
set RPU="%TEMP%p5p7transferred.bin"

cd /d "%output_path%"

:skipp7rpu

::####################### L6 ##########################
::L6 json
(
echo {
echo    "level6": {
echo        "max_display_mastering_luminance": %MDL1%,
echo        "min_display_mastering_luminance": %min%,
echo        "max_content_light_level": %maxcll_L1%,
echo        "max_frame_average_light_level": %maxfall_L1%
echo    }
echo }
) > "%TEMP%L6_edit.json"

echo Editing L6 to MDL: %MDL1% / %min%, MaxCLL: %maxcll_L1%, MaxFALL: %maxfall_L1%
echo.
"%dovi_tool_path%" editor -i %RPU% -j "%TEMP%L6_edit.json" --rpu-out  "%TEMP%%filename1%_Generated_T%L1_Tuning%%OSC%.bin" > nul
set RPU="%TEMP%%filename1%_Generated_T%L1_Tuning%%OSC%.bin"

::###################### final xml #########################

"%RPU.to.XML%" convert %RPU% "%output_path%%filename1%_Generated_T%L1_Tuning%%OSC%.xml" > nul
copy /y "%TEMP%%filename1%_Generated_T%L1_Tuning%%OSC%.bin" "%output_path%" >Nul

::###################################################################################
::################################# INJECT ############################################
::###################################################################################

echo.&echo.
echo \033[36m         ================ | "%cmdcolor%"
echo \033[36m         - INJECTING DV - | "%cmdcolor%"
echo \033[36m         ================ | "%cmdcolor%"
echo.

"%dovi_tool_path%" %dropH% inject-rpu -i %HDR% --rpu-in "%TEMP%%filename1%_Generated_T%L1_Tuning%%OSC%.bin" -o "%output_path%%filename1%_Generated.hevc"
if NOT ["%errorlevel%"]==["0"] echo Couldnt inject the generated RPU...& pause
set HDR="%output_path%%filename1%_Generated.hevc"

if /i "%keep_prores%"=="YES" if not "%fileext1%"==".mov" move %prores% "%output_path%"

set MBOX=:hdr=none:dvp=8.1& set dv.profile=8& set ID=1
if "%HLG%"=="y" set MBOX=:hdr=none:dvp=8.4& set dv.profile=8& set ID=4
if "%P5BL%"=="y" set MBOX=& set dv.profile=5& set ID=0

if not "%fileext1%"==".mov" goto :MUXER
:job.3.1.done

::################################# END ############################################
:end

rename "%filepath1%%filename1%%fileext1%" "%oldfilename%%fileext1%"

if not "%DEL_temp%"=="NO" echo Deleting TEMP folder... & rmdir /Q /S "%TEMP%"

::reset variables for loop
for /L %%i in (1,1,%count2%) do (
     set T%%i.Format=& set T%%i.Lang=& set T%%i.Forced=& set SM%%i=& set T%%i.Lang=& set AUDIO%%i=& set T%%i.Delay=& set delay%%i=& set T%%i.BitRate=& set T%%i.Channels=& set set AE%%i=& set Title%%i=& set T%%i.ID=& set mkvthd%%i=& set ALL%%i=& set AL%%i=& set SUB%%i=& set T%%i.sub=& set SF%%i=& set ch%%i=& set LOSSY%%i=& set FORCED%%i=& set A%%i=& set THD%%i=
)
set count2=& set muxing.succes=& set FPS=& set hlg.input=& set profile=& set muxing.succes=& set lossless.input=
set THD=& set forced=& set in.ID=& set ch=& set FID=& set ec3.id=& set DV=& set Hplus=& set shot=& set frameCount=& set first_line=& set Height=& set count2=
set raw.in=& set p7_bl=& set p5_bl=& set JUSTINJECT=& set dropH=& set mlp=& set dts=& set pcm.au=& set resync=& set dup=& set rem=& set delay.name=& set t81=& set SUBext=
set t82=& set t83=& set cmv4.0=& set T1=& set T2=& set T3=& set T4=&set trims=& set max_pq=& set min_pq=& set DVprofile=& set SRT=& set MBOX=
set cropped.input=& set job=& set audio=& set DT=& set RPU=& set EditL6=& set hlg.input=& set max=& set min=& set MDL.max_path=& set dv.profile=
set MDL.min_path=& set final.vid=& set editL9=& set remm=& set sour=& set offs=& set raw=& set HDR=& set FPS= set mode=& set ID=& set v1=& set v2=& set HLG=& set ID=
set p5=& set SDR=& set P7=& set HDR2=& set HDR1=& set v1_1080p=& set v2_1080p=& set MDL3=& set col=& set P5BL=& set subprofile=& set delay=& set way=& set UP1=& set UP2=& set upal1=
set upal2=& set incolor1=& set incolor2=& set MAPPING1=& set MAPPING2=& set upscaled1=& set upscaled2=& set HDR=& set pcm=& set flac=& set DDP=& set PCM=& set delay=& set NOSUB=& set properfps=& set NOAUDIO=

:: go to next file or end the script
for /l %%i in (2,1,%count%) do (
if "!f%%i!"=="y" set filename1=!filename%%i!& set filepath1=!filepath%%i!& set fileext1=!fileext%%i!& set f%%i=n& goto :loop.CM
)
setlocal disabledelayedexpansion
set filename1=&set filepath1=& set fileext1=&set filename=&set filepath=& set fileext=
echo.
set end_time=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start_time%") do set start_s=%%a&set start_m=%%b&set start_c=%%c&set start_ms=%%d
for /f %options% %%a in ("%end_time%") do set end_s=%%a&set end_m=%%b&set end_c=%%c&set end_ms=%%d

set /a start=(start_s*3600*100 + start_m*60*100 + start_c*100 + start_ms)/100
set /a end=(end_s*3600*100 + end_m*60*100 + end_c*100 + end_ms)/100

set /a elapsed=end-start
set /a hh=elapsed/(60*60), rest=elapsed%%(60*60), mm=rest/60, ss=rest%%60

if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%

echo.
echo Start time: %start_time%
echo End time: %end_time%
echo Time taken: %hh%:%mm%:%ss%
set filename1=&set filepath1=& set fileext1=&set filename=&set filepath=& set fileext=
echo.
echo \033[92mThe script has been completed. Do you want to quit or go back to main menu (q or m default=q)^?| "%cmdcolor%"& set /p action=
if /i "%action%"=="m" goto :Main.Menu
exit