npm package: @mks2508/videopt
Description: ⚡ Professional video optimizer CLI with hardware acceleration support. Compress, analyze, and compare video files with intelligent presets.
Author: MKS2508
Latest version: 1.0.0

# ⚡ videopt

**Professional video optimizer CLI with hardware acceleration**

[![NPM Version](https://img.shields.io/npm/v/%40mks2508%2Fvideopt?label=npm&color=cb3837)](https://www.npmjs.com/package/@mks2508/videopt)
![Node](https://img.shields.io/node/v/%40mks2508%2Fvideopt)
![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)
![License](https://img.shields.io/badge/license-MIT-green)

A powerful, lightning-fast video optimization tool that leverages hardware acceleration (Apple VideoToolbox, NVENC, QSV) to compress, analyze, and compare video files with intelligent presets. Built with modern TypeScript and designed for developers who demand both performance and quality.

- Fast hardware-accelerated encoding (H.264 / H.265 / AV1)
- Smart presets: telegram, personal, archive, streaming, mobile
- Detailed analysis and quality metrics (PSNR, SSIM, VMAF)
- Batch processing with progress bars and robust error handling
- Beautiful CLI with colors, spinners, and module-aware logging

## 📚 Table of Contents
- [Features](#-features)
- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Usage Examples](#-usage)
- [Presets](#-presets)
- [Hardware Acceleration](#-hardware-acceleration)
- [Quality & Comparison](#-quality--comparison)
- [Error Handling & Logging](#-error-handling--logging)
- [CLI Commands](#-cli-commands)
- [Development](#-development)
- [Acknowledgments](#-acknowledgments)

## ✨ Features

- 🚀 **Apple M2 VideoToolbox** hardware acceleration
- 🎯 **5 optimization presets**: telegram, personal, archive, streaming, mobile
- 📊 **Detailed video analysis** with FFprobe integration
- ⚡ **Real-time progress tracking** with spinners and progress bars
- 🔍 **File comparison** with quality metrics (PSNR, SSIM, VMAF)
- 🛡️ **Robust error handling** with Result Pattern
- 📝 **Advanced logging** with colors, animations, and module prefixes
- 🎨 **Beautiful CLI** interface with gradients and emojis

## 🚀 Quick Start

### Prerequisites

- **Bun** runtime installed
- **FFmpeg** with VideoToolbox support
- **macOS** with Apple Silicon (M1/M2/M3)

### Installation

#### Option 1: From npm (Recommended)

```bash
# Install globally (recommended)
npm install -g @mks2508/videopt

# Then use the short command
videopt --help

# Or use with npx (no installation needed)
npx @mks2508/videopt --help
```

#### Option 2: From source

```bash
# Clone the repository
git clone <your-repo-url>
cd movies-optimizer-bun

# Install dependencies
bun install

# Build the project
npm run build
```

### Usage

```bash
# Check system capabilities
videopt check

# Analyze a video file
videopt analyze video.mkv

# Optimize with different presets
videopt optimize input.mkv --preset telegram
videopt optimize input.mkv output.mkv --preset personal --backup

# Compare two files
videopt compare original.mkv optimized.mkv --metrics --detailed

# See all options
videopt --help
```

## 🎯 Optimization Presets

| Preset | Codec | Target | Use Case |
|--------|-------|--------|----------|
| `telegram` | H.264 | ~3 Mbps, <= 2GB | Messaging apps, max compatibility |
| `personal` | H.265 | CRF 22 | Daily use, great quality/size |
| `archive` | H.265 | CRF 20 | High quality preservation |
| `streaming` | H.264 | 4 Mbps + faststart | Web playback |
| `mobile` | H.264 | 1.5–2 Mbps | Phones and low bandwidth |

Tips:
- Use `personal` for la mayoría de casos (mejor relación calidad/tamaño)
- `telegram` limita el tamaño resultante mediante bitrate para ajustarse a 2GB
- `archive` conserva más calidad, tardará más y pesará más

| Preset | Codec | Bitrate | Use Case |
|--------|-------|---------|----------|
| `telegram` | H.264 | 3 Mbps | Messaging apps (max 2GB) |
| `personal` | H.265 | 4-5 Mbps | Balanced quality/size ⭐ |
| `archive` | H.265 | 6-8 Mbps | High quality preservation |
| `streaming` | H.264 | 4 Mbps | Web-optimized with fast-start |
| `mobile` | H.264 | 1.5 Mbps | Mobile-friendly |

## 🛠️ Development

```bash
# Development with auto-reload
bun run dev

# Type checking
bun run typecheck

# Run tests
bun test

# Build for production
bun run build
```

## 🧰 CLI Commands

```bash
videopt check                    # Detect hardware capabilities
videopt analyze <file>           # Analyze streams, bitrates, codecs
videopt optimize <in> [out]      # Optimize with presets/hardware accel
videopt compare <orig> <opt>     # Compare and compute metrics
videopt batch <inDir> [outDir]   # Batch processing (WIP)
```

## 📁 Project Structure

```
src/
├── commands/           # CLI command implementations
│   ├── analyze.ts     # Video analysis command
│   ├── optimize.ts    # Video optimization command
│   └── compare.ts     # File comparison command
├── utils/             # Core utilities
│   ├── ffmpeg.ts      # FFmpeg integration
│   └── logger.ts      # Advanced logging system
├── types/             # Type definitions
│   └── result.ts      # Result pattern implementation
├── schemas/           # Zod validation schemas
│   └── video.ts       # Video-related schemas
└── index.ts           # Main CLI entry point
```

## 🧪 Testing

The project includes comprehensive tests with sample video files:

```bash
# Run all tests
bun test

# Run specific test file
bun test tests/analyze.test.ts

# Run tests with coverage
bun test --coverage
```

## ⚡ Hardware Acceleration

- ✅ Apple VideoToolbox (M1/M2/M3)
- ✅ NVIDIA NVENC (Linux/Windows)
- ✅ Intel QSV
- ✅ VAAPI / AMF (Linux/AMD)

videopt detecta automáticamente el mejor encoder disponible y hace fallback a software cuando es necesario.

The CLI automatically detects and uses hardware acceleration:

- ✅ **VideoToolbox** (Apple Silicon)
- ✅ **NVENC** (NVIDIA GPUs)
- ✅ **QSV** (Intel Quick Sync)
- ✅ **VAAPI** (Linux)
- ✅ **AMF** (AMD)

## 🔧 Configuration

### Error Handling

Uses Result Pattern for robust error handling:

```typescript
const result = await optimizeVideo(config);
if (result.success) {
  console.log('Success:', result.data);
} else {
  console.error('Error:', result.error);
}
```

### Logging

Advanced logging with module prefixes:

```typescript
logger.info('Starting optimization', { 
  module: LogModule.OPTIMIZER, 
  function: 'optimizeVideo' 
});
```

## 🎛️ Error Handling & Logging

- Result Pattern con `Ok/Err` para operaciones robustas
- Errores tipados: System, FFmpeg, Validation, Hardware, Critical
- Logger avanzado con módulos (SYS, FFM, OPT, ANA, CMP) y severidades
- Spinners y progress bars para feedback en tiempo real

## 📈 Performance

- **Hardware Acceleration**: Up to 10x faster encoding
- **Multi-threading**: Automatic core utilization
- **Memory Efficient**: Streaming processing
- **Progress Tracking**: Real-time speed metrics

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

**Special thanks to the incredible [FFmpeg team](https://ffmpeg.org/)**  
The legends who craft assembly code by hand to squeeze every bit of performance from hardware. Their decades of optimization wizardry make tools like videopt possible. FFmpeg is the backbone of digital video – respect! 💪

- **Author**: [MKS2508](https://github.com/MKS2508) - Passionate about video optimization and developer tools
- **Built with**: [Bun](https://bun.sh/) for lightning-fast performance and modern JavaScript runtime
- **Powered by**: [FFmpeg](https://ffmpeg.org/) - The Swiss Army knife of video processing
- **Inspired by**: Modern CLI design principles and the need for hardware-accelerated video tools