mixvideo-v2/docs/watermark-processing-tool.md

424 lines
11 KiB
Markdown

# 批量水印处理工具 - 技术文档
## 概述
批量水印处理工具是 MixVideo Desktop 应用的核心功能模块,提供智能水印检测、移除和批量添加功能。该工具集成到现有的视频处理流水线中,支持多种水印类型和处理算法。
## 功能特性
### 1. 水印检测
- **多算法支持**: 模板匹配、边缘检测、频域分析、透明度检测
- **智能采样**: 基于帧采样率的高效检测
- **区域检测**: 支持全帧、四角、边缘、中心等检测区域
- **置信度评分**: 提供检测结果的可信度评估
### 2. 水印移除
- **多种方法**: AI修复、模糊处理、裁剪移除、遮罩覆盖、内容感知填充、克隆修复
- **质量控制**: 支持低、中、高、无损四种质量级别
- **区域指定**: 可指定特定区域进行水印移除
- **批量处理**: 支持大规模视频文件的批量处理
### 3. 水印添加
- **多种类型**: 图片水印、矢量水印、文字水印、动态水印
- **灵活定位**: 9个预设位置 + 自定义位置 + 动态位置
- **丰富效果**: 透明度、缩放、旋转、动画、混合模式
- **智能避让**: 可避开人脸、文字等重要内容
### 4. 模板管理
- **分类管理**: Logo、版权、签名、装饰、自定义分类
- **格式支持**: PNG、JPG、SVG、GIF等多种格式
- **缩略图生成**: 自动生成预览缩略图
- **导入导出**: 支持模板的导入导出功能
## 技术架构
### 后端架构 (Rust)
```
apps/desktop/src-tauri/src/
├── data/
│ ├── models/watermark.rs # 数据模型定义
│ └── repositories/
│ └── watermark_template_repository.rs # 数据访问层
├── business/
│ ├── services/
│ │ ├── watermark_detection_service.rs # 检测服务
│ │ ├── watermark_removal_service.rs # 移除服务
│ │ ├── watermark_addition_service.rs # 添加服务
│ │ ├── watermark_template_service.rs # 模板管理服务
│ │ └── batch_watermark_processor.rs # 批量处理器
│ └── errors/watermark_errors.rs # 错误处理
└── presentation/
└── commands/watermark_commands.rs # Tauri命令接口
```
### 前端架构 (React + TypeScript)
```
apps/desktop/src/
├── components/
│ └── WatermarkToolDialog.tsx # 主界面组件
├── types/
│ └── watermark.ts # 类型定义
└── hooks/
└── useWatermarkProcessing.ts # 自定义Hook
```
### 数据库设计
```sql
-- 水印模板表
CREATE TABLE watermark_templates (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
file_path TEXT NOT NULL,
thumbnail_path TEXT,
category TEXT NOT NULL,
watermark_type TEXT NOT NULL,
file_size INTEGER NOT NULL,
width INTEGER,
height INTEGER,
description TEXT,
tags TEXT,
is_active INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- 水印检测结果表
CREATE TABLE watermark_detection_results (
id TEXT PRIMARY KEY,
material_id TEXT NOT NULL,
detection_method TEXT NOT NULL,
detections TEXT NOT NULL,
confidence_score REAL NOT NULL,
processing_time_ms INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (material_id) REFERENCES materials(id)
);
-- 批量处理任务表
CREATE TABLE batch_watermark_tasks (
task_id TEXT PRIMARY KEY,
operation TEXT NOT NULL,
material_ids TEXT NOT NULL,
config TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'Pending',
progress TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
started_at DATETIME,
completed_at DATETIME
);
-- 处理结果表
CREATE TABLE watermark_processing_results (
id TEXT PRIMARY KEY,
material_id TEXT NOT NULL,
operation TEXT NOT NULL,
success INTEGER NOT NULL,
output_path TEXT,
processing_time_ms INTEGER NOT NULL,
error_message TEXT,
metadata TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (material_id) REFERENCES materials(id)
);
```
## API 接口
### Tauri 命令
#### 水印检测
```rust
#[tauri::command]
pub async fn detect_watermarks_in_video(
state: State<'_, AppState>,
material_id: String,
video_path: String,
config: WatermarkDetectionConfig,
) -> Result<WatermarkDetectionResult, String>
#[tauri::command]
pub async fn detect_watermarks_in_image(
material_id: String,
image_path: String,
config: WatermarkDetectionConfig,
) -> Result<WatermarkDetectionResult, String>
```
#### 水印移除
```rust
#[tauri::command]
pub async fn remove_watermarks_from_video(
state: State<'_, AppState>,
material_id: String,
input_path: String,
output_path: String,
config: WatermarkRemovalConfig,
) -> Result<WatermarkProcessingResult, String>
```
#### 水印添加
```rust
#[tauri::command]
pub async fn add_watermark_to_video(
state: State<'_, AppState>,
material_id: String,
input_path: String,
output_path: String,
watermark_path: String,
config: WatermarkConfig,
) -> Result<WatermarkProcessingResult, String>
```
#### 批量处理
```rust
#[tauri::command]
pub async fn start_batch_watermark_task(
state: State<'_, AppState>,
operation: WatermarkOperation,
material_ids: Vec<String>,
config: serde_json::Value,
) -> Result<String, String>
```
#### 模板管理
```rust
#[tauri::command]
pub async fn get_watermark_templates(
category: Option<String>,
watermark_type: Option<String>,
) -> Result<Vec<WatermarkTemplate>, String>
#[tauri::command]
pub async fn upload_watermark_template(
name: String,
file_path: String,
category: String,
watermark_type: String,
description: Option<String>,
tags: Vec<String>,
) -> Result<WatermarkTemplate, String>
```
## 配置参数
### 检测配置 (WatermarkDetectionConfig)
```typescript
interface WatermarkDetectionConfig {
similarity_threshold: number; // 相似度阈值 0.0-1.0
min_watermark_size: [number, number]; // 最小水印尺寸
max_watermark_size: [number, number]; // 最大水印尺寸
detection_regions: DetectionRegion[]; // 检测区域
frame_sample_rate: number; // 帧采样率
methods: DetectionMethod[]; // 检测方法
template_ids?: string[]; // 指定模板ID
}
```
### 移除配置 (WatermarkRemovalConfig)
```typescript
interface WatermarkRemovalConfig {
method: RemovalMethod; // 移除方法
quality_level: QualityLevel; // 质量级别
preserve_aspect_ratio: boolean; // 保持宽高比
target_regions?: BoundingBox[]; // 目标区域
blur_radius?: number; // 模糊半径
crop_margin?: number; // 裁剪边距
}
```
### 添加配置 (WatermarkConfig)
```typescript
interface WatermarkConfig {
watermark_type: WatermarkType; // 水印类型
position: WatermarkPosition; // 位置
opacity: number; // 透明度 0.0-1.0
scale: number; // 缩放比例
rotation: number; // 旋转角度
animation?: WatermarkAnimation; // 动画配置
blend_mode: BlendMode; // 混合模式
quality_level: QualityLevel; // 质量级别
}
```
## 性能优化
### 1. 并行处理
- 使用 Rayon 并行处理多个视频文件
- 异步任务队列管理批量处理
- 智能任务调度和资源分配
### 2. 内存优化
- 分块处理大视频文件
- 及时释放临时资源
- 缓存机制减少重复计算
### 3. 算法优化
- 智能帧采样减少计算量
- 多级检测策略提高效率
- 预处理优化提升检测精度
### 4. 缓存策略
- 检测结果缓存
- 水印模板缓存
- 缩略图缓存
## 错误处理
### 错误类型
```rust
pub enum WatermarkError {
DetectionFailed { message: String },
RemovalFailed { message: String },
AdditionFailed { message: String },
UnsupportedFormat { format: String, supported: Vec<String> },
FFmpegError { message: String },
TemplateNotFound { template_id: String },
BatchTaskFailed { task_id: String, message: String },
// ... 更多错误类型
}
```
### 错误分类
- **用户错误**: 输入验证、格式不支持、模板不存在等
- **系统错误**: FFmpeg执行失败、文件操作失败、数据库错误等
- **网络错误**: 连接超时、请求失败等(可重试)
### 错误恢复
- 自动重试机制
- 优雅降级处理
- 详细错误日志记录
## 测试策略
### 单元测试
- 数据模型验证
- 业务逻辑测试
- 错误处理测试
- 配置验证测试
### 集成测试
- 端到端处理流程
- 数据库操作测试
- 文件系统交互测试
### 性能测试
- 大批量文件处理
- 内存使用监控
- 处理时间基准测试
## 部署和配置
### 依赖要求
- FFmpeg (视频处理)
- SQLite (数据存储)
- OpenCV (图像处理,可选)
### 配置文件
```toml
[watermark]
# 默认检测配置
default_similarity_threshold = 0.8
default_frame_sample_rate = 30
# 性能配置
max_concurrent_tasks = 4
max_memory_usage_mb = 2048
# 文件路径配置
template_directory = "watermarks/templates"
cache_directory = "watermarks/cache"
temp_directory = "watermarks/temp"
```
### 目录结构
```
watermarks/
├── templates/ # 水印模板存储
│ ├── {template_id}/
│ │ ├── template.png
│ │ └── thumbnail.jpg
├── cache/ # 缓存文件
└── temp/ # 临时文件
```
## 使用示例
### 前端调用示例
```typescript
// 检测水印
const detectionResult = await invoke('detect_watermarks_in_video', {
materialId: 'material_123',
videoPath: '/path/to/video.mp4',
config: {
similarity_threshold: 0.8,
frame_sample_rate: 30,
methods: ['TemplateMatching', 'EdgeDetection']
}
});
// 批量移除水印
const taskId = await invoke('start_batch_watermark_task', {
operation: 'Remove',
materialIds: ['material_1', 'material_2'],
config: {
method: 'Blurring',
quality_level: 'Medium',
blur_radius: 5.0
}
});
```
## 扩展性
### 新增检测算法
1.`DetectionMethod` 枚举中添加新方法
2.`WatermarkDetectionService` 中实现算法
3. 更新配置和文档
### 新增移除方法
1.`RemovalMethod` 枚举中添加新方法
2.`WatermarkRemovalService` 中实现方法
3. 添加相应的配置参数
### 新增水印类型
1.`WatermarkType` 枚举中添加类型
2. 更新模板验证逻辑
3. 实现对应的处理逻辑
## 维护和监控
### 日志记录
- 结构化日志输出
- 性能指标记录
- 错误详情追踪
### 监控指标
- 处理成功率
- 平均处理时间
- 内存使用情况
- 错误频率统计
### 故障排查
- 详细的错误上下文
- 处理步骤追踪
- 性能瓶颈分析
## 版本历史
### v1.0.0 (当前版本)
- 基础水印检测、移除、添加功能
- 模板管理系统
- 批量处理支持
- 错误处理和日志系统
- 单元测试和集成测试
### 未来规划
- AI增强的水印检测算法
- 更多水印类型支持
- 云端处理能力
- 实时预览功能
- 性能优化和算法改进