1use core::{
4 marker::PhantomData,
5 pin::Pin,
6 sync::atomic,
7 task::{Context, Poll},
8};
9
10use esp_sync::NonReentrantMutex;
11
12use crate::{
13 asynch::AtomicWaker,
14 clock::CpuFrequencyLock,
15 dma::aligned::InternalMemory,
16 interrupt,
17 mipi_dsi::{
18 ConfigError,
19 MipiDsi,
20 vdma::{VdmaChannel, VdmaLinkItem},
21 },
22 peripherals::{Interrupt, MIPI_DSI_BRIDGE, MIPI_DSI_HOST, VDMA},
23 soc::clocks::{ClockTree, MipiDsiDpiClkConfig, MipiDsiInstance},
24 system::Cpu,
25};
26
27static VDMA_ISR_CHANNEL: atomic::AtomicU8 = atomic::AtomicU8::new(0);
33
34const MAX_FBS: usize = 3;
35const NUM_LLIS: usize = 2;
39const DMA_BURST_LEN: u32 = 256;
40const FIFO_EMPTY_THRESHOLD: u32 = 1024 - DMA_BURST_LEN;
41
42static LLI_STORAGE: NonReentrantMutex<InternalMemory<[VdmaLinkItem; NUM_LLIS]>> =
45 NonReentrantMutex::new(InternalMemory::new(
46 [const { VdmaLinkItem::zeroed() }; NUM_LLIS],
47 ));
48
49pub use crate::soc::clocks::MipiDsiDpiClkSclk as DpiClockSource;
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58#[cfg_attr(feature = "defmt", derive(defmt::Format))]
59pub enum ColorFormat {
60 Rgb888,
62 Rgb565,
64}
65
66impl ColorFormat {
67 pub(crate) fn bits_per_pixel(self) -> u32 {
68 match self {
69 Self::Rgb888 => 24,
70 Self::Rgb565 => 16,
71 }
72 }
73
74 fn raw_type(self) -> u8 {
75 match self {
76 Self::Rgb888 => 0,
77 Self::Rgb565 => 2,
78 }
79 }
80
81 fn dpi_type(self) -> u8 {
82 match self {
83 Self::Rgb888 => 0,
84 Self::Rgb565 => 2,
85 }
86 }
87
88 fn host_color_coding(self) -> u8 {
90 match self {
91 Self::Rgb888 => 5, Self::Rgb565 => 0, }
94 }
95}
96
97#[derive(Clone, Copy, Debug)]
99pub struct FrameTiming {
100 pub h_active: u32,
102 pub hsw: u32,
104 pub hbp: u32,
106 pub hfp: u32,
108 pub v_active: u32,
110 pub vsw: u32,
112 pub vbp: u32,
114 pub vfp: u32,
116}
117
118#[derive(Clone, Copy, Debug)]
120pub struct DpiConfig {
121 pub virtual_channel: u8,
123 pub pixel_clock_mhz: f32,
125 pub dpi_clk_src: DpiClockSource,
127 pub in_color_format: ColorFormat,
129 pub out_color_format: ColorFormat,
131 pub timing: FrameTiming,
133}
134
135#[crate::ram]
144#[crate::handler]
145fn vdma_block_done_isr() {
146 let channel_id = VDMA_ISR_CHANNEL.load(atomic::Ordering::Relaxed) as usize;
147 let ch = VDMA::regs().ch(channel_id);
148 ch.intclear0().write(|w| unsafe { w.bits(0xFFFFFFFF) });
149
150 LLI_STORAGE.with(|storage| {
151 let mut storage = storage.get_mut();
152 for lli in storage.iter() {
153 lli.rearm();
154 }
155
156 storage.writeback();
157 });
158}
159
160static VSYNC_WAKER: AtomicWaker = AtomicWaker::new();
163
164#[crate::handler]
165fn dsi_bridge_isr() {
166 let bridge = MIPI_DSI_BRIDGE::regs();
167 let st = bridge.int_st().read();
168 if st.vsync().bit_is_set() {
169 bridge.int_ena().modify(|_, w| w.vsync().clear_bit());
170 VSYNC_WAKER.wake();
171 }
172}
173
174pub struct DsiDpi<'d> {
181 _guard: crate::mipi_dsi::DphyGuard<'d>,
182 _cpu_frequency_lock: CpuFrequencyLock,
184 fb_ptrs: [*mut u8; MAX_FBS],
185 fb_size: usize,
186 num_fbs: usize,
187 current_fb: usize,
188 _phantom: PhantomData<&'d mut [u8]>,
189}
190
191impl Drop for DsiDpi<'_> {
192 fn drop(&mut self) {
193 let channel_id = self._guard.vdma_channel_id as usize;
195 let ch = VDMA::regs().ch(channel_id);
196 unsafe {
197 ch.intsignal_enable0().write_with_zero(|w| w);
198 ch.intstatus_enable0().write_with_zero(|w| w);
199 }
200 interrupt::disable(Cpu::current(), Interrupt::DMA);
201
202 let shift = channel_id as u32;
204 let val: u32 = 0x0100 << shift; unsafe { VDMA::regs().chen0().write(|w| w.bits(val)) };
206
207 MIPI_DSI_BRIDGE::regs()
208 .dpi_misc_config()
209 .modify(|_, w| w.dpi_en().clear_bit());
210 ClockTree::with(|clocks| MipiDsiInstance::MipiDsi.release_dpi_clk(clocks));
211 }
213}
214
215impl<'d> DsiDpi<'d> {
216 pub(crate) fn new(
217 bus: MipiDsi<'d>,
218 config: DpiConfig,
219 framebuffers: &[&'d mut [u8]],
220 ) -> Result<Self, ConfigError> {
221 let cpu_frequency_lock = CpuFrequencyLock::new();
222 let num_fbs = framebuffers.len();
223 debug_assert!((1..=MAX_FBS).contains(&num_fbs));
224 let fb_size = framebuffers[0].len();
225
226 let (_dpi_clk_config, real_dpi_mhz) = ClockTree::with(|clocks| {
231 let src_hz = MipiDsiInstance::dpi_clk_config_frequency(MipiDsiDpiClkConfig::new(
233 config.dpi_clk_src,
234 0,
235 ));
236 let src_mhz = src_hz as f32 / 1_000_000.0;
237 let div = ((src_mhz / config.pixel_clock_mhz) + 0.5) as u32;
238 let div = div.max(1);
239 let cfg = MipiDsiDpiClkConfig::new(config.dpi_clk_src, div - 1);
240 MipiDsiInstance::MipiDsi.configure_dpi_clk(clocks, cfg);
241 MipiDsiInstance::MipiDsi.request_dpi_clk(clocks);
242 (cfg, src_mhz / div as f32)
243 });
244
245 let host = MIPI_DSI_HOST::regs();
246 let bridge = MIPI_DSI_BRIDGE::regs();
247
248 host.dpi_vcid()
250 .modify(|_, w| unsafe { w.dpi_vcid().bits(config.virtual_channel) });
251 host.dpi_color_coding().modify(|_, w| unsafe {
252 w.dpi_color_coding()
253 .bits(config.out_color_format.host_color_coding())
254 });
255
256 host.dpi_cfg_pol().write(|w| unsafe { w.bits(0) });
258
259 host.vid_mode_cfg().modify(|_, w| unsafe {
265 w.vid_mode_type().bits(2); w.lp_vsa_en().set_bit();
267 w.lp_vbp_en().set_bit();
268 w.lp_vfp_en().set_bit();
269 w.lp_hbp_en().set_bit();
270 w.lp_hfp_en().set_bit();
271 w.lp_cmd_en().set_bit()
272 });
273
274 let t = &config.timing;
275 host.vid_pkt_size()
276 .modify(|_, w| unsafe { w.vid_pkt_size().bits(t.h_active as u16) });
277 host.vid_num_chunks()
278 .modify(|_, w| unsafe { w.vid_num_chunks().bits(0) });
279 host.vid_null_size()
280 .modify(|_, w| unsafe { w.vid_null_size().bits(0) });
281
282 let ratio = bus.lane_bit_rate_mbps / config.pixel_clock_mhz / 8.0;
284 let htotal = t.hsw + t.hbp + t.h_active + t.hfp;
285
286 let host_hsw = fround_u32(t.hsw as f32 * ratio);
287 let host_hbp = fround_u32(t.hbp as f32 * ratio);
288 let host_act = fround_u32(t.h_active as f32 * ratio);
289 let host_hfp = fround_u32(t.hfp as f32 * ratio);
290 let host_htotal = fround_u32(htotal as f32 * ratio);
291 let comp = host_htotal as i32 - (host_hsw + host_hbp + host_act + host_hfp) as i32;
292 let host_act = (host_act as i32 + comp).max(0) as u32;
293
294 host.vid_hsa_time()
295 .modify(|_, w| unsafe { w.vid_hsa_time().bits(host_hsw as u16) });
296 host.vid_hbp_time()
297 .modify(|_, w| unsafe { w.vid_hbp_time().bits(host_hbp as u16) });
298 host.vid_hline_time().modify(|_, w| unsafe {
299 w.vid_hline_time()
300 .bits((host_hsw + host_hbp + host_act + host_hfp) as u16)
301 });
302
303 host.vid_vsa_lines()
305 .modify(|_, w| unsafe { w.vsa_lines().bits(t.vsw as u16) });
306 host.vid_vbp_lines()
307 .modify(|_, w| unsafe { w.vbp_lines().bits(t.vbp as u16) });
308 host.vid_vactive_lines()
309 .modify(|_, w| unsafe { w.v_active_lines().bits(t.v_active as u16) });
310 host.vid_vfp_lines()
311 .modify(|_, w| unsafe { w.vfp_lines().bits(t.vfp as u16) });
312
313 let brg_hfp = {
315 let c = fround_u32(real_dpi_mhz / config.pixel_clock_mhz * htotal as f32) as i32
316 - htotal as i32;
317 (t.hfp as i32 + c).max(0) as u32
318 };
319 bridge.dpi_h_cfg0().modify(|_, w| unsafe {
320 w.htotal()
321 .bits((t.hsw + t.hbp + t.h_active + brg_hfp) as u16);
322 w.hdisp().bits(t.h_active as u16)
323 });
324 bridge.dpi_h_cfg1().modify(|_, w| unsafe {
325 w.hsync().bits(t.hsw as u16);
326 w.hbank().bits(t.hbp as u16)
327 });
328 bridge.dpi_v_cfg0().modify(|_, w| unsafe {
329 w.vtotal().bits((t.vsw + t.vbp + t.v_active + t.vfp) as u16);
330 w.vdisp().bits(t.v_active as u16)
331 });
332 bridge.dpi_v_cfg1().modify(|_, w| unsafe {
333 w.vsync().bits(t.vsw as u16);
334 w.vbank().bits(t.vbp as u16)
335 });
336
337 let total_bits = t.h_active * t.v_active * config.in_color_format.bits_per_pixel();
339 bridge.raw_num_cfg().modify(|_, w| unsafe {
340 w.raw_num_total().bits(total_bits.div_ceil(64));
341 w.unalign_64bit_en().bit(!total_bits.is_multiple_of(64));
342 w.raw_num_total_set().set_bit()
343 });
344 bridge
345 .dpi_misc_config()
346 .modify(|_, w| unsafe { w.fifo_underrun_discard_vcnt().bits(t.h_active as u16) });
347 bridge.pixel_type().modify(|_, w| unsafe {
348 w.raw_type().bits(config.in_color_format.raw_type());
349 w.dpi_type().bits(config.out_color_format.dpi_type());
350 w.data_in_type().clear_bit()
351 });
352 bridge.dma_flow_ctrl().modify(|_, w| unsafe {
353 w.dsi_dma_flow_controller().clear_bit();
354 w.dma_flow_multiblk_num().bits(1)
355 });
356 bridge
357 .dma_frame_interval()
358 .modify(|_, w| w.dma_multiblk_en().clear_bit());
359 bridge
360 .dma_req_cfg()
361 .modify(|_, w| unsafe { w.dma_burst_len().bits(DMA_BURST_LEN as u16) });
362 bridge.raw_buf_almost_empty_thrd().modify(|_, w| unsafe {
363 w.dsi_raw_buf_almost_empty_thrd()
364 .bits(FIFO_EMPTY_THRESHOLD as u16)
365 });
366
367 bridge.en().modify(|_, w| w.dsi_en().set_bit());
368 bridge
369 .dpi_config_update()
370 .write(|w| w.dpi_config_update().set_bit());
371
372 interrupt::bind_handler(Interrupt::DSI_BRIDGE, dsi_bridge_isr);
373
374 for fb in framebuffers.iter() {
376 unsafe {
377 crate::soc::cache_writeback_addr(fb.as_ptr() as u32, fb_size as u32);
378 }
379 }
380
381 let fb_ptrs = core::array::from_fn::<_, MAX_FBS, _>(|i| {
383 if i < num_fbs {
384 framebuffers[i].as_ptr().cast_mut()
385 } else {
386 core::ptr::null_mut::<u8>()
387 }
388 });
389
390 let vdma_channel_id = bus.guard.vdma_channel_id;
391 VDMA_ISR_CHANNEL.store(vdma_channel_id, atomic::Ordering::Relaxed);
392
393 LLI_STORAGE.with(|storage| {
394 let mut storage = storage.get_mut();
395 for i in 0..NUM_LLIS {
396 let next = &raw const storage[(i + 1) % NUM_LLIS];
397 storage[i].configure(fb_ptrs[0] as u32, fb_size, next);
398 }
399
400 storage.writeback();
402
403 VdmaChannel::new(vdma_channel_id).start(&storage[0]);
404 });
405
406 {
410 let ch = VDMA::regs().ch(vdma_channel_id as usize);
411 ch.intstatus_enable0()
412 .write(|w| w.ch1_enable_block_tfr_done_intstat().set_bit());
413 ch.intsignal_enable0()
414 .write(|w| w.ch1_enable_block_tfr_done_intsignal().set_bit());
415 }
416 interrupt::bind_handler(Interrupt::DMA, vdma_block_done_isr);
417
418 host.mode_cfg()
420 .modify(|_, w| w.cmd_video_mode().clear_bit());
421 bridge.dpi_misc_config().modify(|_, w| w.dpi_en().set_bit());
422 bridge
423 .dpi_config_update()
424 .write(|w| w.dpi_config_update().set_bit());
425
426 let MipiDsi { guard, .. } = bus;
427 Ok(Self {
428 _guard: guard,
429 _cpu_frequency_lock: cpu_frequency_lock,
430 fb_ptrs,
431 fb_size,
432 num_fbs,
433 current_fb: 0,
434 _phantom: PhantomData,
435 })
436 }
437
438 pub fn framebuffer_mut(&mut self) -> &mut [u8] {
443 let back = (self.current_fb + 1) % self.num_fbs;
444 unsafe { core::slice::from_raw_parts_mut(self.fb_ptrs[back], self.fb_size) }
445 }
446
447 pub fn commit(&mut self) {
457 let back = (self.current_fb + 1) % self.num_fbs;
458
459 unsafe {
461 crate::soc::cache_writeback_addr(self.fb_ptrs[back] as u32, self.fb_size as u32);
462 }
463
464 let src = self.fb_ptrs[back] as u32;
468 LLI_STORAGE.with(|storage| {
469 let storage = storage.get_mut();
470 for lli in storage.iter() {
471 lli.set_source(src);
472 }
473 });
474
475 self.current_fb = back;
478 }
479
480 pub fn wait_for_vsync(&mut self) {
486 let bridge = MIPI_DSI_BRIDGE::regs();
487 while !bridge.int_raw().read().vsync().bit_is_set() {}
488 bridge.int_clr().write(|w| w.vsync().clear_bit_by_one());
489 }
490
491 pub fn wait_for_vsync_async(&mut self) -> impl Future<Output = ()> {
493 VsyncFuture { _dpi: self }
494 }
495}
496
497#[must_use = "futures do nothing unless you `.await` or poll them"]
498struct VsyncFuture<'a, 'b> {
499 _dpi: &'a mut DsiDpi<'b>,
500}
501
502impl Future for VsyncFuture<'_, '_> {
503 type Output = ();
504
505 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
506 let bridge = MIPI_DSI_BRIDGE::regs();
507 if bridge.int_raw().read().vsync().bit_is_set() {
508 bridge.int_clr().write(|w| w.vsync().clear_bit_by_one());
509 Poll::Ready(())
510 } else {
511 VSYNC_WAKER.register(cx.waker());
512 bridge.int_ena().modify(|_, w| w.vsync().set_bit());
513 Poll::Pending
514 }
515 }
516}
517
518impl Drop for VsyncFuture<'_, '_> {
519 fn drop(&mut self) {
520 let bridge = MIPI_DSI_BRIDGE::regs();
521 bridge.int_ena().modify(|_, w| w.vsync().clear_bit());
522 }
523}
524
525#[inline]
528fn fround_u32(x: f32) -> u32 {
529 (x + 0.5) as u32
530}