<#
/////////////////
FFMPalm by PalmDB
/////////////////

Video encoder frontend for Palm OS

What's New:
* Ported to PowerShell!
#>

<#
INITIALIZATION
#>

<# Get script version #>
$version = "1.0.0"

<# Get OS version #>
if (Test-Path "$env:windir\syswow64") {
    $OS = "win64"
} else {
    $OS = "win32"
}

<# Get error state #>
$exit = $false

<# Get current shell directory #>
$PSHostRoot = Get-Location

<# Show version #>
Write-Host "`n" -BackgroundColor Yellow -NoNewline
Write-Host "`n FFMPalm Version $version by PalmDB " -NoNewline -BackgroundColor Yellow -ForegroundColor Black
Write-Host "`n" -BackgroundColor Yellow


<#
PROFILES
#>

function Get-Profile($device) {

    <#
    DEVICE PROFILES
    #>

    switch -regex ($device) {

        <#  ACEECA #>
        "Aceeca_Meazura|Meazura" {
            $device = "Aceeca Meazura" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Aceeca_PDA32|PDA32" {
            $device = "Aceeca PDA32" 
            $cpu = "PXA270hi"
            Break
        }


        <#  ACER #>
        "Acer_S10|S10" {
            $device = "Acer S10" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Acer_S50|S10" {
            $device = "Acer S50" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Acer_S60|S10" {
            $device = "Acer S60" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  AlphaSmart #>
        "AlphaSmart_Dana|Dana" {
            $device = "AlphaSmart Dana" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  GARMIN #>
        "iQue_3000|Q3000" {
            $device = "Garmin iQue 3000" 
            $cpu = "PXA250"
            Break
        }

        "iQue_3200|Q3200" {
            $device = "Garmin iQue 3200" 
            $cpu = "PXA250"
            Break
        }

        "iQue_3600|Q3600" {
            $device = "Garmin iQue 3600" 
            $cpu = "DragonBallMXL"
            Break
        }


        <#  FOSSIL #>
        "Fossil|WristPDA" {
            $device = "Fossil Wrist PDA" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  GROUP SENSE PDA #>
        "Xplore_G18|G18" {
            $device = "Xplore G18" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Xplore_G88|G88" {
            $device = "Xplore G88" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Xplore_M28|M28" {
            $device = "Xplore M28" 
            $cpu = "OMAP310"
            Break
        }

        "Xplore_M68|M68" {
            $device = "Xplore M68" 
            $cpu = "OMAP310"
            Break
        }

        "Xplore_M70|M70" {
            $device = "Xplore M70" 
            $cpu = "OMAP310"
            Break
        }

        "Xplore_M68|M98" {
            $device = "Xplore M98" 
            $cpu = "OMAP310"
            Break
        }


        <#  Handera #>
        "Handera_330|330" {
            $device = "Handera 330" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  Handspring #>
        "Treo_90|90" {
            $device = "Handspring Treo 90" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  HP #>
        "HP_Pre3|Pre3" {
            $device = "HP Pre 3" 
            $cpu = "SnapdragonMSM"
            Break
        }

        "HP_TouchPad|TouchPad" {
            $device = "HP TouchPad" 
            $cpu = "SnapdragonS3"
            Break
        }

        "HP_Veer|Veer" {
            $device = "HP Veer" 
            $cpu = "QualcommMSM"
            Break
        }


        <#  JANAM #>
        "Janam_XP30|XP30" {
            $device = "Janam XP30" 
            $cpu = "DragonBallMXL"
            Break
        }


        <#  LENOVO #>
        "Lenovo_P300|P300" {
            $device = "Lenovo P300" 
            $cpu = "DragonBallMXL"
            Break
        }


        <#  PALM #>
        "Palm_i705|i705" {
            $device = "Palm i705" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Palm_m125|m125" {
            $device = "Palm m125" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Palm_m130|m130" {
            $device = "Palm m130" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Palm_m500|m500" {
            $device = "Palm m500" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Palm_m515|m515" {
            $device = "Palm m515" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Palm_Centro|Centro" {
            $device = "Palm Centro" 
            $cpu = "PXA270lo"
            Break
        }

        "Palm_LifeDrive|LD" {
            $device = "Palm LifeDrive" 
            $cpu = "PXA270hi"
            Break
        }

        "Palm_Pixi|Pixi" {
            $device = "Palm Pixi" 
            $cpu = "QualcommMSM"
            Break
        }

        "Palm_Pre|Pre" {
            $device = "Palm Pre" 
            $cpu = "OMAP3430"
            Break
        }

        "Palm_TX|TX" {
            $device = "Palm TX" 
            $cpu = "PXA270hi"
            Break
        }


        <#  QOOL #>
        "Qool_QDA700|QDA700" {
            $device = "Qool QDA700" 
            $cpu = "DragonBallMXL"
            Break
        }


        <#  SAMSUNG #>
        "SPH_i500|i500" {
            $device = "Samsung SPH-i500" 
            $cpu = "DragonBallVZ"
            Break
        }

        "SPH_i550|i550" {
            $device = "Samsung SPH-i550" 
            $cpu = "DragonBallMX1"
            Break
        }

        "SCH_i539|i539" {
            $device = "Samsung SCH-i539" 
            $cpu = "DragonBallMX1"
            Break
        }


        <#  SONY #>
        "Clie_N610C|N610C" {
            $device = "Sony Clie N610C" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_N760C|N760C" {
            $device = "Sony Clie N760C" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_NR70|NR70" {
            $device = "Sony Clie NR70" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_S320|S320" {
            $device = "Sony Clie S320" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_S360|S360" {
            $device = "Sony Clie S360" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_SJ20|SJ20" {
            $device = "Sony Clie SJ20" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_SJ30|SJ30" {
            $device = "Sony Clie SJ30" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_SL10|SL10" {
            $device = "Sony Clie SL10" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_T400|T400" {
            $device = "Sony Clie T400" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_T600C|T600C" {
            $device = "Sony Clie T600C" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_T665C|T665C" {
            $device = "Sony Clie T665C" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Clie_NX60|NX60" {
            $device = "Sony Clie NX60"
            <#  Actually PXA250, but widescreen #> 
            $cpu = "PXA260"
            Break
        }

        "Clie_NX70|NX70" {
            $device = "Sony Clie NX70"
            <#  Actually PXA250, but widescreen #> 
            $cpu = "PXA260"
            Break
        }

        "Clie_NX80|NX80" {
            $device = "Sony Clie NX80"
            <#  Actually PXA250, but widescreen #> 
            $cpu = "PXA260"
            Break
        }

        "Clie_NZ90|NZ90" {
            $device = "Sony Clie NZ90"
            <#  Actually PXA250, but widescreen #> 
            $cpu = "PXA260"
            Break
        }

        "Clie_TG50|TG50" {
            $device = "Sony Clie TG50" 
            $cpu = "PXA250hi"
            Break
        }

        "Clie_TH55|TH55" {
            $device = "Sony Clie TH55" 
            $cpu = "HHE"
            Break
        }

        "Clie_TJ25|TJ25" {
            $device = "Sony Clie TJ25" 
            $cpu = "DragonBallMX1"
            Break
        }

        "Clie_TJ27|TJ27" {
            $device = "Sony Clie TJ27" 
            $cpu = "DragonBallMX1"
            Break
        }

        "Clie_TJ35|TJ35" {
            $device = "Sony Clie TJ35" 
            $cpu = "DragonBallMX1"
            Break
        }

        "Clie_TJ37|TJ37" {
            $device = "Sony Clie TJ37" 
            $cpu = "DragonBallMX1"
            Break
        }

        "Clie_UX40|UX40" {
            $device = "Sony Clie UX40" 
            $cpu = "HHE"
            Break
        }

        "Clie_UX50|UX50" {
            $device = "Sony Clie UX50" 
            $cpu = "HHE"
            Break
        }

        "Clie_VZ90|VZ90" {
            $device = "Sony Clie VZ90" 
            $cpu = "HHE"
            Break
        }


        <#  SYMBOL #>
        "Symbol_SPT1800|SPT1800" {
            $device = "Symbol SPT 1800" 
            $cpu = "DragonBallVZ"
            Break
        }


        <#  TAPWAVE #>
        "Tapwave_Zodiac|Zodiac" {
            $device = "Tapwave Zodiac" 
            $cpu = "PXA270hi"
            Break
        }


        <#  TREO #>
        "Treo_600|600" {
            $device = "Palm Treo 600" 
            $cpu = "OMAP1510"
            Break
        }

        "Treo_650|650" {
            $device = "Palm Treo 650" 
            $cpu = "PXA270lo"
            Break
        }

        "Treo_680|680" {
            $device = "Palm Treo 680" 
            $cpu = "PXA270lo"
            Break
        }

        "Treo_700p|700p" {
            $device = "Palm Treo 700p" 
            $cpu = "PXA270lo"
            Break
        }

        "Treo_755p|755p" {
            $device = "Palm Treo 755p" 
            $cpu = "PXA270lo"
            Break
        }


        <#  TUNGSTEN #>
        "Tungsten_W|TW" {
            $device = "Palm Tungsten W" 
            $cpu = "DragonBallVZ"
            Break
        }

        "Tungsten_C|TC" {
            $device = "Palm Tungsten C" 
            $cpu = "PXA250hi"
            Break
        }

        "Tungsten_E|E1|TE" {
            $device = "Palm Tungsten E" 
            $cpu = "OMAP311"
            Break
        }

        "Tungsten_E2|E2" {
            $device = "Palm Tungsten E2" 
            $cpu = "PXA250hi"
            Break
        }

        "Tungsten_T|T1|TT" {
            $device = "Palm Tungsten T" 
            $cpu = "OMAP311"
            Break
        }

        "Tungsten_T2|T2" {
            $device = "Palm Tungsten T2" 
            $cpu = "OMAP311"
            Break
        }

        "Tungsten_T3|T3" {
            $device = "Palm Tungsten T3" 
            $cpu = "PXA260"
            Break
        }

        "Tungsten_T5|T5" {
            $device = "Palm Tungsten T5" 
            $cpu = "PXA270hi"
            Break
        }


        <#  ZIRE #>
        "Zire_21|Z21" {
            $device = "Palm Zire 21"
            <#  Actually OMAP311, but grayscale requires the same players as DragonBall #> 
            $cpu = "DragonBallVZ"
            Break
        }

        "Zire_22|Z22" {
            $device = "Palm Zire 22" 
            $cpu = "S3C2410"
            Break
        }

        "Zire_31|Z31" {
            $device = "Palm Zire 31" 
            $cpu = "PXA250lo"
            Break
        }

        "Zire_71|Z71" {
            $device = "Palm Zire 71" 
            $cpu = "OMAP310"
            Break
        }

        "Zire_72|Z72" {
            $device = "Palm Zire 72" 
            $cpu = "PXA270lo"
            Break
        }

        <# Otherwise assume input is common profile #>
        Default {
            $cpu = $device
            $device = "your Palm"
        }
    }


    <#
    COMMON PROFILES
    #>

    switch ($cpu) {
        <# Listed roughly in order of processing power #>

        "DragonBallVZ" {
            $script:legacy = $true
            $script:player = "gMovie, Kinoma, or TealMovie (*)"
            $script:width = "160"
            $script:height = "160"
            $script:fps = "15"
            $script:vcodec = "mpeg1video"
            $script:acodec = "mp2"
            $script:vbitrate = "1024K"
            $script:abitrate = "128K"
            $script:ext = "mpg"
        }
        
        "S3C2410" {
            $script:player = "CorePlayer"
            $script:width = "160"
            $script:height = "160"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "192K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "OMAP1510" {
            $script:player = "CorePlayer"
            $script:width = "160"
            $script:height = "160"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "224K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "OMAP310" {
            $script:player = "CorePlayer"
            $script:width = "240"
            $script:height = "176"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "224K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "OMAP311" {
            $script:player = "CorePlayer"
            $script:width = "240"
            $script:height = "240"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "224K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "DragonBallMXL" {
            $script:player = "CorePlayer"
            $script:width = "304"
            $script:height = "228"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "224K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "DragonBallMX1" {
            $script:player = "CorePlayer"
            $script:width = "320"
            $script:height = "320"
            $script:fps = "20"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "256K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "PXA250lo" {
            $script:player = "CorePlayer"
            $script:width = "160"
            $script:height = "160"
            $script:fps = "30"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "352K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "PXA250hi" {
            $script:player = "CorePlayer"
            $script:width = "320"
            $script:height = "320"
            $script:fps = "24"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "352K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "PXA260" {
            $script:player = "CorePlayer"
            $script:width = "424"
            $script:height = "280"
            $script:fps = "24"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "352K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "HHE" {
            $script:player = "CorePlayer"
            $script:width = "456"
            $script:height = "304"
            $script:fps = "24"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "256K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "PXA270lo" {
            $script:player = "TCPMP or CorePlayer"
            $script:width = "320"
            $script:height = "320"
            $script:fps = "30"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "640K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "PXA270hi" {
            $script:player = "TCPMP or CorePlayer"
            $script:width = "480"
            $script:height = "320"
            $script:fps = "30"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "848K"
            $script:abitrate = "352K -ar 22050"
            $script:ext = "avi"
        }
        
        "MAX" {
            $script:player = "TCPMP or CorePlayer overclocked to 500MHz or more"
            $script:width = "480"
            $script:height = "320"
            $script:fps = "30"
            $script:vcodec = "libxvid -g 120 -bf 4"
            $script:acodec = "pcm_u8"
            $script:vbitrate = "1920K"
            $script:abitrate = "512K -ar 32000"
            $script:ext = "avi"
        }
        
        "OMAP3430" {
            $script:player = "the WebOS video player app"
            $script:width = "480"
            $script:height = "320"
            $script:fps = "30"
            $script:vcodec = "libx264 -profile:v baseline"
            $script:acodec = "aac"
            $script:vbitrate = "1024K"
            $script:abitrate = "192K"
            $script:ext = "mp4"
        }
        
        "QualcommMSM" {
            $script:player = "the WebOS video player app"
            $script:width = "400"
            $script:height = "320"
            $script:fps = "30"
            $script:vcodec = "libx264 -profile:v baseline"
            $script:acodec = "aac"
            $script:vbitrate = "1024K"
            $script:abitrate = "192K"
            $script:ext = "mp4"
        }
        
        "SnapdragonMSM" {
            $script:player = "the WebOS video player app"
            $script:width = "800"
            $script:height = "480"
            $script:fps = "30"
            $script:vcodec = "libx264"
            $script:acodec = "aac"
            $script:vbitrate = "1024K"
            $script:abitrate = "192K"
            $script:ext = "mp4"
        }
        
        "SnapdragonS3" {
            $script:player = "the WebOS video player app"
            $script:width = "1024"
            $script:height = "768"
            $script:fps = "30"
            $script:vcodec = "libx264"
            $script:acodec = "aac"
            $script:vbitrate = "1536K"
            $script:abitrate = "192K"
            $script:ext = "mp4"
        }

        <# Return empty if no device or common profile is found #>
        Default {
            $device = ""
        }
    }

    <# Return selected device string #>
    return $device
}


<#
HELP
#>

function Write-Hint {
    Write-Host "`nFor usage info, try:" -ForegroundColor Yellow
    Write-Host "`n  ffmpalm " -NoNewline -ForegroundColor Gray 
    Write-Host "--help`n" -ForegroundColor Green
}

function Write-Help {
    Write-Host @"

 FFMPalm is a CLI frontend for a collection of video conversion utilities and presets designed
 to provide the best balance of quality and performance on as many Palm OS devices as possible.

 Currently, supported sources include local drives, streaming websites (YouTube et al), and DVD.
"@
    Read-Host "`nPress ENTER to continue"

    Write-Host "SYNTAX:" -ForegroundColor Yellow
    Write-Host "    ffmpalm " -NoNewline -ForegroundColor Gray
    Write-Host "`"input file/url`" " -NoNewline -ForegroundColor Green
    Write-Host "`"output file`" " -NoNewline -ForegroundColor Cyan
    Write-Host "device_profile " -NoNewline -ForegroundColor Magenta
    Write-Host "[--options] " -ForegroundColor DarkGreen

    Write-Host "`nOPTIONS:" -ForegroundColor Yellow
    Write-Host "    --crop-none " -NoNewline
    Write-Host "           (Disables auto and manual crop)" -ForegroundColor Yellow
    Write-Host "    --crop-region W:H:X:Y " -NoNewLine
    Write-Host " (Manual crop - Not recommended, will auto-crop by default!)" -ForegroundColor Yellow
    Write-Host "    --crop-sample HH:MM:SS " -NoNewLine
    Write-Host "(Sample frame for auto-crop to find black bars)" -ForegroundColor Yellow
    Write-Host "    --dvd-title # " -NoNewLine
    Write-Host "         (Enables DVD conversion [where main feature is typically title 1 or 2])" -ForegroundColor Yellow
    Write-Host "    --smooth " -NoNewLine
    Write-Host "              (Slower conversion, smoother framerate)" -ForegroundColor Yellow

    Write-Host "`nEXAMPLES:" -ForegroundColor Yellow
    Write-Host "    ffmpalm " -NoNewline -ForegroundColor Gray
    Write-Host "`"C:\video_in.mp4`" " -NoNewline -ForegroundColor Green
    Write-Host "`"C:\video_out`" " -NoNewline -ForegroundColor Cyan
    Write-Host "Palm_TX" -ForegroundColor Magenta
    
    Write-Host "    ffmpalm " -NoNewline -ForegroundColor Gray
    Write-Host "https://www.youtube.com/watch?v=3EjuGv9roKc " -NoNewline -ForegroundColor Green
    Write-Host "`"C:\video_out`" " -NoNewline -ForegroundColor Cyan
    Write-Host "E2 " -NoNewline -ForegroundColor Magenta
    Write-Host "--crop-sample 00:02:35" -ForegroundColor DarkGreen

    Write-Host "    ffmpalm " -NoNewline -ForegroundColor Gray
    Write-Host "D:\ " -NoNewline -ForegroundColor Green
    Write-Host "`"C:\video_out`" " -NoNewline -ForegroundColor Cyan
    Write-Host "UX50 " -NoNewline -ForegroundColor Magenta
    Write-Host "--dvd-title 1" -ForegroundColor DarkGreen

    Read-Host "`nPress ENTER to continue"

    Write-Host "ABOUT:" -ForegroundColor Yellow
    Write-Host @"
 FFMPalm will automatically select the best conversion settings based on your input device profile.
 Device profiles can be input as either the device brand + model, or model only. For example, both 
 "T3" and "Tungsten_T3" will be recognized. (See below for a full table of supported devices.)

 File extension will be selected automatically based on device profile, so there is no need to add 
 an extension to the output filename. In some cases, temporary files may also be stored at this
 location until the process is finished, so make sure there is enough free space!

 FFMPalm will attempt to automatically crop videos to remove letterboxing or pillarboxing. However,
 this requires a clear sample image to detect black bars. By default, an image will be sampled at
 1 minute. If this happens to be a black image (such as titles or transitions) or the video is less
 than one minute long, a different sample frame can be specified with the optional --crop-sample
 argument, using the time format HH:MM:SS. To disable cropping entirely, use --crop-none.

 To convert a DVD, use only the drive letter as an input path. Then, use the --dvd-title argument
 to specify which 'title' (video) to convert. A single DVD may contain multiple titles, such as
 additional trailers and bonus features. The main feature is typically title 1 or 2. The DVD will be 
 imported locally before conversion to Palm format. Further conversions can be made from the local
 version without re-importing.
"@

    Read-Host "`nPress ENTER to continue"

    Write-Host "PROFILES:" -ForegroundColor Yellow
    Write-Host @"
 |----------------------------------------------------------------------------------------------|
 | DEVICE PROFILES (OS 5+)                                                                      |
 |----------------------|--------------------|-------------------------|------------------------|
 | ACEECA               | GARMIN             | GROUP SENSE PDA         | HP                     |
 |----------------------|--------------------|-------------------------|------------------------|
 | Aceeca_PDA32 (PDA32) | iQue_3000 (Q3000)  | Xplore_M28 (M28)        | HP_Pre3     (Pre3)     |
 |                      | iQue_3200 (Q3200)  | Xplore_M68 (M68)        | HP_TouchPad (TouchPad) |
 |                      | iQue_3600 (Q3600)  | Xplore_M70 (M70)        | HP_Veer     (Veer)     |
 |                      |                    | Xplore_M98 (M98)        |                        |
 |----------------------|--------------------|-------------------------|------------------------|
 | JANAM                | LENOVO             | PALM                    | QOOL                   |
 |----------------------|--------------------|-------------------------|------------------------|
 | Janam_XP30 (XP30)    | Lenovo_P300 (P300) | Palm_Centro    (Centro) | Qool_QDA700 (QDA700)   |
 |                      |                    | Palm_LifeDrive (LD)     |                        |
 |                      |                    | Palm_Pixi      (Pixi)   |                        |
 |                      |                    | Palm_Pre       (Pre)    |                        |
 |                      |                    | Palm_TX        (TX)     |                        |
 |----------------------|--------------------|-------------------------|------------------------|
 | SAMSUNG              | SONY               | TAPWAVE                 | TREO                   |
 |----------------------|--------------------|-------------------------|------------------------|
 | SPH_i550 (i550)      | Clie_NX60 (NX60)   | Tapwave_Zodiac (Zodiac) | Treo_600  (600)        |
 | SCH_i539 (i539)      | Clie_NX70 (NX70)   |                         | Treo_650  (650)        |
 |                      | Clie_NX80 (NX80)   |                         | Treo_680  (680)        |
 |                      | Clie_NZ90 (NZ90)   |                         | Treo_700p (700p)       |
 |                      | Clie_TG50 (TG50)   |                         | Treo_755p (755p)       |
 |                      | Clie_TH55 (TH55)   |                         |                        |
 |                      | Clie_TJ25 (TJ25)   |                         |                        |
 |                      | Clie_TJ27 (TJ27)   |                         |                        |
 |                      | Clie_TJ35 (TJ35)   |                         |                        |
 |                      | Clie_TJ37 (TJ37)   |                         |                        |
 |                      | Clie_UX40 (UX40)   |                         |                        |
 |                      | Clie_UX50 (UX50)   |                         |                        |
 |                      | Clie_VZ90 (VZ90)   |                         |                        |
 |----------------------|--------------------|-------------------------|------------------------|
 | TUNGSTEN             | ZIRE               |                         |                        |
 |----------------------|--------------------|-------------------------|------------------------|
 | Tungsten_C  (TC)     | Zire_21 (Z21)      |-------------------------|------------------------|
 | Tungsten_E  (E1/TE)  | Zire_22 (Z22)      |-------------------------|------------------------|
 | Tungsten_E2 (E2)     | Zire_31 (Z31)      |-------------------------|------------------------|
 | Tungsten_T  (T1/TT)  | Zire_71 (Z71)      |-------------------------|------------------------|
 | Tungsten_T2 (T2)     | Zire_72 (Z72)      |-------------------------|------------------------|
 | Tungsten_T3 (T3)     |                    |-------------------------|------------------------|
 | Tungsten_T5 (T5)     |                    |-------------------------|------------------------|
 |----------------------|--------------------|-------------------------|------------------------|

 It is also technically possible to convert videos for playback on older/less powerful devices than 
 the list above. However, this is generally not recommended as image quality is severely limited,
 and specialized third-party desktop software is required to transfer videos generated by FFMPalm to
 the device itself as .pdb files. This software typically requires old versions of Apple QuickTime
 which may not be compatible with your PC.

 If you'd like to continue anyway, FFMPalm includes profiles for these older devices which will
 convert video to a generic format compatible with the **desktop transfer software**, not the devices
 themselves. It is up to you to install such software and select appropriate settings for transfer
 to your device.

 Visit https://palmdb.net/apps/media/video/ for more information and downloads!

 |-----------------------------------------------------------------------------------------------|
 | DEVICE PROFILES (OS 4)                                                                        |
 |--------------------------|--------------------|--------------------------|--------------------|
 | ACEECA                   | ACER               | ALPHASMART               | FOSSIL             |
 |--------------------------|--------------------|--------------------------|--------------------|
 | Aceeca_Meazura (Meazura) | Acer_S10 (S10)     | AlphaSmart_Dana (Dana)   | Fossil (WristPDA)  |
 |                          | Acer_S50 (S50)     |                          |                    |
 |                          | Acer_S60 (S60)     |                          |                    |
 |--------------------------|--------------------|--------------------------|--------------------|
 | GROUP SENSE PDA          | HANDERA            | HANDSPRING               | PALM               |
 |--------------------------|--------------------|--------------------------|--------------------|
 | Xplore_G18 (G18)         | Handera_330 (330)  | Treo_90 (90)             | Palm_i705 (i705)   |
 | Xplore_G88 (G88)         |                    |                          | Palm_m125 (m125)   |
 |                          |                    |                          | Palm_m130 (m130)   |
 |                          |                    |                          | Palm_m500 (m500)   |
 |                          |                    |                          | Palm_m515 (m515)   |
 |--------------------------|--------------------|--------------------------|--------------------|
 | SAMSUNG                  | SONY               | SYMBOL                   | TUNGSTEN           |
 |--------------------------|--------------------|--------------------------|--------------------|
 | SPH-i500 (i500)          | Clie_N610C (N610C) | Symbol_SPT1800 (SPT1800) | Tungsten_W (TW)    |
 |                          | Clie_NR70  (NR70)  |                          |                    |
 |                          | Clie_S320  (S320)  |                          |                    |
 |                          | Clie_S360  (S360)  |                          |                    |
 |                          | Clie_SJ20  (SJ20)  |                          |                    |
 |                          | Clie_SJ30  (SJ30)  |                          |                    |
 |                          | Clie_SL10  (SL10)  |                          |                    |
 |                          | Clie_T400  (T400)  |                          |                    |
 |                          | Clie_T600C (T600C) |                          |                    |
 |                          | Clie_T665C (T665C) |                          |                    |
 |--------------------------|--------------------|--------------------------|--------------------|

 There are also a number of common profiles available based on different chipsets. The above device 
 profiles will automatically select the appropriate common profile for their hardware, but if you 
 know your device's chipset, you can also select a common profile directly.

 |--------------------------------------------------------------------------------------|
 | COMMON PROFILES                                                                      |
 |-----------------|---------------|---------------|---------|------|-------------------|
 | INTEL           | MOTOROLA      | QUALCOMM      | SAMSUNG | SONY | TEXAS INSTRUMENTS |
 |-----------------|---------------|---------------|---------|------|-------------------|
 | PXA250lo        | DragonBallVZ  | QualcommMSM   | S3C2410 | HHE  | OMAP1510          |
 | PXA250hi        | DragonBallMXL | SnapdragonMSM |         |      | OMAP310           |
 | PXA260          | DragonBallMX1 | SnapdragonS3  |         |      | OMAP311           |
 | PXA270lo        |               |               |         |      | OMAP3430          |
 | PXA270hi        |               |               |         |      |                   |
 | MAX             |               |               |         |      |                   |
 |-----------------|---------------|---------------|---------|------|-------------------|

"@
}


<#
FIRST TIME SETUP
#>

<# Test whether Visual C++ redist needs to be installed #>
switch ($OS) {
    "win64" {
        $vcredist = Get-ItemProperty HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | select DisplayName | Where-Object {$_.DisplayName -like $("Microsoft Visual C++ 2010*")} | Out-String
        Break
    }

    "win32" {
        $vcredist = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | select DisplayName | Where-Object {$_.DisplayName -like $("Microsoft Visual C++ 2010*")} | Out-String
        Break
    }

    Default {
        $vcredist = ""
    }
}

<# Install Visual C++ redestributable, if not installed #>
if ($vcredist -eq "") {
    Set-Location $PSScriptRoot
    .\redist\vcredist_x86.exe /q /norestart
    Set-Location $PSHostRoot
}


<#
PARSE ARGUMENTS
#>

<# Initialize argument defaults #>
function Clear-Input {
    $script:cropEnabled = $true
    $script:cropRegion = ""
    $script:cropSample = "00:00:59"
    $script:deviceProfile = ""
    $script:deviceLegacy = $false
    $script:dvdEnabled = $false
    $script:dvdTitle = -1
    $script:fileInput = ""
    $script:fileOutput = ""
    $script:smooth = "blend"
    $script:streamEnabled = $false
}
Clear-Input

<# Show hint for help command if no arguments are input #>
if (($args.length) -eq 0) {
    Write-Hint
    $exit = $true
} else {
    <# Otherwise, get input arguments #>
    for ($a = 0; $a -lt ($args.length); $a++) {
        <# Full help #>
        if ($args[$a] -eq "--help") {
            Clear-Input
            Write-Help
            $exit = $true
            Break
        }

        <# Other arguments #>
        if ($args[$a] -eq "--crop-none") {
            $cropEnabled = $false
            Continue
        }

        if ($args[$a] -eq "--crop-region") {
            $cropRegion = "crop=" + $args[$a + 1]
            $a++
            Continue
        }

        if ($args[$a] -eq "--crop-sample") {
            $cropSample = $args[$a + 1]
            $a++
            Continue
        }

        if ($args[$a] -eq  "--dvd-title") {
            $dvdEnabled = $true
            $dvdTitle = $args[$a + 1]
            $a++
            Continue
        }

        if ($args[$a] -eq "--smooth") {
            $smooth = "mci"
            Continue
        }

        <# Files and profiles #>
        if ($args[$a] -is [string]) {
            <# Get input file path first #>
            if ($fileInput -eq "") {
                if ($dvdEnabled) {
                    <# Input file is DVD #>
                    if (Test-Path $args[$a]) {
                        $fileInput = $args[$a]
                    }
                } else {
                    <# Input file is URL #>
                    if (($args[$a].Substring(0, 4)) -eq "http") {
                        $streamEnabled = $true
                        $fileInput = $args[$a]
                    } else {
                        <# Input file is local path #>
                        if (Test-Path $args[$a]) {
                            $fileInput = Resolve-Path $args[$a]
                        }
                    }
                }
                Continue
            }

            <# Get output file path second#>
            if ($fileOutput -eq "") {
                <# Get target directory #>
                try { $matches.Clear() } catch { }
                $args[$a] -match ".+(\\)" | Out-Null

                <# Create target directory, if it doesn't exist #>
                if (!(Test-Path $matches[0])) {
                    New-Item -ItemType Directory -Path $matches[0] | Out-Null
                }

                <# Get fully qualified output file (without extension, if any) #>
                $fileOutput = ((Resolve-Path $matches[0]).toString()) + (($args[$a] -replace ".+(\\)") -replace "\.[^.\\/]+$")
                Continue
            }

            <# Get device profile third #>
            if ($deviceProfile -eq "") {
                $deviceProfile = $args[$a]
                Continue
            }
        }
    }

    <# Get device profile from argument #>
    $deviceProfile = Get-Profile $deviceProfile

    <# Show argument input errors #>
    while (!$exit) {
        if ($fileInput -eq "") {
            Write-Host "`nError: Missing or incorrect input file!" -ForegroundColor Red
            Write-Hint
            Clear-Input
            $exit = $true
            Break
        }
        if ($fileOutput -eq "") {
            Write-Host "`nError: Missing or incorrect output file!" -ForegroundColor Red
            Write-Hint
            Clear-Input
            $exit = $true
            Break
        }
        if ($deviceProfile -eq "") {
            Write-Host "`nError: Missing or incorrect device profile!" -ForegroundColor Red
            Write-Hint
            Clear-Input
            $exit = $true
            Break
        }
        if ($cropEnabled) {
            if ([string] $cropSample -eq "") {
                Write-Host "`nError: Crop sample declared, but missing sample time!" -ForegroundColor Red
                Write-Hint
                Clear-Input
                $exit = $true
                Break
            }
        }
        if ($dvdEnabled) {
            if ([string] $dvdTitle -eq "") {
                Write-Host "`nError: DVD title declared, but missing title number!" -ForegroundColor Red
                Write-Hint
                Clear-Input
                $exit = $true
                Break
            }
        }

        <# Show overwrite warning if output exists #>
        if (Test-Path "$fileOutput.$ext") {
            $overwrite = Read-Host "`nFile exists. Overwrite? [Y/N]"
            Write-Host ""

            <# Cancel if user declines to overwrite #>
            switch -regex ($overwrite) {
                "N|n" {
                    Write-Host "Operation cancelled.`n" -ForegroundColor Green
                    $exit = $true
                }
            }
        }

        <# End error checking if no errors were found #>
        Break
    }
}


<#
VIDEO PROCESSING
#>

Set-Location -Path $PSScriptRoot

<# Process DVD #>
if ($dvdEnabled) {
    Write-Host "`n[import] Importing DVD video. This will take a while, please wait...`n"

    <# Convert DVD to local file #>
    .\bin\HandBrakeCLI.exe --input "$fileInput" --title $dvdTitle --preset "Matroska/H.264 MKV 480p30" --output "$fileOutput.dvd.mkv"

    <# Use local DVD copy as input file #>
    if (Test-Path "$fileOutput.dvd.mkv") {
        $fileInput = "$fileOutput.dvd.mkv"
    } else {
        <# Otherwise show error if import failed #>
        Write-Host "`nError: Importing DVD title $dvdTitle failed!" -ForegroundColor Red
        Write-Hint
        $exit = $true
    }
}

<# Process streaming URL #>
if ($streamEnabled) {
    Write-Host ""

    <# Convert streaming video to local file #>
    .\bin\youtube-dl.exe -f "best[height<=720]" -o "$fileOutput.tmp" $fileInput

    <# Use local copy as input file #>
    if (Test-Path "$fileOutput.tmp") {
        $fileInput = "$fileOutput.tmp"
    } else {
        <# Otherwise show error if import failed #>
        Write-Host "`nError: Downloading URL `"$fileInput`" failed!" -ForegroundColor Red
        Write-Hint
        $exit = $true
    }
}

<# Process local file #>
if (!$exit) {
    Write-Host "[convert] Working, please wait..."

    <# Get crop setting, if enabled #>
    if ($cropEnabled) {
        <# Use auto-crop, if manual crop is not specified #>
        if ($cropRegion -eq "") {
            try { $matches.Clear() } catch { }
            .\bin\ffmpeg.exe -ss $cropSample -i $fileInput -vframes 2 -vf "scale=iw*min($width/iw\,$height/ih):ih*min($width/iw\,$height/ih), pad=$width`:$height`:($width-iw)/2:($height-ih)/2, cropdetect" -f null NUL 2>&1 | ForEach { $_.toString() -match "crop=(.*)$" } | Out-Null

            <# Use autocrop setting, if found #>
            if ($matches[0].length -gt 0) {
                if (($matches[0].Substring(0, 4)) -eq "crop") {
                    $cropRegion = $matches[0]
                }
            }
        }
    } else {
        <# Otherwise use default crop #>
        $cropRegion = "crop=iw:ih:0:0"
    }

    <# Convert file #>
    .\bin\ffmpeg.exe -hide_banner -loglevel quiet -stats -i "$fileInput" -preset slower -c:v $vcodec.split(" ") -c:a $acodec.split(" ") -b:v $vbitrate.split(" ") -b:a $abitrate.split(" ") -r $fps.split(" ") -vf "scale=iw*min($width/iw\,$height/ih):ih*min($width/iw\,$height/ih), pad=$width`:$height`:($width-iw)/2:($height-ih)/2, $cropRegion, deblock=filter=strong:block=4, spp=4, minterpolate=fps=$fps`:mi_mode=$smooth" -y "$fileOutput.$ext"

    <# Cleanup temp file, if any #>
    if (Test-Path "$fileOutput.tmp") {
        Remove-Item "$fileOutput.tmp"
    }

    <# Notify process complete #>
    if (Test-Path "$fileOutput.$ext") {
        if ((Get-Item "$fileOutput.$ext").length -gt 0) {
            Write-Host "`nProcess complete!" -ForegroundColor Green
            Write-Host "`nFor $deviceProfile it is recommended to use $player for viewing converted videos."
            if ($deviceLegacy) {
                Write-Host "(*Requires companion desktop transfer software)" -ForegroundColor Yellow
            }
            if ($dvdEnabled) {
                Write-Host "`nYour DVD video has been saved for future conversions without re-importing."
            }
            Write-Host "`nVisit https://palmdb.net/apps/media/video/ for more information and downloads!`n"
        } else {
            <# Otherwise show error if conversion failed #>
            Write-Host "`nError: Converting `"$fileOutput.$ext`" failed!" -ForegroundColor Red
            Write-Hint
            $exit = $true

            <# Remove empty file #>
            Remove-Item "$fileOutput.$ext"
        }
    } else {
        <# Otherwise show error if creation failed #>
        Write-Host "`nError: Creating file `"$fileOutput.$ext`" failed!" -ForegroundColor Red
        Write-Hint
        $exit = $true
    }
}


<# 
FINALIZATION
#>

<# Restore original directory #>
Set-Location -Path $PSHostRoot

<# Prompt for exit to prevent self-close #>
Read-Host "Press ENTER to continue"