1mod 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#[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 InvalidInput,
50 InvalidBuffer,
52 UnsupportedFormat,
54 OutputTooSmall,
56 Timeout,
58 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79#[cfg_attr(feature = "defmt", derive(defmt::Format))]
80#[instability::unstable]
81pub struct EncodeConfig {
82 pub width: u16,
84 pub height: u16,
86 pub quality: u8,
88 pub input_format: PixelFormat,
90 pub subsampling: Subsampling,
92}
93
94#[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 #[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 #[instability::unstable]
127 pub fn set_timeout(&mut self, timeout: Option<Duration>) {
128 self.timeout = timeout;
129 }
130
131 #[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 #[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 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 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 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 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 #[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 #[derive(Debug)]
416 struct MemoryPower;
417
418 impl MemoryPower {
419 fn force_on() -> Self {
420 Self
421 }
422 }
423
424 fn encode_timeout(_status: &InterruptStatus) -> bool {
426 false
427 }
428 }
429}
430
431#[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]);