Skip to main content

Overview

Camera Workflow is a secure, parallel media converter written in Go that converts images to modern formats (AVIF, WebP) and videos to efficient codecs (H.265, AV1). The system is designed as a monorepo containing both a Go-based conversion engine and a Raycast UI extension.

Monorepo Structure

camera-workflow/
├── cmd/                    # CLI commands
├── internal/               # Core Go packages
├── apps/raycast/          # Raycast extension UI
├── scripts/               # Build and utility scripts
├── main.go                # Application entry point
└── Makefile               # Build system

Core Architecture

Entry Point Flow

The application follows a clear execution flow:
  1. main.go → Minimal entry point that delegates to cmd package
  2. cmd/root.go → CLI interface using Cobra, flag binding, and pre-run validation
  3. internal/converter/ → Main conversion orchestrator
package main

import "github.com/Azilone/Camera-Workflow/cmd"

func main() {
    cmd.Execute()  // Delegates to Cobra CLI
}

Component Overview

Configuration

Package: internal/config/
  • Viper-based configuration management
  • YAML file support ($HOME/.media-converter.yaml)
  • Layered configuration: defaults → config file → env vars → CLI flags
  • Validation and sanitization

Conversion Engine

Package: internal/converter/
  • Orchestrates the entire conversion process
  • Manages worker pools with semaphores
  • Parallel processing for images and videos
  • Progress tracking and statistics

Security Layer

Package: internal/security/
  • Disk space checks (platform-specific)
  • File integrity verification
  • Conversion timeouts
  • Process marker management
  • Corruption detection and recovery

Logging System

Package: internal/logger/
  • Structured logging (Logrus)
  • Dual output: console + file
  • Colored output for terminal
  • JSON mode for Tauri integration

Utilities

Package: internal/utils/
  • File handling and validation
  • Dependency checks (FFmpeg, ImageMagick)
  • Format detection
  • Date extraction from metadata
  • Hardware acceleration detection

Checksum

Package: internal/checksum/
  • xxHash64 implementation
  • File integrity verification
  • Duplicate detection
  • Checksum tracking

API Layer

Package: internal/api/
  • JSON event streaming
  • Tauri frontend integration
  • Structured event types
  • Real-time progress updates

Internal Package Details

Configuration (internal/config/config.go)

The configuration system uses a layered approach with clear precedence:
type Config struct {
    // Directories
    SourceDir string
    DestDir   string

    // Processing
    MaxJobs        int
    DryRun         bool
    CopyOnly       bool
    VerifyChecksum bool
    JSONMode       bool

    // Image settings
    PhotoFormat      string  // "avif" or "webp"
    PhotoQualityAVIF int     // 1-100
    PhotoQualityWebP int     // 1-100

    // Video settings
    VideoCodec        string  // "h265", "h264", "av1"
    VideoCRF          int     // Constant Rate Factor
    VideoAcceleration bool    // Hardware acceleration

    // Adaptive worker management
    AdaptiveWorkers AdaptiveWorkerConfig

    // Security
    ConversionTimeoutPhoto time.Duration
    ConversionTimeoutVideo time.Duration
    MinOutputSizeRatio     float64
}
Configuration Precedence (highest to lowest):
  1. Command line flags
  2. Environment variables
  3. YAML config file
  4. Default values

Converter (internal/converter/converter.go)

The main conversion orchestrator manages the entire workflow: Key Responsibilities:
  • File discovery and categorization
  • Worker pool management (semaphore-based)
  • Progress tracking and statistics
  • Safety tests before batch processing
  • Recovery and cleanup operations
Processing Flow:
┌─────────────────────────────────────────────────┐
│ 1. Initialization                               │
│    - Validate directories                       │
│    - Check dependencies (FFmpeg, ImageMagick)   │
│    - Initialize logger                          │
└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐
│ 2. Recovery Phase                               │
│    - Cleanup abandoned .tmp files               │
│    - Remove stale .processing markers           │
│    - Verify existing converted files            │
│    - Re-queue corrupted files                   │
└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐
│ 3. Safety Test                                  │
│    - Test conversion on sample file             │
│    - Verify output integrity                    │
│    - Skip in dry-run mode                       │
└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐
│ 4. File Discovery                               │
│    - Walk source directory tree                 │
│    - Skip system files and directories          │
│    - Categorize by format (photo/video)         │
└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐
│ 5. Parallel Conversion                          │
│    - Image conversions (N workers)              │
│    - Video conversions (2 workers or adaptive)  │
│    - Real-time progress tracking                │
└─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐
│ 6. Final Report                                 │
│    - Statistics and timing                      │
│    - Space savings                              │
│    - S3 cost estimations                        │
└─────────────────────────────────────────────────┘

Image Conversion (internal/converter/image.go)

Handles photo conversions using ImageMagick:
  • Supports AVIF and WebP output formats
  • Quality settings per format (AVIF: 80, WebP: 85)
  • Metadata preservation
  • Output file validation

Video Conversion (internal/converter/video.go)

