Something went wrong. Try again.
Command-line HEIC/HEIF converter using Ente's image raster pipeline (main-branch-only mirror of forge.ejuarezg.com/ejuarezg/heic2img)
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422//! Content-based dispatch. Pixels follow the Ente pipeline pinned in NOTICE;//! filenames never select a decoder or an orientation branch.use anyhow::{Result, bail};use ente_heic::{DecodeGuardrails, image_integration::apply_exif_orientation_dynamic};use image::{DynamicImage, ImageDecoder, codecs::jpeg::JpegDecoder};use serde::Serialize;use std::{ fs::File, io::{Cursor, Read}, path::Path,};
pub const PIPELINE_VERSION: &str = "ente-rgb-v2";pub const MAX_INPUT_BYTES: u64 = 128 * 1024 * 1024;// Conservative worst-case RGBA16 allocation: 64M * 8 <= 512MiB. Codec// scratch and ICC/orientation/resize buffers are additional bounded allocations.pub const MAX_PIXELS: u64 = 64_000_000;pub const MAX_ALLOCATION: u64 = 512 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Format { Jpeg, Heic,}impl Format { pub fn name(self) -> &'static str { match self { Self::Jpeg => "jpeg", Self::Heic => "heic", } } fn extension_matches(self, path: &Path) -> bool { let ext = path .extension() .and_then(|s| s.to_str()) .unwrap_or("") .to_ascii_lowercase(); match self { Self::Jpeg => matches!(ext.as_str(), "jpg" | "jpeg"), Self::Heic => matches!(ext.as_str(), "heic" | "heif"), } }}
#[derive(Debug)]struct Failure(&'static str);impl std::fmt::Display for Failure { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.0) }}impl std::error::Error for Failure {}fn failure(code: &'static str) -> anyhow::Error { Failure(code).into()}
pub fn error_code(error: &anyhow::Error) -> &'static str { for cause in error.chain() { if let Some(Failure(code)) = cause.downcast_ref::<Failure>() { return code; } if let Some(image::ImageError::Limits(_)) = cause.downcast_ref::<image::ImageError>() { return "resource_limit"; } if cause.downcast_ref::<std::io::Error>().is_some() { return "io_error"; } } "corrupt_data"}
pub fn read_bounded(path: &Path) -> Result<Vec<u8>> { let file = File::open(path)?; let metadata = file.metadata()?; if !metadata.is_file() { return Err(failure("not_regular_file")); } if metadata.len() > MAX_INPUT_BYTES { return Err(failure("resource_limit")); } let mut bytes = Vec::new(); file.take(MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; if bytes.len() as u64 > MAX_INPUT_BYTES { return Err(failure("resource_limit")); } Ok(bytes)}
/// Inspect bounded container structure, not just a suffix or a generic BMFF/// signature. AVIF, timed HEIF sequences, MOV and MP4 are deliberately excluded./// Generic mif1 alone is not evidence of HEVC coding.pub fn detect(bytes: &[u8]) -> Result<Format> { if bytes.starts_with(&[0xff, 0xd8]) { return Ok(Format::Jpeg); } let mut pos = 0usize; while pos + 8 <= bytes.len() { let size = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as u64; let kind = &bytes[pos + 4..pos + 8]; // Do not interpret arbitrary non-BMFF inputs as corrupt HEIC. if pos == 0 && !matches!(kind, b"ftyp" | b"free" | b"skip" | b"wide") { return Err(failure("unsupported_format")); } let (size, header) = if size == 1 { if pos + 16 > bytes.len() { return Err(failure("corrupt_data")); } ( u64::from_be_bytes(bytes[pos + 8..pos + 16].try_into().unwrap()), 16usize, ) } else if size == 0 { ((bytes.len() - pos) as u64, 8) } else { (size, 8) }; if size < header as u64 || size > (bytes.len() - pos) as u64 { return Err(failure("corrupt_data")); } let end = pos + size as usize; if kind == b"ftyp" { let payload = &bytes[pos + header..end]; if payload.len() < 8 || !payload.len().is_multiple_of(4) { return Err(failure("corrupt_data")); } let brands = || { std::iter::once(&payload[..4]).chain( payload[8..] .as_chunks::<4>() .0 .iter() .map(|brand| brand.as_slice()), ) }; if brands().any(|b| { matches!( b, b"avif" | b"avis" | b"msf1" | b"hevc" | b"hevx" | b"hevm" | b"hevs" | b"qt " | b"mp41" | b"mp42" ) }) { return Err(failure("unsupported_format")); } if brands().any(|b| matches!(b, b"heic" | b"heix" | b"heim" | b"heis")) { return Ok(Format::Heic); } return Err(failure("unsupported_format")); } pos = end; } Err(failure("unsupported_format"))}
#[derive(Clone, Debug, Serialize)]pub struct Diagnostic { pub code: &'static str,}#[derive(Clone, Debug, Serialize)]pub struct Probe { pub schema_version: u32, pub pipeline_version: &'static str, pub tool_version: &'static str, pub ok: bool, pub actual_format: Option<&'static str>, pub extension_match: Option<bool>, /// Decoder raster before application-level EXIF. HEIC container transforms /// are already applied by the decoder, not raw coded tile dimensions. pub stored_dimensions: Option<[u32; 2]>, pub oriented_dimensions: Option<[u32; 2]>, pub orientation_handling: Option<&'static str>, pub color_status: Option<&'static str>, pub validation: &'static str, pub review_required: bool, pub warnings: Vec<Diagnostic>, pub errors: Vec<Diagnostic>,}impl Probe { fn new() -> Self { Self { schema_version: 1, pipeline_version: PIPELINE_VERSION, tool_version: env!("CARGO_PKG_VERSION"), ok: false, actual_format: None, extension_match: None, stored_dimensions: None, oriented_dimensions: None, orientation_handling: None, color_status: None, validation: "full_decode", review_required: false, warnings: vec![], errors: vec![], } } fn warning(&mut self, code: &'static str, review: bool) { self.warnings.push(Diagnostic { code }); self.review_required |= review; }}
pub struct DecodedRgb { pub width: u32, pub height: u32, pub rgb: Vec<u8>, pub probe: Probe,}
pub fn probe(path: &Path) -> Probe { let mut report = Probe::new(); match decode_inner(path, &mut report) { Ok(_) => report.ok = true, Err(error) => { report.review_required = true; report.errors.push(Diagnostic { code: error_code(&error), }); // Never print raw metadata, ICC blobs, or decoder error payloads. eprintln!("probe failed: {}", error_code(&error)); } } report}
pub fn decode(path: &Path) -> Result<DecodedRgb> { let mut report = Probe::new(); let image = decode_inner(path, &mut report)?; report.ok = true; let rgb = image.into_rgb8(); Ok(DecodedRgb { width: rgb.width(), height: rgb.height(), rgb: rgb.into_raw(), probe: report, })}
fn check_dimensions(width: u32, height: u32, channels_bytes: u64) -> Result<()> { let pixels = u64::from(width) * u64::from(height); if pixels == 0 { return Err(failure("corrupt_data")); } if pixels > MAX_PIXELS || pixels * channels_bytes > MAX_ALLOCATION { return Err(failure("resource_limit")); } Ok(())}
fn decode_inner(path: &Path, report: &mut Probe) -> Result<DynamicImage> { let bytes = read_bounded(path)?; let format = detect(&bytes)?; report.actual_format = Some(format.name()); report.extension_match = Some(format.extension_matches(path)); if !format.extension_matches(path) { report.warning("extension_mismatch", false); } let (image, icc, orientation) = match format { Format::Jpeg => decode_jpeg(&bytes, report)?, Format::Heic => { // Same pinned HEIC RGBA decoder as image-integration, with no suffix // hint and with a conservative pre-allocation pixel ceiling. let decoded = ente_heic::decode_bytes_to_rgba_with_guardrails( &bytes, DecodeGuardrails { max_input_bytes: Some(MAX_INPUT_BYTES), max_pixels: Some(MAX_PIXELS), max_temp_spool_bytes: Some(256 * 1024 * 1024), temp_spool_directory: None, }, ) .map_err(|error| { let code = match error.category() { ente_heic::DecodeErrorCategory::ResourceLimit => "resource_limit", ente_heic::DecodeErrorCategory::UnsupportedFeature => "unsupported_feature", _ => "corrupt_data", }; failure(code) })?; let decoded = decoded.into_dynamic_image_with_metadata()?; let hint = ente_heic::exif_orientation_hint(&bytes); report.orientation_handling = Some(if hint.primary_item_has_orientation_transform { "heic_container_already_applied" } else { "heic_exif_hint" }); ( decoded.image, decoded.icc_profile, hint.orientation_to_apply().unwrap_or(1), ) } }; check_dimensions( image.width(), image.height(), u64::from(image.color().bytes_per_pixel()), )?; report.stored_dimensions = Some([image.width(), image.height()]); let (image, status) = crate::color_management::apply_icc_profile_with_status(image, icc.as_deref()); report.color_status = Some(status); if !matches!(status, "srgb" | "converted_srgb" | "untagged_assumed_srgb") { report.warning(status, true); } let image = apply_exif_orientation_dynamic(image, orientation); report.oriented_dimensions = Some([image.width(), image.height()]); Ok(image)}
fn decode_jpeg(bytes: &[u8], report: &mut Probe) -> Result<(DynamicImage, Option<Vec<u8>>, u8)> { use zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions}; // image's JPEG wrapper uses zune in tolerant mode, which can accept // truncation. Use the SAME pinned engine in strict mode for production. // Guard input size before either engine buffers it, pixels before decode. if !bytes.windows(2).any(|marker| marker == [0xff, 0xd9]) { return Err(failure("corrupt_data")); } let options = DecoderOptions::default() .set_strict_mode(true) .set_max_width(65535) .set_max_height(65535); let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), options); decoder .decode_headers() .map_err(|_| failure("corrupt_data"))?; let (width, height) = decoder .dimensions() .ok_or_else(|| failure("corrupt_data"))?; check_dimensions(width as u32, height as u32, 3)?; report.stored_dimensions = Some([width as u32, height as u32]); let target = match decoder.input_colorspace() { Some(ColorSpace::Luma) => ColorSpace::Luma, Some(ColorSpace::RGB | ColorSpace::YCbCr) => ColorSpace::RGB, _ => return Err(failure("unsupported_color_space")), // CMYK/YCCK are NOT RGB + original ICC. }; decoder.set_options(decoder.options().jpeg_set_out_colorspace(target)); // Use image's standard EXIF parser, exactly the orientation source Ente uses. let mut metadata = JpegDecoder::new(Cursor::new(bytes))?; let orientation = match metadata.orientation() { Ok(value) => value.to_exif(), Err(_) => { report.warning("orientation_read_failed", true); metadata .exif_metadata() .ok() .flatten() .and_then(|exif| image::metadata::Orientation::from_exif_chunk(&exif)) .map_or(1, |o| o.to_exif()) } }; report.orientation_handling = Some("jpeg_standard_exif_once"); let mut icc = metadata.icc_profile().map_err(|_| failure("invalid_icc"))?; // zune returns None when declared ICC chunks cannot be reconstructed. Do // not mistake a malformed embedded profile for an untagged sRGB photo. if icc.is_none() && jpeg_declares_icc(bytes) { icc = Some(Vec::new()); } let pixels = decoder.decode().map_err(|_| failure("corrupt_data"))?; let image = if target == ColorSpace::Luma { DynamicImage::ImageLuma8( image::GrayImage::from_raw(width as u32, height as u32, pixels) .ok_or_else(|| failure("corrupt_data"))?, ) } else { DynamicImage::ImageRgb8( image::RgbImage::from_raw(width as u32, height as u32, pixels) .ok_or_else(|| failure("corrupt_data"))?, ) }; Ok((image, icc, orientation))}
fn jpeg_declares_icc(bytes: &[u8]) -> bool { let mut pos = 2; while pos + 4 <= bytes.len() { if bytes[pos] != 0xff { break; } while pos < bytes.len() && bytes[pos] == 0xff { pos += 1; } if pos >= bytes.len() { break; } let marker = bytes[pos]; pos += 1; if marker == 0xda || marker == 0xd9 { break; } if marker == 0x01 || (0xd0..=0xd8).contains(&marker) { continue; } if pos + 2 > bytes.len() { break; } let length = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]) as usize; if length < 2 || length > bytes.len() - pos { break; } if marker == 0xe2 && bytes[pos + 2..pos + length].starts_with(b"ICC_PROFILE\0") { return true; } pos += length; } false}
pub fn require_color_safe(report: &Probe) -> Result<()> { if report.review_required { bail!("color_review_required: fallback pixels are not verified sRGB; publication blocked"); } Ok(())}