mini-film 2.2.3

Apply Lightroom-style film emulation profiles to RAW files with RawTherapee and HALD workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::{
    fs,
    path::{Path, PathBuf},
    time::Duration,
};

use anyhow::{Context, Result, bail};
use indicatif::ProgressBar;
use mini_film::{GrainSettings, apply_grain, apply_grain_8bit};
use tempfile::Builder;

use crate::app::export::{
    finalize_output, output_ext, validate_export_options, validate_output_format,
};
use crate::app::profile::{
    ResolvedProfile, normalize_name, rawtherapee_profiles_with_hald, resolve_profile,
};
use crate::app::progress::{
    ApplyProgress, file_progress_style, progress_length, progress_stage_adaptive, progress_step,
};
use crate::app::raw::{run_raw_develop, run_raw_develop_jpeg};
use crate::app::util::{remove_temp_file, time_of_day_seed};
use crate::cli::ExportOptions;

pub(crate) struct ApplyArgs {
    pub(crate) raw: PathBuf,
    pub(crate) output: PathBuf,
    pub(crate) profile: String,
    pub(crate) hald_dir: PathBuf,
    pub(crate) profiles_root: PathBuf,
    pub(crate) hald_level: u32,
    pub(crate) rawtherapee: PathBuf,
    pub(crate) convert: PathBuf,
    pub(crate) keep_intermediate: Option<PathBuf>,
    pub(crate) no_grain: bool,
    pub(crate) grain: Option<String>,
    pub(crate) grain_preset: Option<String>,
    pub(crate) grain_seed: Option<u64>,
    pub(crate) export: ExportOptions,
}

pub(crate) struct ApplyJob<'a> {
    pub(crate) raw: &'a Path,
    pub(crate) output: &'a Path,
    pub(crate) rawtherapee: &'a Path,
    pub(crate) convert: &'a Path,
    pub(crate) keep_intermediate: Option<&'a Path>,
    pub(crate) no_grain: bool,
    pub(crate) export: &'a ExportOptions,
    pub(crate) quiet: bool,
}

/// Run the single-file apply command.
///
/// This validates output/export options, creates a temporary workspace, resolves
/// the selected profile into a Hald plus RawTherapee/grain metadata, applies any
/// explicit grain override, chooses a deterministic-or-time-based seed, and then
/// delegates the actual RAW/Hald/grain/export pipeline to `apply_resolved`.
pub(crate) fn run_apply(args: ApplyArgs) -> Result<()> {
    validate_output_format(&args.output)?;
    validate_export_options(&args.export)?;

    let temp_dir = Builder::new().prefix("mini-film-").tempdir()?;
    let mut resolved = resolve_profile(&args, temp_dir.path())?;
    if let Some(grain) =
        resolve_grain_override(args.grain.as_deref(), args.grain_preset.as_deref())?
    {
        resolved.grain = grain;
    }
    let grain_seed = args.grain_seed.unwrap_or_else(time_of_day_seed);

    let file = ProgressBar::new(progress_length());
    file.set_style(file_progress_style());
    file.set_message("starting");
    let started = std::time::Instant::now();
    let progress = ApplyProgress {
        file: &file,
        started,
        estimates: None,
    };

    let result = apply_resolved(
        ApplyJob {
            raw: &args.raw,
            output: &args.output,
            rawtherapee: &args.rawtherapee,
            convert: &args.convert,
            keep_intermediate: args.keep_intermediate.as_deref(),
            no_grain: args.no_grain,
            export: &args.export,
            quiet: true,
        },
        &resolved,
        grain_seed,
        temp_dir.path(),
        Some(&progress),
    );
    match &result {
        Ok(()) => file.finish_and_clear(),
        Err(_) => file.abandon_with_message("failed"),
    }
    result?;

    if let Some(hald_path) = &resolved.hald_path {
        eprintln!(
            "wrote {} using {}",
            args.output.display(),
            hald_path.display()
        );
    } else {
        eprintln!("wrote {} using RawTherapee PP3", args.output.display());
    }
    Ok(())
}

