# Converts videos to HEVC for given path:
# https://github.com/rigaya/NVEnc/releases

#-----------------------------------------------------------------------
# Edit the $videoPath variable to point to your video-files folder:
$videoPath = 'Z:\__VR_SP_CONTENT\_data'

#-----------------------------------------------------------------------
$fileTester = "$PSScriptRoot\..\mediainfo.exe"


#############################################################################################################
#                                    Testing and conversion preparations 									#
#############################################################################################################

# Get video list from provided path:
$videos = Get-ChildItem -LiteralPath $videoPath -Name -Recurse -Include ('*.mp4', '*.mkv') #('*.avi', '*.mp4', '*.mkv') - avi currently doesn't work.

# Instantiating used variables:
$videoID = 1
$convertedVideos = 0
$notConvertedVideos = 0

# Square brackets are used as wildcards in Powershell. 
# To recognize this as normal text, the LogWite function uses the -LiteralPath parameter instead of the -Path parameter.
$logFolderName = $((Get-Date).tostring("yyyy-MM-dd") + ' - [preList - convert HEVC to x264 created at ' + (Get-Date).tostring("HH-mm") + ']')
$count = $videos.Count

if($videos.Count -lt 1)
{
    Write-Host "No videos found in: $videoPath" -ForegroundColor Red
    Read-Host -Prompt "Press Enter to exit"
	exit
}
# Log write function:
Function LogWrite
{
   Param ([string]$logstring)
   Add-content -LiteralPath $Logfile -value $logstring
}
# Create new log directory:
New-Item -itemType Directory -Path $PSScriptRoot\ -Name $logFolderName > $null

Clear-Host # Clears the upper message from the window
#############################################################################################################
# END - Testing and conversion preparations



#############################################################################################################
#                                          Main conversion process											#
#############################################################################################################
Write-Host "Found $count videos with a total size of $folderSizeInGB - starting generation of list.." -ForegroundColor Cyan
Write-Host
Write-Host
Write-Host "------------------------------------------------------------------------------------------------"

foreach($video in $videos)
{
    
    $video = $video.Replace("`"", "")
    $inputFile = $videoPath + "\" + $video
	
	# Pre-file-check if "HEVC" exist in filename skip filechecking:
	if ($video -match "HEVC")
	{
		$codec = "HEVC"
	} else {
		# Get and check File info for codec, if it's already HEVC: - JSON query: (['media']['track'][1]['Format'])
		$fileDetails = cmd /c $fileTester $inputFile --Output=JSON | ConvertFrom-Json
		$codec = $fileDetails.media.track[1].Format
	}
	
	
	# If not already HEVC, convert video using NVEncC64:
	if($codec -eq "HEVC")
	{
		# Configure new file naming:
		if ($video -match "265")
		{
			$outputFile = $videoPath + "\" + $video.Replace("265", "264")
		} else {
			$outputFile = $videoPath + "\" + $video.Insert(($video.Length - 4), '-x264')
		}
		Write-Host "Analyzing video ($videoID of $count), needs conversion - number: $($convertedVideos + 1)" -ForegroundColor Magenta
		Write-Host "$video `nto:`n$outputFile" -ForegroundColor White
		Write-Host
		
		Write-Host
		Write-Host "------------------------------------------------------------------------------------------------"
		$convertedVideos = $convertedVideos + 1
		$Logfile = "$PSScriptRoot\$logFolderName\needs_conversion.log"
		LogWrite "$outputFile"

	} else 
	{
		# Alert if video doesn't need conversion:
		Write-Host "Analyzing video ($videoID of $count) - skip" -ForegroundColor Magenta
		Write-Host "$video is already in correct format!" -ForegroundColor Green
		Write-Host
		Write-Host "------------------------------------------------------------------------------------------------"
		# Increments not converted video counter:
		$notConvertedVideos = $notConvertedVideos + 1
		$Logfile = "$PSScriptRoot\$logFolderName\already_correct_codec.log"
		LogWrite "$inputFile"
	}
	# Increments video counter:
	$videoID = $videoID + 1
	$outputFile = "" # Resets the variable to nothing, that in case of an error the old file is not affected.
}
#############################################################################################################

Read-Host -Prompt "Press Enter to exit"
#############################################################################################################
# END - conversion script