1 /*
2  * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "hal/lcd_hal.h"
8 #include "hal/lcd_ll.h"
9 #include "hal/log.h"
10 
lcd_hal_init(lcd_hal_context_t * hal,int id)11 void lcd_hal_init(lcd_hal_context_t *hal, int id)
12 {
13     hal->dev = LCD_LL_GET_HW(id);
14 }
15 
16 /**
17  * @brief helper function, calculate the Greatest Common Divisor
18  * @note gcd(a, b) = gcd(b, a % b)
19  * @param a bigger value
20  * @param b smaller value
21  * @return result of gcd(a, b)
22  */
23 __attribute__((always_inline))
_gcd(uint32_t a,uint32_t b)24 static inline uint32_t _gcd(uint32_t a, uint32_t b)
25 {
26     uint32_t c = a % b;
27     while (c != 0) {
28         a = b;
29         b = c;
30         c = a % b;
31     }
32     return b;
33 }
34 
lcd_hal_cal_pclk_freq(lcd_hal_context_t * hal,uint32_t src_freq_hz,uint32_t expect_pclk_freq_hz,int lcd_clk_flags)35 uint32_t lcd_hal_cal_pclk_freq(lcd_hal_context_t *hal, uint32_t src_freq_hz, uint32_t expect_pclk_freq_hz, int lcd_clk_flags)
36 {
37     // lcd_clk = module_clock_src / (n + b / a)
38     // pixel_clk = lcd_clk / mo
39     uint32_t mo = src_freq_hz / expect_pclk_freq_hz / LCD_LL_CLK_FRAC_DIV_N_MAX + 1;
40     if (mo == 1 && !(lcd_clk_flags & LCD_HAL_PCLK_FLAG_ALLOW_EQUAL_SYSCLK)) {
41         mo = 2;
42     }
43     uint32_t n = src_freq_hz / expect_pclk_freq_hz / mo;
44     uint32_t a = 0;
45     uint32_t b = 0;
46     // delta_hz / expect_pclk_freq_hz <==> b / a
47     uint32_t delta_hz = src_freq_hz / mo - expect_pclk_freq_hz * n;
48     // fractional divider
49     if (delta_hz) {
50         uint32_t gcd = _gcd(expect_pclk_freq_hz, delta_hz);
51         a = expect_pclk_freq_hz / gcd;
52         b = delta_hz / gcd;
53         // normalize div_a and div_b
54         uint32_t d = a / LCD_LL_CLK_FRAC_DIV_AB_MAX + 1;
55         a /= d;
56         b /= d;
57     }
58 
59     HAL_EARLY_LOGD("lcd_hal", "n=%d,a=%d,b=%d,mo=%d", n, a, b, mo);
60 
61     lcd_ll_set_group_clock_coeff(hal->dev, n, a, b);
62     lcd_ll_set_pixel_clock_prescale(hal->dev, mo);
63 
64     if (delta_hz) {
65         return ((uint64_t)src_freq_hz * a) / (n * a + b) / mo;
66     } else {
67         return src_freq_hz / n / mo;
68     }
69 }
70