utils

package
v0.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2026 License: BSD-3-Clause Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultAudioBitrate = 256000  // 256 kbps
	DefaultVideoBitrate = 1500000 // 1500 kbps
)

Default bitrates for duration estimation (bits per second)

Variables

View Source
var (
	VideoExtensionMap   = make(map[string]bool)
	AudioExtensionMap   = make(map[string]bool)
	ImageExtensionMap   = make(map[string]bool)
	TextExtensionMap    = make(map[string]bool)
	ArchiveExtensionMap = make(map[string]bool)
	MediaExtensionMap   = make(map[string]bool)
)
View Source
var ArchiveExtensions = []string{
	"7z", "Z", "ace", "alz", "alzip", "arc", "arj", "b5i", "b6i", "bin",
	"br", "bz2", "cab", "cb7", "cba", "cbr", "cbt", "cbz", "ccd", "cdr",
	"cif", "cpio", "daa", "deb", "dmg", "exe", "gi", "gz", "img", "iso",
	"lha", "lzh", "lzma", "lzo", "lzx", "mdf", "msi", "nrg", "nsi", "nsis",
	"p01", "pak", "pdi", "rar", "rpm", "sit", "sitx", "tar", "tar.bz2",
	"tar.gz", "tar.xz", "tar.zst", "taz", "tbz2", "tgz", "toast", "txz",
	"tz", "tzst", "udf", "uif", "vcd", "wim", "xar", "xz", "z", "zip",
	"zipx", "zoo", "zst", "zstd",
}
View Source
var AudioExtensions = []string{
	"aa3", "aac", "ac3", "aif", "aiff", "ape", "caf", "dff", "dsf", "flac",
	"m2a", "m4a", "m4b", "m4r", "mka", "mp3", "mpga", "oga", "ogg", "opus",
	"pcm", "wav", "wma",
}
View Source
var ImageExtensions = []string{}/* 131 elements not displayed */
View Source
var OptimizedExtensions = []string{".av1.mkv", ".opus", ".mka", ".avif", ".oga", ".ogg", ".svg", ".svgz"}
View Source
var SQLiteExtensions = []string{".sqlite", ".sqlite3", ".db", ".db3", ".s3db", ".sl3"}
View Source
var TextExtensions = []string{
	"azw", "azw3", "azw4", "cbc", "chm", "djv", "djvu", "doc", "docx", "dot",
	"epub", "fb2", "fbz", "htmlz", "lit", "lrf", "md",
	"mobi", "odt", "pdb", "pdf", "pml", "pot", "pps", "prc", "rb",
	"rtf", "snb", "tcr", "txtz", "vsd",
}
View Source
var UnreliableDurationFormats = map[string]int{

	".vob": 5000000,
	".ifo": 5000000,
	".vro": 5000000,

	".m2t":  15000000,
	".m2ts": 15000000,
	".mts":  15000000,
	".mod":  10000000,
	".tod":  12000000,

	".divx": 4000000,
	".xvid": 4000000,
	".rm":   2000000,
	".rmvb": 3000000,
	".wmv":  3000000,
	".asf":  3000000,

	".avchd": 20000000,
	".bdmv":  30000000,
	".mpls":  30000000,

	".iso": 8000000,
}

UnreliableDurationFormats are formats known to have unreliable duration metadata (DVD, Blu-ray, camcorder formats, and older codecs) The int value is the estimated bitrate in bits per second for each format

View Source
var VideoExtensions = []string{}/* 253 elements not displayed */

Functions

func CalculateWaitDuration added in v0.0.16

func CalculateWaitDuration(now time.Time, ranges []*TimeRange) time.Duration

CalculateWaitDuration calculates how long to wait until the next active time. Returns 0 if currently in an active period.

func CalculateWaitDurationForFinish added in v0.0.16

func CalculateWaitDurationForFinish(now time.Time, processingDuration time.Duration, ranges []*TimeRange) time.Duration

CalculateWaitDurationForFinish calculates how long to wait so that processing will finish during an active period. Returns 0 if starting now would already finish during an active period.