/// Apply an already resolved profile to one RAW input.
///
/// The function owns the processing graph. It develops RAW with RawTherapee
/// while applying generated `.pp3` adjustments and the Hald CLUT via Film
/// Simulation, using 8-bit JPEG intermediates for JPEG-bound outputs and 16-bit
/// TIFF intermediates for TIFF-bound outputs. It eagerly removes temporary
/// files, optionally renders grain in either 8-bit JPEG space or 16-bit TIFF
/// space, and finally exports to the requested output format while updating
/// progress bars for batch callers.
pub(crate) fn apply_resolved(
    job: ApplyJob<'_>,
    resolved: &ResolvedProfile,
    grain_seed: u64,
    temp_dir: &Path,
    progress: Option<&ApplyProgress<'_>>,
) -> Result<()> {
    validate_output_format(job.output)?;

    let grain_enabled = !job.no_grain && resolved.grain.is_enabled();
    let output_ext = output_ext(job.output)?;
    let jpeg_output = output_ext == "jpg" || output_ext == "jpeg";
    let jpeg_intermediate = jpeg_output && job.keep_intermediate.is_none();
    let intermediate = job
        .keep_intermediate
        .map(Path::to_path_buf)
        .unwrap_or_else(|| {
            if jpeg_intermediate {
                temp_dir.join("rawtherapee.jpg")
            } else {
                temp_dir.join("rawtherapee.tif")
            }
        });
    let cleanup_intermediate = job.keep_intermediate.is_none();

    let rawtherapee_profiles = rawtherapee_profiles_with_hald(resolved, temp_dir)?;
    let raw_stage = progress_stage_adaptive(
        progress,
        1,
        3,
        if jpeg_intermediate {
            "rawtherapee-jpeg"
        } else {
            "rawtherapee-tiff"
        },
        "rawtherapee",
        estimate_rawtherapee_duration(job.raw, jpeg_intermediate),
    );
    if jpeg_intermediate {
        run_raw_develop_jpeg(
            job.rawtherapee,
            &rawtherapee_profiles,
            job.raw,
            &intermediate,
            job.export.jpg_quality,
            job.export.jpeg_subsampling,
            job.quiet,
        )?;
    } else {
        run_raw_develop(
            job.rawtherapee,
            &rawtherapee_profiles,
            job.raw,
            &intermediate,
            job.quiet,
        )?;
    }
    raw_stage.finish();

    if grain_enabled && jpeg_output {
        let grain_stage = progress_stage_adaptive(
            progress,
            3,
            4,
            "grain-jpeg",
            "grain",
            estimate_grain_duration(job.raw, true),
        );
        let grained = temp_dir.join("grained-8.ppm");
        apply_grain_8bit(&intermediate, &grained, resolved.grain, grain_seed)?;
        grain_stage.finish();
        if progress.is_none() {
            eprintln!(
                "applied grain amount={} size={} frequency={}",
                resolved.grain.amount, resolved.grain.size, resolved.grain.frequency
            );
        }
        let export_stage = progress_stage_adaptive(
            progress,
            4,
            5,
            "export-jpeg",
            "jpeg export",
            estimate_export_duration(true),
        );
        finalize_output(job.convert, &grained, job.output, job.export)?;
        export_stage.finish();
        remove_temp_file(&grained)?;
    } else if grain_enabled {
        let grain_stage = progress_stage_adaptive(
            progress,
            3,
            4,
            "grain-tiff",
            "grain",
            estimate_grain_duration(job.raw, false),
        );
        let grained = temp_dir.join("grained.tif");
        apply_grain(&intermediate, &grained, resolved.grain, grain_seed)?;
        grain_stage.finish();
        if progress.is_none() {
            eprintln!(
                "applied grain amount={} size={} frequency={}",
                resolved.grain.amount, resolved.grain.size, resolved.grain.frequency
            );
        }
        let export_stage = progress_stage_adaptive(
            progress,
            4,
            5,
            "export-tiff",
            "export",
            estimate_export_duration(false),
        );
        finalize_output(job.convert, &grained, job.output, job.export)?;
        export_stage.finish();
        remove_temp_file(&grained)?;
    } else {
        progress_step(progress, 3, "grain skipped");
        let export_stage = progress_stage_adaptive(
            progress,
            4,
            5,
            if jpeg_output {
                "export-jpeg"
            } else {
                "export-tiff"
            },
            "export",
            estimate_export_duration(jpeg_output),
        );
        finalize_output(job.convert, &intermediate, job.output, job.export)?;
        export_stage.finish();
    }

    if cleanup_intermediate {
        remove_temp_file(&intermediate)?;
    }

    progress_step(progress, 5, "done");
    Ok(())
}

fn estimate_rawtherapee_duration(raw: &Path, jpeg_intermediate: bool) -> Duration {
    let mib = file_size_mib(raw).unwrap_or(45.0);
    let seconds = if jpeg_intermediate {
        1.2 + mib * 0.075
    } else {
        2.0 + mib * 0.11
    };
    Duration::from_secs_f64(seconds.clamp(2.0, 18.0))
}