Handles video conversions using FFmpeg:
  • Codec support: H.265, H.264, AV1
  • Hardware acceleration detection (macOS VideoToolbox, Linux VAAPI/NVENC)
  • Progress tracking with time-based progress bars
  • AWS S3 cost estimation
  • Adaptive worker management

Security Checker (internal/security/security.go)

Provides comprehensive safety mechanisms: File Integrity:
  • VerifyOutputFile() - Validates converted files using external tools
  • IsFileCorrupted() - Detects corrupted existing files
  • VerifyFileIntegrity() - Comprehensive integrity checks
Process Management:
  • CreateProcessingMarker() - Marks files being processed (PID + timestamp)
  • RemoveProcessingMarker() - Cleans up after successful conversion
  • FindAbandonedMarkers() - Detects dead processes
  • CleanupAbandonedFiles() - Removes orphaned .tmp files
Disk Space:
  • Platform-specific implementations (Unix/Windows)
  • Pre-conversion space validation
  • Estimates needed space (50% of source for safety)

Logger (internal/logger/logger.go)

Structured logging with dual modes: Normal Mode:
  • Colored terminal output
  • Progress bars and statistics
  • File logging to {destination}/conversion.log
JSON Mode:
  • Structured events to stdout
  • File logging (no colors)
  • Tauri frontend integration
Event Types:
  • started - Conversion begins
  • progress - Overall progress updates
  • file_start - Individual file processing starts
  • file_end - Individual file processing completes
  • log - General log messages
  • error - Error events
  • complete - Conversion finished
  • statistics - Detailed stats

Utilities (internal/utils/utils.go)

Date Extraction (GetFileDate()): Extraction priority order:
  1. macOS mdls metadata (most reliable for RAW files)
  2. EXIF data via ImageMagick (EXIF:DateTimeOriginal)
  3. Video metadata via FFmpeg (creation_time)
  4. File modification time (with validation)
This ensures files are organized by actual creation date, not filesystem timestamps. File Organization:
  • CreateDestinationPath() - Generates organized paths
  • GetMonthName() - Multi-language month names (EN, FR, ES, DE)
  • ShouldSkipSystemEntry() - Filters system files/directories
Dependency Checks:
  • FFmpeg and ffprobe
  • ImageMagick (magick command)
  • Hardware acceleration detection

Checksum (internal/checksum/checksum.go)

Fast file integrity verification:
  • xxHash64 implementation (faster than MD5/SHA256)
  • Stream-based calculation (low memory usage)
  • Duplicate detection
  • Copy-mode verification

API (internal/api/json_writer.go)

JSON event streaming for frontend integration:
// Example event structure
type JSONEvent struct {
    Type      EventType   `json:"type"`
    Timestamp time.Time   `json:"timestamp"`
    Data      interface{} `json:"data"`
}

Adaptive Worker Management

For video conversions, the system supports adaptive worker scaling based on system resources: Components:
  • AdaptiveLimiter - Dynamic semaphore with adjustable limits
  • ResourceMonitor - Tracks CPU and memory usage
  • AdaptiveController - Adjusts worker count based on thresholds
Configuration:
adaptive_workers:
  enabled: true
  min: 1
  max: 6
  cpu_high: 80.0   # Reduce workers above 80% CPU
  cpu_low: 50.0    # Increase workers below 50% CPU
  mem_low_percent: 20.0  # Reduce workers if <20% memory available
  interval_seconds: 3

Safety and Idempotence

The system is designed to be 100% safe and idempotent:

Idempotent Operations

  • Run multiple times safely - already converted files are skipped
  • Resume after interruption (Ctrl+C, crashes, failures)
  • Atomic conversions via .tmp files + atomic rename

Safety Guarantees

  • Originals preserved by default (--keep-originals=true)
  • Triple verification before deletion
  • Processing markers track active conversions
  • Automatic recovery from crashes
  • Corruption detection

Recovery System

When resuming after interruption:
  1. Skips successfully converted files
  2. Cleans up temporary files from interrupted conversions
  3. Re-converts partially processed or corrupted files
  4. Continues from where it left off

Platform-Specific Code

Several packages have platform-specific implementations:
  • internal/security/diskspace_*.go - Disk space checks (Unix/Windows)
  • internal/security/process_check_*.go - Process existence checks (Unix/Windows)
  • internal/converter/resource_*.go - Resource monitoring (Darwin/Linux/Stub)
Build tags ensure the correct implementation is compiled for each platform.

External Dependencies

Required Tools

  • FFmpeg - Video conversion and metadata extraction
  • FFprobe - Video analysis
  • ImageMagick (magick) - Image conversion and EXIF data

Go Dependencies

  • github.com/spf13/cobra - CLI framework
  • github.com/spf13/viper - Configuration management
  • github.com/sirupsen/logrus - Structured logging
  • github.com/fatih/color - Terminal colors
  • golang.org/x/sync - Semaphore for worker pools
  • github.com/cespare/xxhash/v2 - Fast checksum calculation

Next Steps

Building

Learn how to build the project from source

Testing

Run tests and check coverage

Contributing

Contribute to the project

Build docs developers (and LLMs) love