func ClearStdin added in v0.0.16

func ClearStdin()

ClearStdin flushes pending input from the terminal if it's a terminal

func CommandExists

func CommandExists(name string) bool

CommandExists checks if a command is available in PATH

func EstimateDurationFromSize

func EstimateDurationFromSize(size int64, isVideo bool) float64

EstimateDurationFromSize estimates duration from file size and bitrate Returns duration in seconds

func EstimateDurationFromSizeWithFormat

func EstimateDurationFromSizeWithFormat(size int64, ext string) float64

EstimateDurationFromSizeWithFormat estimates duration from file size using format-specific bitrate Returns duration in seconds

func EstimateFinishTime added in v0.0.16

func EstimateFinishTime(now time.Time, processingDuration time.Duration) time.Time

EstimateFinishTime calculates the estimated finish time given current time and processing duration

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists

func FolderSize

func FolderSize(path string) int64

FolderSize calculates the total size of a folder

func FormatDuration

func FormatDuration(seconds float64) string

FormatDuration formats seconds into human readable duration Prints max two units, skipping zero values (except 0 → "0s")

func FormatSize

func FormatSize(bytes int64) string

FormatSize formats bytes into human readable size using base 1024

func GetAccessTime added in v0.0.3

func GetAccessTime(info os.FileInfo) time.Time

GetAccessTime returns the access time of a file

func GetClearLineSequence added in v0.0.3

func GetClearLineSequence() string

