Skip to main content

esp_hal/
jpeg.rs

1//! Hardware baseline JPEG encoding.
2//!
3//! ## Supported formats
4//!
5//! | Input layout | Output subsampling |
6//! | --- | --- |
7//! | RGB565 and BGR565 (either byte order), RGB888, BGR888 | 4:4:4, 4:2:2, 4:2:0 |
8//! | YCbCr 4:4:4 (YUV, VUY) | 4:4:4, 4:2:2, 4:2:0 |
9//! | YCbCr 4:2:2 (YUYV, UYVY) | 4:2:2, 4:2:0 |
10//! | Packed YCbCr 4:2:0 | 4:2:0 |
11//! | Grayscale | Grayscale |
12
13mod format;
14mod header;
15
16use core::{
17    ptr,
18    sync::atomic::{Ordering, compiler_fence},
19};
20
21use self::format::{InputLayout, Sampling};
22pub use self::format::{PixelFormat, Subsampling};
23use crate::{
24    dma::aligned::{PSRAM_CACHE_LINE, region_dma_alignment},
25    dma2d::{AnyDma2dRxChannel, BURST_128_BYTES, Channels, invalidate, writeback},
26    pac::jpeg::int_raw::R as InterruptStatus,
27    peripherals::{DMA2D, DMA2D_TX_CH0, JPEG},
28    soc::{is_slice_in_dram, is_slice_in_psram},
29    system::{GenericPeripheralGuard, Peripheral, PeripheralClockControl},
30    time::{Duration, Instant},
31};
32
33const RX_BUFFER_ALIGNMENT: usize = 4;
34const JPEG_TRIGGER: u8 = 0;
35const DMA_FIELD_BITS: u32 = 14;
36const DMA_FIELD_MASK: u32 = (1 << DMA_FIELD_BITS) - 1;
37const MAX_DIMENSION: usize = DMA_FIELD_MASK as usize;
38const MAX_PAYLOAD: usize = (1 << (2 * DMA_FIELD_BITS)) - 1;
39
40const _: () = core::assert!(header::LEN.is_multiple_of(PSRAM_CACHE_LINE));
41
42/// A JPEG encoder error.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[cfg_attr(feature = "defmt", derive(defmt::Format))]
45#[non_exhaustive]
46#[instability::unstable]
47pub enum Error {
48    /// Invalid dimensions, quality, or input size.
49    InvalidInput,
50    /// Unsupported buffer memory region, size, or alignment.
51    InvalidBuffer,
52    /// Incompatible input pixel format and output subsampling.
53    UnsupportedFormat,
54    /// Insufficient space for the compressed image.
55    OutputTooSmall,
56    /// The configured completion wait expired.
57    Timeout,
58    /// JPEG or DMA2D hardware error.
59    Hardware,
60}
61
62impl core::error::Error for Error {}
63
64impl core::fmt::Display for Error {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        f.write_str(match self {
67            Self::InvalidInput => "invalid JPEG input",
68            Self::InvalidBuffer => "invalid JPEG buffer",
69            Self::UnsupportedFormat => "incompatible input format and subsampling",
70            Self::OutputTooSmall => "JPEG output buffer is too small",
71            Self::Timeout => "JPEG encoding timed out",
72            Self::Hardware => "JPEG hardware error",
73        })
74    }
75}
76
77/// JPEG encoding settings.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79#[cfg_attr(feature = "defmt", derive(defmt::Format))]
80#[instability::unstable]
81pub struct EncodeConfig {
82    /// Image width in pixels, from 1 to 16383.
83    pub width: u16,
84    /// Image height in pixels, from 1 to 16383.
85    pub height: u16,
86    /// Compression quality, from 1 to 100.
87    pub quality: u8,
88    /// Pixel layout of the input image.
89    pub input_format: PixelFormat,
90    /// Chroma subsampling of the encoded JPEG.
91    pub subsampling: Subsampling,
92}
93
94/// A blocking baseline JPEG encoder.
95#[derive(Debug)]
96#[instability::unstable]
97pub struct Encoder<'d> {
98    _peripheral: JPEG<'d>,
99    _memory: MemoryPower,
100    channels: Channels<'d>,
101    _guard: GenericPeripheralGuard<{ Peripheral::Jpeg as u8 }>,
102    timeout: Option<Duration>,
103}
104
105impl<'d> Encoder<'d> {
106    /// Creates a new JPEG encoder using DMA2D TX0 for macroblock reordering.
107    #[instability::unstable]
108    pub fn new(
109        peripheral: JPEG<'d>,
110        tx: DMA2D_TX_CH0<'d>,
111        rx: impl Into<AnyDma2dRxChannel<'d>>,
112    ) -> Self {
113        Self {
114            _peripheral: peripheral,
115            channels: Channels::new(tx, rx),
116            _guard: GenericPeripheralGuard::new(),
117            _memory: MemoryPower::force_on(),
118            timeout: None,
119        }
120    }
121
122    /// Sets the software timeout for JPEG completion.
123    ///
124    /// The timeout is disabled by default (`None`).
125    /// DMA cleanup can extend past this limit.
126    #[instability::unstable]
127    pub fn set_timeout(&mut self, timeout: Option<Duration>) {
128        self.timeout = timeout;
129    }
130
131    /// Encodes a tightly packed image and returns the JPEG length in bytes.
132    ///
133    /// See [supported formats](crate::jpeg#supported-formats) for valid format combinations
134    /// and [`PixelFormat`] for input layout requirements.
135    ///
136    /// The input must be in SRAM or initialized PSRAM.
137    /// RGB565, BGR565, and YCbCr 4:2:2 input must be aligned to two bytes.
138    ///
139    /// The output address and length must be multiples of
140    #[doc = cfg_select! {
141        esp32p4 => "64 bytes in cached SRAM, 4 bytes in uncached SRAM, or 128 bytes in PSRAM.",
142        esp32s31 => "4 bytes in SRAM or 64 bytes in PSRAM.",
143    }]
144    /// PSRAM configurations that require strictly aligned memory transactions, such as encryption
145    /// or ECC, are unsupported.
146    /// Output contents are unspecified on error.
147    ///
148    /// # Errors
149    ///
150    /// - [`Error::InvalidInput`] when dimensions or quality are invalid, or the input is too short.
151    /// - [`Error::UnsupportedFormat`] when the input format and subsampling are incompatible.
152    /// - [`Error::InvalidBuffer`] when a buffer is inaccessible or unaligned, or the output payload
153    ///   capacity exceeds the DMA descriptor limit.
154    /// - [`Error::OutputTooSmall`] when the JPEG does not fit.
155    /// - [`Error::Timeout`] when the configured completion wait expires.
156    /// - [`Error::Hardware`] on a JPEG or DMA2D error.
157    #[instability::unstable]
158    pub fn encode(
159        &mut self,
160        input: &[u8],
161        output: &mut [u8],
162        config: EncodeConfig,
163    ) -> Result<usize, Error> {
164        let EncodeConfig {
165            width,
166            height,
167            quality,
168            input_format,
169            subsampling,
170        } = config;
171        let width_usize = usize::from(width);
172        let height_usize = usize::from(height);
173        if !(1..=MAX_DIMENSION).contains(&width_usize)
174            || !(1..=MAX_DIMENSION).contains(&height_usize)
175            || !(1..=100).contains(&quality)
176        {
177            return Err(Error::InvalidInput);
178        }
179        let layout = InputLayout::new(input_format, subsampling, width_usize, height_usize)?;
180        let input = input.get(..layout.len).ok_or(Error::InvalidInput)?;
181        if output.len() <= header::LEN {
182            return Err(Error::OutputTooSmall);
183        }
184        let output_alignment = region_dma_alignment(output.as_ptr() as usize)
185            .ok_or(Error::InvalidBuffer)?
186            .max(RX_BUFFER_ALIGNMENT);
187        if !(is_slice_in_dram(input) || is_slice_in_psram(input))
188            || !(is_slice_in_dram(output) || is_slice_in_psram(output))
189            || !(input.as_ptr() as usize).is_multiple_of(layout.alignment)
190            || !(output.as_ptr() as usize).is_multiple_of(output_alignment)
191            || !output.len().is_multiple_of(output_alignment)
192            || output.len() - header::LEN > MAX_PAYLOAD
193        {
194            return Err(Error::InvalidBuffer);
195        }
196
197        let sampling = Sampling::new(subsampling);
198        let (luminance, chrominance) = header::quantization_tables(quality, &sampling);
199        let chrominance = chrominance.as_ref();
200        let (header, payload) = output.split_first_chunk_mut::<{ header::LEN }>().unwrap();
201        // Allow 64 symbols per block, each up to 16 Huffman bits and 16 coefficient bits.
202        // Byte stuffing can double the scan size, and EOI adds two bytes.
203        const MAX_BLOCK_BYTES: usize = 64 * (16 + 16) / 8 * 2;
204        let (mcu_width, mcu_height) = sampling.mcu_size();
205        let mcu_count =
206            width_usize.div_ceil(mcu_width as usize) * height_usize.div_ceil(mcu_height as usize);
207        let max_scan_length = mcu_count
208            .saturating_mul(sampling.blocks_per_mcu() * MAX_BLOCK_BYTES)
209            .saturating_add(2);
210        let capacity = payload
211            .len()
212            .min(max_scan_length)
213            .next_multiple_of(output_alignment);
214        let payload = &mut payload[..capacity];
215        header::write(header, width, height, &sampling, &luminance, chrominance);
216
217        const DMA_OWNED: u32 = 1 << 31;
218        const MODE_2D: u32 = 1 << 29;
219        const MULTIPLE_BLOCKS: u32 = 1 << 28;
220        // Use the visible dimensions for HA and VA so DMA2D pads partial macroblocks.
221        let mut tx = Descriptor([
222            DMA_OWNED | MODE_2D | (layout.dma_block_width << DMA_FIELD_BITS) | mcu_height,
223            (layout.dma_pbyte << 28) | (u32::from(width) << DMA_FIELD_BITS) | u32::from(height),
224            MULTIPLE_BLOCKS,
225            input.as_ptr() as u32,
226            0,
227            0,
228        ]);
229        let capacity = capacity as u32;
230        let mut rx = Descriptor([
231            DMA_OWNED | (capacity & DMA_FIELD_MASK),
232            capacity >> DMA_FIELD_BITS,
233            0,
234            payload.as_mut_ptr() as u32,
235            0,
236            0,
237        ]);
238
239        self.channels.reset();
240        let jpeg = JPEG::regs();
241        let color_space_bits = layout.color_space as u8;
242        #[cfg(esp32p4)]
243        let (color_space_bits, extd_select) = match layout.color_space {
244            format::ColorSpace::Ycbcr444 => (0, Some(false)),
245            format::ColorSpace::Ycbcr420 => (0, Some(true)),
246            _ => (color_space_bits, None),
247        };
248        jpeg.config().modify(|_, w| w.soft_rst().set_bit());
249        jpeg.config().modify(|_, w| unsafe {
250            w.soft_rst().clear_bit();
251            w.mode().clear_bit();
252            w.color_space().bits(color_space_bits);
253            w.sample_sel().bits(sampling.sample_sel);
254            w.pixel_rev().bit(layout.pixel_reverse);
255            w.tailer_en().set_bit();
256            w.ff_check_en().set_bit();
257            w.qnr_precision().clear_bit();
258            w.qnr_fifo_en().set_bit();
259            w.lqnr_tbl_sel().bits(0);
260            w.cqnr_tbl_sel().bits(1)
261        });
262        #[cfg(esp32p4)]
263        jpeg.extd_config().write(|w| {
264            w.extd_color_space_en().bit(extd_select.is_some());
265            w.extd_color_space().bit(extd_select.unwrap_or(false))
266        });
267        jpeg.pic_size().write(|w| unsafe {
268            w.ha().bits(width);
269            w.va().bits(height)
270        });
271        jpeg.int_clr().write(|w| unsafe { w.bits(u32::MAX) });
272
273        for &value in &luminance {
274            jpeg.t0qnr()
275                .write(|w| unsafe { w.t0_qnr_val().bits(u32::from(value)) });
276        }
277        if let Some(chrominance) = chrominance {
278            for &value in chrominance {
279                jpeg.t1qnr()
280                    .write(|w| unsafe { w.t1_qnr_val().bits(u32::from(value)) });
281            }
282        }
283
284        let dma = DMA2D::regs();
285        let (tx_channel, rx_channel) = self.channels.indices();
286        self.channels.connect(JPEG_TRIGGER);
287        if layout.dma_swap_bytes {
288            self.channels.swap_tx_pixel_bytes();
289        }
290        dma.out_conf0_ch(tx_channel).modify(|_, w| unsafe {
291            w.out_reorder_en_ch().set_bit();
292            w.out_mem_burst_length_ch().bits(BURST_128_BYTES);
293            w.out_page_bound_en_ch().set_bit();
294            w.out_macro_block_size_ch()
295                .bits(sampling.dma_macro_block_size);
296            w.outdscr_burst_en_ch().set_bit()
297        });
298        dma.in_conf0_ch(rx_channel).modify(|_, w| unsafe {
299            w.in_mem_burst_length_ch().bits(BURST_128_BYTES);
300            w.in_page_bound_en_ch().set_bit();
301            w.indscr_burst_en_ch().set_bit()
302        });
303
304        writeback(input);
305        writeback(payload);
306        writeback(core::slice::from_ref(&tx));
307        writeback(core::slice::from_ref(&rx));
308        // SAFETY: Reset left the channels idle. Cache writeback is complete, and the descriptors
309        // and buffers stay live until the channels stop.
310        unsafe {
311            self.channels
312                .start((&raw mut tx) as u32, (&raw mut rx) as u32)
313        };
314        jpeg.config().modify(|_, w| w.jpeg_start().set_bit());
315
316        let result = self.wait_for_completion();
317        self.channels.reset();
318        if result.is_err() {
319            PeripheralClockControl::reset(Peripheral::Jpeg);
320        }
321        // RX can write the payload and descriptor before reporting an error.
322        // SAFETY: The payload and RX descriptor each cover whole cache lines.
323        unsafe {
324            invalidate(payload);
325            invalidate(core::slice::from_ref(&rx));
326        }
327        result?;
328
329        compiler_fence(Ordering::SeqCst);
330        let word0 = unsafe { ptr::read_volatile(&raw const rx.0[0]) };
331        let word1 = unsafe { ptr::read_volatile(&raw const rx.0[1]) };
332        let length_low = (word0 >> DMA_FIELD_BITS) & DMA_FIELD_MASK;
333        let length_high = (word1 >> DMA_FIELD_BITS) & DMA_FIELD_MASK;
334        let length = length_low | (length_high << DMA_FIELD_BITS);
335        if length < 2 || length > capacity {
336            return Err(Error::Hardware);
337        }
338        Ok(header::LEN + length as usize)
339    }
340
341    fn wait_for_completion(&self) -> Result<(), Error> {
342        let dma = DMA2D::regs();
343        let (tx_channel, rx_channel) = self.channels.indices();
344        let timeout = self.timeout.map(|timeout| (Instant::now(), timeout));
345        loop {
346            let rx = dma.in_int_raw_ch(rx_channel).read();
347            let tx = dma.out_int_raw_ch(tx_channel).read();
348            let jpeg = JPEG::regs().int_raw().read();
349            if rx.in_dscr_err_ch_int_raw().bit()
350                || rx.in_err_eof_ch_int_raw().bit()
351                || tx.out_dscr_err_ch_int_raw().bit()
352                || tx.outfifo_ro_ovf_ch_int_raw().bit()
353                || tx.outfifo_ro_udf_ch_int_raw().bit()
354                || jpeg.rle_parallel_err().bit()
355                || jpeg.en_frame_eof_err().bit()
356                || encode_timeout(&jpeg)
357            {
358                return Err(Error::Hardware);
359            }
360            if rx.in_suc_eof_ch_int_raw().bit() {
361                return Ok(());
362            }
363            if rx.in_dscr_empty_ch_int_raw().bit() {
364                return Err(Error::OutputTooSmall);
365            }
366            if timeout.is_some_and(|(start, timeout)| start.elapsed() >= timeout) {
367                return Err(Error::Timeout);
368            }
369            core::hint::spin_loop();
370        }
371    }
372}
373
374cfg_select! {
375    esp32s31 => {
376        use crate::peripherals::HP_SYS;
377
378        /// Forces the JPEG memory on, and restores its low-power control when dropped.
379        #[derive(Debug)]
380        struct MemoryPower {
381            force_ctrl: bool,
382            low_power: bool,
383        }
384
385        impl MemoryPower {
386            fn force_on() -> Self {
387                let memory = HP_SYS::regs().jpeg_mem_lp_ctrl();
388                let previous = memory.read();
389                memory.modify(|_, w| {
390                    w.jpeg_mem_force_ctrl().set_bit();
391                    w.jpeg_mem_lp_en().clear_bit()
392                });
393                Self {
394                    force_ctrl: previous.jpeg_mem_force_ctrl().bit(),
395                    low_power: previous.jpeg_mem_lp_en().bit(),
396                }
397            }
398        }
399
400        impl Drop for MemoryPower {
401            fn drop(&mut self) {
402                HP_SYS::regs().jpeg_mem_lp_ctrl().modify(|_, w| {
403                    w.jpeg_mem_force_ctrl().bit(self.force_ctrl);
404                    w.jpeg_mem_lp_en().bit(self.low_power)
405                });
406            }
407        }
408
409        fn encode_timeout(status: &InterruptStatus) -> bool {
410            status.encode_timeout().bit()
411        }
412    }
413    _ => {
414        // The JPEG memory has no software low-power control.
415        #[derive(Debug)]
416        struct MemoryPower;
417
418        impl MemoryPower {
419            fn force_on() -> Self {
420                Self
421            }
422        }
423
424        // ESP32-P4 has no JPEG encode timeout interrupt.
425        fn encode_timeout(_status: &InterruptStatus) -> bool {
426            false
427        }
428    }
429}
430
431// RX writes back the descriptor. Keep it on its own cache line on a cached stack.
432#[cfg_attr(soc_internal_memory_cached, repr(C, align(128)))]
433#[cfg_attr(not(soc_internal_memory_cached), repr(C, align(64)))]
434struct Descriptor([u32; 6]);