fn estimate_grain_duration(raw: &Path, jpeg_output: bool) -> Duration {
    let mib = file_size_mib(raw).unwrap_or(45.0);
    let seconds = if jpeg_output {
        0.35 + mib * 0.018
    } else {
        0.9 + mib * 0.045
    };
    Duration::from_secs_f64(seconds.clamp(0.6, 8.0))
}

fn estimate_export_duration(jpeg_output: bool) -> Duration {
    if jpeg_output {
        Duration::from_millis(900)
    } else {
        Duration::from_secs(2)
    }
}

fn file_size_mib(path: &Path) -> Option<f64> {
    Some(fs::metadata(path).ok()?.len() as f64 / 1_048_576.0)
}

/// Resolve command-line grain overrides.
///
/// XMP grain is used by default, but users can override it with either an
/// explicit `amount,size,frequency` tuple or a named preset. The two override
/// forms are mutually exclusive, and `none`/`off` intentionally resolves to
/// disabled grain rather than an error.
pub(crate) fn resolve_grain_override(
    grain: Option<&str>,
    preset: Option<&str>,
) -> Result<Option<GrainSettings>> {
    match (grain, preset) {
        (Some(_), Some(_)) => bail!("use either --grain or --grain-preset, not both"),
        (Some(value), None) => Ok(Some(parse_grain(value)?)),
        (None, Some(value)) => Ok(Some(match normalize_name(value).as_str() {
            "none" | "off" => GrainSettings::default(),
            "light" => GrainSettings {
                amount: 18,
                size: 35,
                frequency: 40,
            },
            "medium" => GrainSettings {
                amount: 30,
                size: 45,
                frequency: 45,
            },
            "heavy" => GrainSettings {
                amount: 45,
                size: 60,
                frequency: 55,
            },
            _ => bail!("unknown grain preset {value:?}; use light, medium, heavy, or none"),
        })),
        (None, None) => Ok(None),
    }
}

fn parse_grain(value: &str) -> Result<GrainSettings> {
    let parts: Vec<_> = value.split(',').map(str::trim).collect();
    if parts.len() != 3 {
        bail!("--grain must be amount,size,frequency, for example --grain 30,45,45");
    }
    Ok(GrainSettings {
        amount: parse_grain_part(parts[0], "amount")?,
        size: parse_grain_part(parts[1], "size")?,
        frequency: parse_grain_part(parts[2], "frequency")?,
    })
}

fn parse_grain_part(value: &str, name: &str) -> Result<u8> {
    let parsed: u16 = value
        .parse()
        .with_context(|| format!("invalid grain {name} value {value:?}"))?;
    if parsed > 100 {
        bail!("grain {name} must be in 0..100");
    }
    Ok(parsed as u8)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn grain_override_accepts_tuple_presets_and_none() {
        let grain = resolve_grain_override(Some("10, 20,30"), None)
            .unwrap()
            .unwrap();
        assert_eq!(grain.amount, 10);
        assert_eq!(grain.size, 20);
        assert_eq!(grain.frequency, 30);

        let grain = resolve_grain_override(None, Some("heavy"))
            .unwrap()
            .unwrap();
        assert_eq!(grain.amount, 45);
        assert_eq!(grain.size, 60);
        assert_eq!(grain.frequency, 55);

        assert!(
            !resolve_grain_override(None, Some("none"))
                .unwrap()
                .unwrap()
                .is_enabled()
        );
    }

    #[test]
    fn grain_override_rejects_ambiguous_or_out_of_range_values() {
        assert!(resolve_grain_override(Some("1,2,3"), Some("light")).is_err());
        assert!(resolve_grain_override(Some("1,2"), None).is_err());
        assert!(resolve_grain_override(Some("1,2,101"), None).is_err());
        assert!(resolve_grain_override(None, Some("huge")).is_err());
    }

    #[test]
    fn duration_estimates_are_clamped_and_depend_on_output_path() {
        let dir = tempfile::tempdir().unwrap();
        let raw = dir.path().join("raw.dng");
        std::fs::File::create(&raw)
            .unwrap()
            .write_all(&vec![0u8; 2 * 1024 * 1024])
            .unwrap();

        let jpeg = estimate_rawtherapee_duration(&raw, true);
        let tiff = estimate_rawtherapee_duration(&raw, false);
        assert!(jpeg >= Duration::from_secs(2));
        assert!(tiff >= jpeg);
        assert_eq!(estimate_export_duration(true), Duration::from_millis(900));
        assert_eq!(estimate_export_duration(false), Duration::from_secs(2));
    }

    #[test]
    fn missing_file_size_returns_none() {
        assert!(file_size_mib(Path::new("/definitely/missing/raw.dng")).is_none());
    }
}