GetClearLineSequence returns the escape sequence to clear/overwrite a line. We use \x1b[K (Erase from cursor to end of line) which is standard for overwriting.

func GetCommandPath added in v0.0.3

func GetCommandPath(name string) string

GetCommandPath returns the absolute path to a command

func GetDeviceID added in v0.0.5

func GetDeviceID(info os.FileInfo) (uint64, bool)

GetDeviceID returns the device ID of a file

func GetDurationForTimeout

func GetDurationForTimeout(duration float64, size int64, ext string) float64

GetDurationForTimeout returns a duration value suitable for timeout calculations. If the provided duration is valid (> 0), it returns it as-is. If duration is <= 0, it estimates from file size:

  • For unreliable formats (DVD, Blu-ray, etc.), uses format-specific bitrate
  • For other formats, uses default video bitrate

Returns 0 if size is invalid (<= 0)

func GetEstimatedBitrate

func GetEstimatedBitrate(ext string) int

GetEstimatedBitrate returns the estimated bitrate for a format Returns 0 if the format is not in the unreliable formats map

func GetMountPoint added in v0.0.5

func GetMountPoint(path string) (string, error)

GetMountPoint returns the mount point for a given path. It works even if the file doesn't exist by walking up the directory tree to find an existing parent directory.

func GetTerminalHeight

func GetTerminalHeight() int

GetTerminalHeight returns the current terminal height

func GetTerminalWidth

func GetTerminalWidth() int

GetTerminalWidth returns the current terminal width

func HasUnreliableDuration

func HasUnreliableDuration(ext string) bool

HasUnreliableDuration checks if a file extension is known to have unreliable duration metadata

func IsOptimized added in v0.0.6

func IsOptimized(ext string) bool

IsOptimized checks if a file extension is already optimized

func IsTimeInAnyRange added in v0.0.16

func IsTimeInAnyRange(t time.Time, ranges []*TimeRange) bool

IsTimeInAnyRange checks if a given time is within any of the provided time ranges

func IsTimeInRange added in v0.0.16

func IsTimeInRange(t time.Time, tr *TimeRange) bool

IsTimeInRange checks if a given time is within a time range. Handles overnight ranges (e.g., 10pm-6am).

func MoveFile added in v0.0.3

func MoveFile(src, dst string) error

MoveFile moves a file from source to destination, handling cross-filesystem moves

func ParseBitrate

func ParseBitrate(s string) int64

ParseBitrate parses bitrate strings like "128kbps", "1Mbps", "1k", "1M"

func ParseDurationString

func ParseDurationString(s string) time.Duration

ParseDurationString parses duration strings like "10s", "20m", "1h"

func ParsePercentOrBytes

func ParsePercentOrBytes(s string) float64

ParsePercentOrBytes parses percentage or byte values. Returns:

  • For percentages (e.g., "5%"): returns decimal fraction (0.05)
  • For size strings (e.g., "1MB", "100KB"): returns bytes as float64
  • For plain numbers: returns the number as float64

Note: The caller must know the expected type based on context. Values < 1.0 are typically percentages, values >= 1.0 are typically bytes.

func ParseSize

func ParseSize(s string) int64

ParseSize parses size strings like "30KiB", "1MB", "1G"

func ParseTime added in v0.0.16

func ParseTime(s string) (time.Time, error)

ParseTime parses time strings like "2pm", "8am", "10:30am", "14:00"

func PrintTable added in v0.0.3

func PrintTable(headers []string, rows [][]string)

PrintTable prints a formatted table with dynamic column widths

func PrintTableToString added in v0.0.3

func PrintTableToString(headers []string, rows [][]string) string

PrintTableToString returns a formatted table string with dynamic column widths

func RunCommandWithSystemd added in v0.0.6

func RunCommandWithSystemd(ctx context.Context, exe string, args []string, cfg SystemdRunConfig) ([]byte, error)

RunCommandWithSystemd executes a command, optionally wrapping it with systemd-run for resource control. Returns the command's exit error and output.

If systemd-run is available and MemoryLimit > 0, the command is wrapped with:

  • systemd-run --scope -p MemoryMax=<limit> -p MemorySwapMax=<swap> --nice=<nice> -- ...

If systemd-run is not available or Enabled is false, runs the command directly.

func SetupProcessGroup added in v0.0.6

func SetupProcessGroup(cmd *exec.Cmd)

SetupProcessGroup configures the command to run in a new process group. This allows us to kill all child processes together.

func ShouldOverrideDuration

func ShouldOverrideDuration(reportedDuration float64, size int64, ext string) (float64, bool)

ShouldOverrideDuration determines if reported duration should be overridden with an estimate based on file size. Returns true only when:

  • File extension matches an unreliable format
  • Reported duration is suspiciously low (< 2 minutes)
  • Estimated duration is much higher (> 2 minutes)

func TruncateMiddle

func TruncateMiddle(s string, max int) string

TruncateMiddle truncates a string in the middle with ellipsis

func WillFinishInActiveTime added in v0.0.16

func WillFinishInActiveTime(now time.Time, processingDuration time.Duration, ranges []*TimeRange) bool

WillFinishInActiveTime checks if processing started now would finish during an active period

Types

type SystemdRunConfig added in v0.0.6

type SystemdRunConfig struct {
	// MemoryLimit is the maximum memory allowed (in bytes).
	// If 0, no memory limit is set.
	MemoryLimit int64
	// MemorySwapMax is the maximum swap allowed (in bytes).
	// Default is MemoryLimit / 2. If 0 and MemoryLimit is set, swap is disabled.
	MemorySwapMax int64
	// Nice sets the process priority (-20 to 19).
	// Default: 0
	Nice int
	// UseJournald enables journald-compatible mode (--wait --pipe).
	// Default: false (uses --scope mode)
	UseJournald bool
	// Enabled controls whether systemd-run is used at all.
	// Default: true (use systemd-run if available)
	Enabled bool
	// Dir specifies the working directory for the command.
	// If empty, the current working directory is used.
	Dir string
}

SystemdRunConfig holds configuration for running commands via systemd-run.

type TerminalSize

type TerminalSize struct {
	// contains filtered or unexported fields
}

TerminalSize tracks the current terminal dimensions

type TimeRange added in v0.0.16

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange represents a time range like "2pm-8am" or "10am-1pm"

func ParseTimeRange added in v0.0.16

func ParseTimeRange(s string) (*TimeRange, error)

ParseTimeRange parses time range strings like "2pm-8am" or "10am-1pm"

func ParseTimeRanges added in v0.0.16

func ParseTimeRanges(ranges []string) ([]*TimeRange, error)

ParseTimeRanges parses multiple time range strings

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL