1 /**
2   ******************************************************************************
3   * @file    stm32u5xx_hal_jpeg.c
4   * @author  MCD Application Team
5   * @brief   JPEG HAL module driver.
6   *          This file provides firmware functions to manage the following
7   *          functionalities of the JPEG encoder/decoder peripheral:
8   *           + Initialization and de-initialization functions
9   *           + JPEG processing functions encoding and decoding
10   *           + JPEG decoding Getting Info and encoding configuration setting
11   *           + JPEG enable/disable header parsing functions (for decoding)
12   *           + JPEG Input/Output Buffer configuration.
13   *           + JPEG callback functions
14   *           + JPEG Abort/Pause/Resume functions
15   *           + JPEG custom quantization tables setting functions
16   *           + IRQ handler management
17   *           + Peripheral State and Error functions
18   *
19   ******************************************************************************
20   * @attention
21   *
22   * Copyright (c) 2021 STMicroelectronics.
23   * All rights reserved.
24   *
25   * This software is licensed under terms that can be found in the LICENSE file
26   * in the root directory of this software component.
27   * If no LICENSE file comes with this software, it is provided AS-IS.
28   *
29   ******************************************************************************
30   @verbatim
31   ==============================================================================
32                      ##### How to use this driver #####
33   ==============================================================================
34     [..]
35      (#) Initialize the JPEG peripheral using HAL_JPEG_Init : No initialization parameters are required.
36          Only the call to HAL_JPEG_Init is necessary to initialize the JPEG peripheral.
37 
38      (#) If operation is JPEG encoding use function HAL_JPEG_ConfigEncoding to set
39          the encoding parameters (mandatory before calling the encoding function).
40          the application can change the encoding parameter ImageQuality from
41          1 to 100 to obtain a more or less quality (visual quality vs the original row image),
42          and inversely more or less jpg file size.
43 
44      (#) Note that for decoding operation the JPEG peripheral output data are organized in
45          YCbCr blocks called MCU (Minimum Coded Unit) as defioned in the JPEG specification
46          ISO/IEC 10918-1 standard.
47          It is up to the application to transform these YCbCr blocks to RGB data that can be display.
48 
49          Respectively, for Encoding operation the JPEG peripheral input should be organized
50          in YCbCr MCU blocks. It is up to the application to perform the necessary RGB to YCbCr
51          MCU blocks transformation before feeding the JPEG peripheral with data.
52 
53      (#) Use functions HAL_JPEG_Encode and HAL_JPEG_Decode to start respectively
54          a JPEG encoding/decoding operation in polling method (blocking).
55 
56      (#) Use functions HAL_JPEG_Encode_IT and HAL_JPEG_Decode_IT to start respectively
57          a JPEG encoding/decoding operation with Interrupt method (not blocking).
58 
59      (#) Use functions HAL_JPEG_Encode_DMA and HAL_JPEG_Decode_DMA to start respectively
60          a JPEG encoding/decoding operation with DMA method (not blocking).
61 
62      (#) Callback HAL_JPEG_InfoReadyCallback is asserted if the current operation
63          is a JPEG decoding to provide the application with JPEG image  parameters.
64          This callback is asserted when the JPEG peripheral successfully parse the
65          JPEG header.
66 
67      (#) Callback HAL_JPEG_GetDataCallback is asserted for both encoding and decoding
68          operations to inform the application that the input buffer has been
69          consumed by the peripheral and to ask for a new data chunk if the operation
70          (encoding/decoding) has not been complete yet.
71 
72         (++) This CallBack should be implemented in the application side. It should
73              call the function HAL_JPEG_ConfigInputBuffer if new input data are available,
74              or call HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_INPUT
75              to inform the JPEG HAL driver that the ongoing operation shall pause waiting for the
76              application to provide a new input data chunk.
77              Once the application succeed getting new data and if the input has been paused,
78              the application can call the function HAL_JPEG_ConfigInputBuffer to set the new
79              input buffer and size, then resume the JPEG HAL input by calling new function HAL_JPEG_Resume.
80              If the application has ended feeding the HAL JPEG with input data (no more input data), the application
81              Should call the function HAL_JPEG_ConfigInputBuffer (within the callback HAL_JPEG_GetDataCallback)
82              with the parameter InDataLength set to zero.
83 
84          (++) The mechanism of HAL_JPEG_ConfigInputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows
85               to the application to provide the input data (for encoding or decoding) by chunks.
86               If the new input data chunk is not available (because data should be read from an input file
87               for example) the application can pause the JPEG input (using function HAL_JPEG_Pause)
88               Once the new input data chunk is available ( read from a file for example), the application
89               can call the function HAL_JPEG_ConfigInputBuffer to provide the HAL with the new chunk
90               then resume the JPEG HAL input by calling function HAL_JPEG_Resume.
91 
92          (++) The application can call functions HAL_JPEG_ConfigInputBuffer then HAL_JPEG_Resume.
93               any time (outside the HAL_JPEG_GetDataCallback)  Once the new input chunk data available.
94               However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called
95               (if necessary) within the callback HAL_JPEG_GetDataCallback, i.e when the HAL JPEG has ended
96               Transferring the previous chunk buffer to the JPEG peripheral.
97 
98      (#) Callback HAL_JPEG_DataReadyCallback is asserted when the HAL JPEG driver
99          has filled the given output buffer with the given size.
100 
101          (++) This CallBack should be implemented in the application side. It should
102               call the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver
103               with the new output buffer location and size to be used  to store next data chunk.
104               if the application is not ready to provide the output chunk location then it can
105               call the function HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_OUTPUT
106               to inform the JPEG HAL driver that it shall pause output data. Once the application
107               is ready to receive the new data chunk (output buffer location free or available) it should call
108               the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver
109               with the new output chunk buffer location and size, then call HAL_JPEG_Resume
110               to inform the HAL that it shall resume outputting data in the given output buffer.
111 
112          (++) The mechanism of HAL_JPEG_ConfigOutputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows
113               the application to receive data from the JPEG peripheral by chunks. when a chunk
114               is received, the application can pause the HAL JPEG output data to be able to process
115               these received data (YCbCr to RGB conversion in case of decoding or data storage in case
116               of encoding).
117 
118          (++) The application can call  functions HAL_JPEG_ ConfigOutputBuffer then HAL_JPEG_Resume.
119               any time (outside the HAL_JPEG_DataReadyCallback) Once the output data buffer is free to use.
120               However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called
121               (if necessary) within the callback HAL_JPEG_ DataReadyCallback, i.e when the HAL JPEG has ended
122               Transferring the previous chunk buffer from the JPEG peripheral to the application.
123 
124      (#) Callback HAL_JPEG_EncodeCpltCallback is asserted when the HAL JPEG driver has
125          ended the current JPEG encoding operation, and all output data has been transmitted
126          to the application.
127 
128      (#) Callback HAL_JPEG_DecodeCpltCallback is asserted when the HAL JPEG driver has
129          ended the current JPEG decoding operation. and all output data has been transmitted
130          to the application.
131 
132      (#) Callback HAL_JPEG_ErrorCallback is asserted when an error occurred during
133          the current operation. the application can call the function HAL_JPEG_GetError()
134          to retrieve the error codes.
135 
136      (#) By default the HAL JPEG driver uses the default quantization tables
137          as provide in the JPEG specification (ISO/IEC 10918-1 standard) for encoding.
138          User can change these default tables if necessary using the function HAL_JPEG_SetUserQuantTables
139          Note that for decoding the quantization tables are automatically extracted from
140          the JPEG header.
141 
142       (#) To control JPEG state you can use the following function: HAL_JPEG_GetState()
143 
144      *** JPEG HAL driver macros list ***
145      =============================================
146      [..]
147        Below the list of most used macros in JPEG HAL driver.
148 
149       (+) __HAL_JPEG_RESET_HANDLE_STATE : Reset JPEG handle state.
150       (+) __HAL_JPEG_ENABLE             : Enable the JPEG peripheral.
151       (+) __HAL_JPEG_DISABLE            : Disable the JPEG peripheral.
152       (+) __HAL_JPEG_GET_FLAG           : Check the specified JPEG status flag.
153       (+) __HAL_JPEG_CLEAR_FLAG         : Clear the specified JPEG status flag.
154       (+) __HAL_JPEG_ENABLE_IT          : Enable the specified JPEG Interrupt.
155       (+) __HAL_JPEG_DISABLE_IT         : Disable the specified JPEG Interrupt.
156       (+) __HAL_JPEG_GET_IT_SOURCE      : returns the state of the specified JPEG Interrupt (Enabled or disabled).
157 
158   *** Callback registration ***
159   =============================================
160 
161   The compilation define  USE_HAL_JPEG_REGISTER_CALLBACKS when set to 1
162   allows the user to configure dynamically the driver callbacks.
163   Use Functions HAL_JPEG_RegisterCallback() or HAL_JPEG_RegisterXXXCallback()
164   to register an interrupt callback.
165 
166   Function HAL_JPEG_RegisterCallback() allows to register following callbacks:
167     (+) EncodeCpltCallback : callback for end of encoding operation.
168     (+) DecodeCpltCallback : callback for end of decoding operation.
169     (+) ErrorCallback      : callback for error detection.
170     (+) MspInitCallback    : JPEG MspInit.
171     (+) MspDeInitCallback  : JPEG MspDeInit.
172   This function takes as parameters the HAL peripheral handle, the Callback ID
173   and a pointer to the user callback function.
174 
175   For specific callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated
176   register callbacks : respectively HAL_JPEG_RegisterInfoReadyCallback(),
177   HAL_JPEG_RegisterGetDataCallback() and HAL_JPEG_RegisterDataReadyCallback().
178 
179   Use function HAL_JPEG_UnRegisterCallback() to reset a callback to the default
180   weak function.
181   HAL_JPEG_UnRegisterCallback() takes as parameters the HAL peripheral handle,
182   and the Callback ID.
183   This function allows to reset following callbacks:
184     (+) EncodeCpltCallback : callback for end of encoding operation.
185     (+) DecodeCpltCallback : callback for end of decoding operation.
186     (+) ErrorCallback      : callback for error detection.
187     (+) MspInitCallback    : JPEG MspInit.
188     (+) MspDeInitCallback  : JPEG MspDeInit.
189 
190   For callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated
191   unregister callbacks : respectively HAL_JPEG_UnRegisterInfoReadyCallback(),
192   HAL_JPEG_UnRegisterGetDataCallback() and HAL_JPEG_UnRegisterDataReadyCallback().
193 
194   By default, after the HAL_JPEG_Init() and when the state is HAL_JPEG_STATE_RESET
195   all callbacks are set to the corresponding weak functions :
196   examples HAL_JPEG_DecodeCpltCallback() , HAL_JPEG_GetDataCallback().
197   Exception done for MspInit and MspDeInit functions that are
198   reset to the legacy weak function in the HAL_JPEG_Init()/ HAL_JPEG_DeInit() only when
199   these callbacks are null (not registered beforehand).
200   if not, MspInit or MspDeInit are not null, the HAL_JPEG_Init() / HAL_JPEG_DeInit()
201   keep and use the user MspInit/MspDeInit functions (registered beforehand)
202 
203   Callbacks can be registered/unregistered in HAL_JPEG_STATE_READY state only.
204   Exception done MspInit/MspDeInit callbacks that can be registered/unregistered
205   in HAL_JPEG_STATE_READY or HAL_JPEG_STATE_RESET state,
206   thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
207   In that case first register the MspInit/MspDeInit user callbacks
208   using HAL_JPEG_RegisterCallback() before calling HAL_JPEG_DeInit()
209   or HAL_JPEG_Init() function.
210 
211   When The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS is set to 0 or
212   not defined, the callback registration feature is not available and all callbacks
213   are set to the corresponding weak functions.
214 
215   @endverbatim
216   ******************************************************************************
217   */
218 
219 /* Includes ------------------------------------------------------------------*/
220 #include "stm32u5xx_hal.h"
221 
222 /** @addtogroup STM32U5xx_HAL_Driver
223   * @{
224   */
225 
226 #ifdef HAL_JPEG_MODULE_ENABLED
227 
228 #if defined (JPEG)
229 
230 /** @defgroup JPEG JPEG
231   * @brief JPEG HAL module driver.
232   * @{
233   */
234 
235 /* Private define ------------------------------------------------------------*/
236 /** @addtogroup JPEG_Private_Constants
237   * @{
238   */
239 #define JPEG_TIMEOUT_VALUE  ((uint32_t)1000)     /* 1s */
240 #define JPEG_AC_HUFF_TABLE_SIZE  ((uint32_t)162) /* Huffman AC table size : 162 codes*/
241 #define JPEG_DC_HUFF_TABLE_SIZE  ((uint32_t)12)  /* Huffman DC table size : 12 codes*/
242 
243 #define JPEG_QUANTVAL_MAX ((uint32_t)255)           /* Quantization values are 8-bit numbers*/
244 #define JPEG_LOW_QUALITY_REFERENCE ((uint32_t)5000) /*Reference value to generate scaling factor
245                                                       for low quality factors (<50) */
246 #define JPEG_HIGH_QUALITY_REFERENCE ((uint32_t)200) /*Reference value to generate scaling factor
247                                                       for high quality factors (>=50)*/
248 
249 #define JPEG_FIFO_SIZE ((uint32_t)16U)              /* JPEG Input/Output HW FIFO size in words*/
250 
251 #define JPEG_FIFO_TH_SIZE ((uint32_t)4U)            /* JPEG Input/Output HW FIFO Threshold in words*/
252 
253 #define JPEG_DMA_MASK     ((uint32_t)0x00001800)     /* JPEG DMA request Mask*/
254 #define JPEG_DMA_IDMA     ((uint32_t)JPEG_CR_IDMAEN)  /* DMA request for the input FIFO */
255 #define JPEG_DMA_ODMA     ((uint32_t)JPEG_CR_ODMAEN)  /* DMA request for the output FIFO */
256 
257 #define JPEG_INTERRUPT_MASK  ((uint32_t)0x0000007EU) /* JPEG Interrupt Mask*/
258 
259 #define JPEG_CONTEXT_ENCODE          ((uint32_t)0x00000001) /* JPEG context : operation is encoding*/
260 #define JPEG_CONTEXT_DECODE          ((uint32_t)0x00000002) /* JPEG context : operation is decoding*/
261 #define JPEG_CONTEXT_OPERATION_MASK  ((uint32_t)0x00000003) /* JPEG context : operation Mask */
262 
263 #define JPEG_CONTEXT_POLLING        ((uint32_t)0x00000004)  /* JPEG context : Transfer use Polling */
264 #define JPEG_CONTEXT_IT             ((uint32_t)0x00000008)  /* JPEG context : Transfer use Interrupt */
265 #define JPEG_CONTEXT_DMA            ((uint32_t)0x0000000C)  /* JPEG context : Transfer use DMA */
266 #define JPEG_CONTEXT_METHOD_MASK    ((uint32_t)0x0000000C)  /* JPEG context : Transfer Mask */
267 
268 
269 #define JPEG_CONTEXT_CONF_ENCODING  ((uint32_t)0x00000100)  /* JPEG context : encoding config done */
270 
271 #define JPEG_CONTEXT_PAUSE_INPUT    ((uint32_t)0x00001000)  /* JPEG context : Pause Input */
272 #define JPEG_CONTEXT_PAUSE_OUTPUT   ((uint32_t)0x00002000)  /* JPEG context : Pause Output */
273 
274 #define JPEG_CONTEXT_CUSTOM_TABLES  ((uint32_t)0x00004000)  /* JPEG context : Use custom quantization tables */
275 
276 #define JPEG_CONTEXT_ENDING_DMA     ((uint32_t)0x00008000)  /* JPEG context : ending with DMA in progress */
277 
278 #define JPEG_PROCESS_ONGOING        ((uint32_t)0x00000000)  /* Process is on going */
279 #define JPEG_PROCESS_DONE           ((uint32_t)0x00000001)  /* Process is done (ends) */
280 #define JPEG_GET_DMA_REMAIN_DATA(__HANDLE__)     (__HAL_DMA_GET_COUNTER(__HANDLE__)\
281                                                   + HAL_DMAEx_GetFifoLevel(__HANDLE__))
282 /**
283   * @}
284   */
285 
286 /* Private typedef -----------------------------------------------------------*/
287 /** @addtogroup JPEG_Private_Types
288   * @{
289   */
290 
291 /*
292  JPEG Huffman Table Structure definition :
293  This implementation of Huffman table structure is compliant with ISO/IEC 10918-1 standard,
294  Annex C Huffman Table specification
295  */
296 typedef struct
297 {
298   /* These two fields directly represent the contents of a JPEG DHT marker */
299   uint8_t Bits[16];        /*!< bits[k] = # of symbols with codes of length k bits,
300                              this parameter corresponds to BITS list in the Annex C */
301 
302   uint8_t HuffVal[162];    /*!< The symbols, in order of incremented code length,
303                              this parameter corresponds to HUFFVAL list in the Annex C */
304 
305 
306 } JPEG_ACHuffTableTypeDef;
307 
308 typedef struct
309 {
310   /* These two fields directly represent the contents of a JPEG DHT marker */
311   uint8_t Bits[16];        /*!< bits[k] = # of symbols with codes of length k bits,
312                              this parameter corresponds to BITS list in the Annex C */
313 
314   uint8_t HuffVal[12];    /*!< The symbols, in order of incremented code length,
315                             this parameter corresponds to HUFFVAL list in the Annex C */
316 
317 
318 } JPEG_DCHuffTableTypeDef;
319 
320 typedef struct
321 {
322   uint8_t CodeLength[JPEG_AC_HUFF_TABLE_SIZE];      /*!< Code length  */
323 
324   uint32_t HuffmanCode[JPEG_AC_HUFF_TABLE_SIZE];    /*!< HuffmanCode */
325 
326 } JPEG_AC_HuffCodeTableTypeDef;
327 
328 typedef struct
329 {
330   uint8_t CodeLength[JPEG_DC_HUFF_TABLE_SIZE];        /*!< Code length  */
331 
332   uint32_t HuffmanCode[JPEG_DC_HUFF_TABLE_SIZE];    /*!< HuffmanCode */
333 
334 } JPEG_DC_HuffCodeTableTypeDef;
335 /**
336   * @}
337   */
338 
339 /* Private macro -------------------------------------------------------------*/
340 /** @addtogroup JPEG_Private_Macros
341   * @{
342   */
343 #define JPEG_ENABLE_DMA(__HANDLE__,__DMA__)  ((__HANDLE__)->Instance->CR |= ((__DMA__) & JPEG_DMA_MASK))
344 /*note  : To disable a DMA request we must use MODIFY_REG macro to avoid writing "1" to the FIFO flush bits
345          located in the same DMA request enable register (CR register). */
346 #define JPEG_DISABLE_DMA(__HANDLE__,__DMA__) MODIFY_REG((__HANDLE__)->Instance->CR, ((__DMA__) & JPEG_DMA_MASK), 0UL)
347 /**
348   * @}
349   */
350 
351 /* Private variables ---------------------------------------------------------*/
352 /** @addtogroup JPEG_Private_Variables
353   * @{
354   */
355 
356 static const JPEG_DCHuffTableTypeDef JPEG_DCLUM_HuffTable =
357 {
358   { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 },   /*Bits*/
359 
360   { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb }           /*HUFFVAL */
361 
362 };
363 
364 static const JPEG_DCHuffTableTypeDef JPEG_DCCHROM_HuffTable =
365 {
366   { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 },  /*Bits*/
367 
368   { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb }          /*HUFFVAL */
369 };
370 
371 static const JPEG_ACHuffTableTypeDef JPEG_ACLUM_HuffTable =
372 {
373   { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d },  /*Bits*/
374 
375   {
376     0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,     /*HUFFVAL */
377     0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
378     0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
379     0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
380     0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
381     0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
382     0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
383     0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
384     0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
385     0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
386     0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
387     0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
388     0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
389     0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
390     0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
391     0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
392     0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
393     0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
394     0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
395     0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
396     0xf9, 0xfa
397   }
398 };
399 
400 static const JPEG_ACHuffTableTypeDef JPEG_ACCHROM_HuffTable =
401 {
402   { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 },   /*Bits*/
403 
404   {
405     0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,      /*HUFFVAL */
406     0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
407     0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
408     0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
409     0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
410     0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
411     0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
412     0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
413     0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
414     0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
415     0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
416     0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
417     0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
418     0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
419     0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
420     0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
421     0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
422     0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
423     0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
424     0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
425     0xf9, 0xfa
426   }
427 };
428 
429 static const uint8_t JPEG_ZIGZAG_ORDER[JPEG_QUANT_TABLE_SIZE] =
430 {
431   0,   1,   8,  16,   9,   2,   3,  10,
432   17,  24,  32,  25,  18,  11,   4,   5,
433   12,  19,  26,  33,  40,  48,  41,  34,
434   27,  20,  13,   6,   7,  14,  21,  28,
435   35,  42,  49,  56,  57,  50,  43,  36,
436   29,  22,  15,  23,  30,  37,  44,  51,
437   58,  59,  52,  45,  38,  31,  39,  46,
438   53,  60,  61,  54,  47,  55,  62,  63
439 };
440 /**
441   * @}
442   */
443 
444 /* Private function prototypes -----------------------------------------------*/
445 /** @addtogroup JPEG_Private_Functions_Prototypes
446   * @{
447   */
448 
449 static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode,
450                                                 uint32_t *LastK);
451 static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable,
452                                                            JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable);
453 static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable,
454                                                            JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable);
455 static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC,
456                                              const __IO uint32_t *DCTableAddress);
457 static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC,
458                                              const __IO uint32_t *ACTableAddress);
459 static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg);
460 static void JPEG_Set_Huff_DHTMem(JPEG_HandleTypeDef *hjpeg);
461 static uint32_t  JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable,
462                                            __IO uint32_t *QTableAddress);
463 static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg);
464 static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg);
465 static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg);
466 
467 static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg);
468 static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg);
469 static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords);
470 static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords);
471 static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg);
472 
473 static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg);
474 static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg);
475 static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg);
476 static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg);
477 static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma);
478 static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma);
479 static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma);
480 static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma)  ;
481 
482 /**
483   * @}
484   */
485 
486 /** @defgroup JPEG_Exported_Functions JPEG Exported Functions
487   * @{
488   */
489 
490 /** @defgroup JPEG_Exported_Functions_Group1 Initialization and de-initialization functions
491   *  @brief    Initialization and de-initialization functions.
492   *
493 @verbatim
494   ==============================================================================
495               ##### Initialization and de-initialization functions #####
496   ==============================================================================
497     [..]  This section provides functions allowing to:
498       (+) Initialize the JPEG peripheral and creates the associated handle
499       (+) DeInitialize the JPEG peripheral
500 
501 @endverbatim
502   * @{
503   */
504 
505 /**
506   * @brief  Initializes the JPEG according to the specified
507   *         parameters in the JPEG_InitTypeDef and creates the associated handle.
508   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
509   *         the configuration information for JPEG module
510   * @retval HAL status
511   */
HAL_JPEG_Init(JPEG_HandleTypeDef * hjpeg)512 HAL_StatusTypeDef HAL_JPEG_Init(JPEG_HandleTypeDef *hjpeg)
513 {
514   /* These are the sample quantization tables given in JPEG spec ISO/IEC 10918-1 standard , section K.1. */
515   static const uint8_t JPEG_LUM_QuantTable[JPEG_QUANT_TABLE_SIZE] =
516   {
517     16,  11,  10,  16,  24,  40,  51,  61,
518     12,  12,  14,  19,  26,  58,  60,  55,
519     14,  13,  16,  24,  40,  57,  69,  56,
520     14,  17,  22,  29,  51,  87,  80,  62,
521     18,  22,  37,  56,  68, 109, 103,  77,
522     24,  35,  55,  64,  81, 104, 113,  92,
523     49,  64,  78,  87, 103, 121, 120, 101,
524     72,  92,  95,  98, 112, 100, 103,  99
525   };
526   static const uint8_t JPEG_CHROM_QuantTable[JPEG_QUANT_TABLE_SIZE] =
527   {
528     17,  18,  24,  47,  99,  99,  99,  99,
529     18,  21,  26,  66,  99,  99,  99,  99,
530     24,  26,  56,  99,  99,  99,  99,  99,
531     47,  66,  99,  99,  99,  99,  99,  99,
532     99,  99,  99,  99,  99,  99,  99,  99,
533     99,  99,  99,  99,  99,  99,  99,  99,
534     99,  99,  99,  99,  99,  99,  99,  99,
535     99,  99,  99,  99,  99,  99,  99,  99
536   };
537 
538   /* Check the JPEG handle allocation */
539   if (hjpeg == NULL)
540   {
541     return HAL_ERROR;
542   }
543 
544 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
545   if (hjpeg->State == HAL_JPEG_STATE_RESET)
546   {
547     /* Allocate lock resource and initialize it */
548     hjpeg->Lock = HAL_UNLOCKED;
549 
550     hjpeg->InfoReadyCallback  = HAL_JPEG_InfoReadyCallback;  /* Legacy weak InfoReadyCallback  */
551     hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */
552     hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */
553     hjpeg->ErrorCallback      = HAL_JPEG_ErrorCallback;      /* Legacy weak ErrorCallback      */
554     hjpeg->GetDataCallback    = HAL_JPEG_GetDataCallback;    /* Legacy weak GetDataCallback    */
555     hjpeg->DataReadyCallback  = HAL_JPEG_DataReadyCallback;  /* Legacy weak DataReadyCallback  */
556 
557     if (hjpeg->MspInitCallback == NULL)
558     {
559       hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit  */
560     }
561 
562     /* Init the low level hardware */
563     hjpeg->MspInitCallback(hjpeg);
564   }
565 #else
566   if (hjpeg->State == HAL_JPEG_STATE_RESET)
567   {
568     /* Allocate lock resource and initialize it */
569     hjpeg->Lock = HAL_UNLOCKED;
570 
571     /* Init the low level hardware : GPIO, CLOCK */
572     HAL_JPEG_MspInit(hjpeg);
573   }
574 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
575 
576   /* Change the JPEG state */
577   hjpeg->State = HAL_JPEG_STATE_BUSY;
578 
579   /* Start the JPEG Core*/
580   __HAL_JPEG_ENABLE(hjpeg);
581 
582   /* Stop the JPEG encoding/decoding process*/
583   hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
584 
585   /* Disable All Interrupts */
586   __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
587 
588   /* Disable All DMA requests */
589   JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK);
590 
591   /* Flush input and output FIFOs*/
592   hjpeg->Instance->CR |= JPEG_CR_IFF;
593   hjpeg->Instance->CR |= JPEG_CR_OFF;
594 
595   /* Clear all flags */
596   __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);
597 
598   /* init default quantization tables*/
599   hjpeg->QuantTable0 = (uint8_t *)((uint32_t)JPEG_LUM_QuantTable);
600   hjpeg->QuantTable1 = (uint8_t *)((uint32_t)JPEG_CHROM_QuantTable);
601   hjpeg->QuantTable2 = NULL;
602   hjpeg->QuantTable3 = NULL;
603 
604   /* init the default Huffman tables*/
605   if (JPEG_Set_HuffEnc_Mem(hjpeg) != HAL_OK)
606   {
607     hjpeg->ErrorCode = HAL_JPEG_ERROR_HUFF_TABLE;
608 
609     return HAL_ERROR;
610   }
611 
612   /* Enable header processing*/
613   hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR;
614 
615   /* Reset JpegInCount and JpegOutCount */
616   hjpeg->JpegInCount = 0;
617   hjpeg->JpegOutCount = 0;
618 
619   /* Change the JPEG state */
620   hjpeg->State = HAL_JPEG_STATE_READY;
621 
622   /* Reset the JPEG ErrorCode */
623   hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE;
624 
625   /* Clear the context fields */
626   hjpeg->Context = 0;
627 
628   /* Return function status */
629   return HAL_OK;
630 }
631 
632 /**
633   * @brief  DeInitializes the JPEG peripheral.
634   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
635   *         the configuration information for JPEG module
636   * @retval HAL status
637   */
HAL_JPEG_DeInit(JPEG_HandleTypeDef * hjpeg)638 HAL_StatusTypeDef HAL_JPEG_DeInit(JPEG_HandleTypeDef *hjpeg)
639 {
640   /* Check the JPEG handle allocation */
641   if (hjpeg == NULL)
642   {
643     return HAL_ERROR;
644   }
645 
646 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
647   if (hjpeg->MspDeInitCallback == NULL)
648   {
649     hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit  */
650   }
651 
652   /* DeInit the low level hardware */
653   hjpeg->MspDeInitCallback(hjpeg);
654 
655 #else
656   /* DeInit the low level hardware: CLOCK, NVIC.*/
657   HAL_JPEG_MspDeInit(hjpeg);
658 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
659 
660   /* Change the JPEG state */
661   hjpeg->State = HAL_JPEG_STATE_BUSY;
662 
663   /* Reset the JPEG ErrorCode */
664   hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE;
665 
666   /* Reset JpegInCount and JpegOutCount */
667   hjpeg->JpegInCount = 0;
668   hjpeg->JpegOutCount = 0;
669 
670   /* Change the JPEG state */
671   hjpeg->State = HAL_JPEG_STATE_RESET;
672 
673   /*Clear the context fields*/
674   hjpeg->Context = 0;
675 
676   /* Release Lock */
677   __HAL_UNLOCK(hjpeg);
678 
679   /* Return function status */
680   return HAL_OK;
681 }
682 
683 /**
684   * @brief  Initializes the JPEG MSP.
685   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
686   *         the configuration information for JPEG module
687   * @retval None
688   */
HAL_JPEG_MspInit(JPEG_HandleTypeDef * hjpeg)689 __weak void HAL_JPEG_MspInit(JPEG_HandleTypeDef *hjpeg)
690 {
691   /* Prevent unused argument(s) compilation warning */
692   UNUSED(hjpeg);
693 
694   /* NOTE : This function Should not be modified, when the callback is needed,
695             the HAL_JPEG_MspInit could be implemented in the user file
696    */
697 }
698 
699 /**
700   * @brief  DeInitializes JPEG MSP.
701   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
702   *         the configuration information for JPEG module
703   * @retval None
704   */
HAL_JPEG_MspDeInit(JPEG_HandleTypeDef * hjpeg)705 __weak void HAL_JPEG_MspDeInit(JPEG_HandleTypeDef *hjpeg)
706 {
707   /* Prevent unused argument(s) compilation warning */
708   UNUSED(hjpeg);
709 
710   /* NOTE : This function Should not be modified, when the callback is needed,
711             the HAL_JPEG_MspDeInit could be implemented in the user file
712    */
713 }
714 
715 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
716 /**
717   * @brief  Register a User JPEG Callback
718   *         To be used to override the weak predefined callback
719   * @param  hjpeg JPEG handle
720   * @param  CallbackID ID of the callback to be registered
721   *         This parameter can be one of the following values:
722   *          @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID
723   *          @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID
724   *          @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID
725   *          @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID
726   *          @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID
727   * @param  pCallback pointer to the Callback function
728   * @retval HAL status
729   */
HAL_JPEG_RegisterCallback(JPEG_HandleTypeDef * hjpeg,HAL_JPEG_CallbackIDTypeDef CallbackID,pJPEG_CallbackTypeDef pCallback)730 HAL_StatusTypeDef HAL_JPEG_RegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID,
731                                             pJPEG_CallbackTypeDef pCallback)
732 {
733   HAL_StatusTypeDef status = HAL_OK;
734 
735   if (pCallback == NULL)
736   {
737     /* Update the error code */
738     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
739     return HAL_ERROR;
740   }
741   /* Process locked */
742   __HAL_LOCK(hjpeg);
743 
744   if (HAL_JPEG_STATE_READY == hjpeg->State)
745   {
746     switch (CallbackID)
747     {
748       case HAL_JPEG_ENCODE_CPLT_CB_ID :
749         hjpeg->EncodeCpltCallback = pCallback;
750         break;
751 
752       case HAL_JPEG_DECODE_CPLT_CB_ID :
753         hjpeg->DecodeCpltCallback = pCallback;
754         break;
755 
756       case HAL_JPEG_ERROR_CB_ID :
757         hjpeg->ErrorCallback = pCallback;
758         break;
759 
760       case HAL_JPEG_MSPINIT_CB_ID :
761         hjpeg->MspInitCallback = pCallback;
762         break;
763 
764       case HAL_JPEG_MSPDEINIT_CB_ID :
765         hjpeg->MspDeInitCallback = pCallback;
766         break;
767 
768       default :
769         /* Update the error code */
770         hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
771         /* Return error status */
772         status =  HAL_ERROR;
773         break;
774     }
775   }
776   else if (HAL_JPEG_STATE_RESET == hjpeg->State)
777   {
778     switch (CallbackID)
779     {
780       case HAL_JPEG_MSPINIT_CB_ID :
781         hjpeg->MspInitCallback = pCallback;
782         break;
783 
784       case HAL_JPEG_MSPDEINIT_CB_ID :
785         hjpeg->MspDeInitCallback = pCallback;
786         break;
787 
788       default :
789         /* Update the error code */
790         hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
791         /* Return error status */
792         status =  HAL_ERROR;
793         break;
794     }
795   }
796   else
797   {
798     /* Update the error code */
799     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
800     /* Return error status */
801     status =  HAL_ERROR;
802   }
803 
804   /* Release Lock */
805   __HAL_UNLOCK(hjpeg);
806   return status;
807 }
808 
809 /**
810   * @brief  Unregister a JPEG Callback
811   *         JPEG callback is redirected to the weak predefined callback
812   * @param  hjpeg JPEG handle
813   * @param  CallbackID ID of the callback to be unregistered
814   *         This parameter can be one of the following values:
815   *          @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID
816   *          @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID
817   *          @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID
818   *          @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID
819   *          @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID
820   * @retval HAL status
821   */
HAL_JPEG_UnRegisterCallback(JPEG_HandleTypeDef * hjpeg,HAL_JPEG_CallbackIDTypeDef CallbackID)822 HAL_StatusTypeDef HAL_JPEG_UnRegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID)
823 {
824   HAL_StatusTypeDef status = HAL_OK;
825 
826   /* Process locked */
827   __HAL_LOCK(hjpeg);
828 
829   if (HAL_JPEG_STATE_READY == hjpeg->State)
830   {
831     switch (CallbackID)
832     {
833       case HAL_JPEG_ENCODE_CPLT_CB_ID :
834         hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback  */
835         break;
836 
837       case HAL_JPEG_DECODE_CPLT_CB_ID :
838         hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback  */
839         break;
840 
841       case HAL_JPEG_ERROR_CB_ID :
842         hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback;           /* Legacy weak ErrorCallback  */
843         break;
844 
845       case HAL_JPEG_MSPINIT_CB_ID :
846         hjpeg->MspInitCallback = HAL_JPEG_MspInit;              /* Legacy weak MspInit  */
847         break;
848 
849       case HAL_JPEG_MSPDEINIT_CB_ID :
850         hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit;          /* Legacy weak MspDeInit  */
851         break;
852 
853       default :
854         /* Update the error code */
855         hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
856         /* Return error status */
857         status =  HAL_ERROR;
858         break;
859     }
860   }
861   else if (HAL_JPEG_STATE_RESET == hjpeg->State)
862   {
863     switch (CallbackID)
864     {
865       case HAL_JPEG_MSPINIT_CB_ID :
866         hjpeg->MspInitCallback = HAL_JPEG_MspInit;           /* Legacy weak MspInit  */
867         break;
868 
869       case HAL_JPEG_MSPDEINIT_CB_ID :
870         hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit;       /* Legacy weak MspInit  */
871         break;
872 
873       default :
874         /* Update the error code */
875         hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
876         /* Return error status */
877         status =  HAL_ERROR;
878         break;
879     }
880   }
881   else
882   {
883     /* Update the error code */
884     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
885     /* Return error status */
886     status =  HAL_ERROR;
887   }
888 
889   /* Release Lock */
890   __HAL_UNLOCK(hjpeg);
891   return status;
892 }
893 
894 /**
895   * @brief  Register Info Ready JPEG Callback
896   *         To be used instead of the weak HAL_JPEG_InfoReadyCallback() predefined callback
897   * @param  hjpeg JPEG handle
898   * @param  pCallback pointer to the Info Ready Callback function
899   * @retval HAL status
900   */
HAL_JPEG_RegisterInfoReadyCallback(JPEG_HandleTypeDef * hjpeg,pJPEG_InfoReadyCallbackTypeDef pCallback)901 HAL_StatusTypeDef HAL_JPEG_RegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg,
902                                                      pJPEG_InfoReadyCallbackTypeDef pCallback)
903 {
904   HAL_StatusTypeDef status = HAL_OK;
905 
906   if (pCallback == NULL)
907   {
908     /* Update the error code */
909     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
910     return HAL_ERROR;
911   }
912   /* Process locked */
913   __HAL_LOCK(hjpeg);
914 
915   if (HAL_JPEG_STATE_READY == hjpeg->State)
916   {
917     hjpeg->InfoReadyCallback = pCallback;
918   }
919   else
920   {
921     /* Update the error code */
922     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
923     /* Return error status */
924     status =  HAL_ERROR;
925   }
926 
927   /* Release Lock */
928   __HAL_UNLOCK(hjpeg);
929   return status;
930 }
931 
932 /**
933   * @brief  UnRegister the Info Ready JPEG Callback
934   *         Info Ready JPEG Callback is redirected to the weak HAL_JPEG_InfoReadyCallback() predefined callback
935   * @param  hjpeg JPEG handle
936   * @retval HAL status
937   */
HAL_JPEG_UnRegisterInfoReadyCallback(JPEG_HandleTypeDef * hjpeg)938 HAL_StatusTypeDef HAL_JPEG_UnRegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg)
939 {
940   HAL_StatusTypeDef status = HAL_OK;
941 
942   /* Process locked */
943   __HAL_LOCK(hjpeg);
944 
945   if (HAL_JPEG_STATE_READY == hjpeg->State)
946   {
947     hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback  */
948   }
949   else
950   {
951     /* Update the error code */
952     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
953     /* Return error status */
954     status =  HAL_ERROR;
955   }
956 
957   /* Release Lock */
958   __HAL_UNLOCK(hjpeg);
959   return status;
960 }
961 
962 /**
963   * @brief  Register Get Data JPEG Callback
964   *         To be used instead of the weak HAL_JPEG_GetDataCallback() predefined callback
965   * @param  hjpeg JPEG handle
966   * @param  pCallback pointer to the Get Data Callback function
967   * @retval HAL status
968   */
HAL_JPEG_RegisterGetDataCallback(JPEG_HandleTypeDef * hjpeg,pJPEG_GetDataCallbackTypeDef pCallback)969 HAL_StatusTypeDef HAL_JPEG_RegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg, pJPEG_GetDataCallbackTypeDef pCallback)
970 {
971   HAL_StatusTypeDef status = HAL_OK;
972 
973   if (pCallback == NULL)
974   {
975     /* Update the error code */
976     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
977     return HAL_ERROR;
978   }
979   /* Process locked */
980   __HAL_LOCK(hjpeg);
981 
982   if (HAL_JPEG_STATE_READY == hjpeg->State)
983   {
984     hjpeg->GetDataCallback = pCallback;
985   }
986   else
987   {
988     /* Update the error code */
989     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
990     /* Return error status */
991     status =  HAL_ERROR;
992   }
993 
994   /* Release Lock */
995   __HAL_UNLOCK(hjpeg);
996   return status;
997 }
998 
999 /**
1000   * @brief  UnRegister the Get Data JPEG Callback
1001   *         Get Data JPEG Callback is redirected to the weak HAL_JPEG_GetDataCallback() predefined callback
1002   * @param  hjpeg JPEG handle
1003   * @retval HAL status
1004   */
HAL_JPEG_UnRegisterGetDataCallback(JPEG_HandleTypeDef * hjpeg)1005 HAL_StatusTypeDef HAL_JPEG_UnRegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg)
1006 {
1007   HAL_StatusTypeDef status = HAL_OK;
1008 
1009   /* Process locked */
1010   __HAL_LOCK(hjpeg);
1011 
1012   if (HAL_JPEG_STATE_READY == hjpeg->State)
1013   {
1014     hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback;  /* Legacy weak GetDataCallback  */
1015   }
1016   else
1017   {
1018     /* Update the error code */
1019     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
1020     /* Return error status */
1021     status =  HAL_ERROR;
1022   }
1023 
1024   /* Release Lock */
1025   __HAL_UNLOCK(hjpeg);
1026   return status;
1027 }
1028 
1029 /**
1030   * @brief  Register Data Ready JPEG Callback
1031   *         To be used instead of the weak HAL_JPEG_DataReadyCallback() predefined callback
1032   * @param  hjpeg JPEG handle
1033   * @param  pCallback pointer to the Get Data Callback function
1034   * @retval HAL status
1035   */
HAL_JPEG_RegisterDataReadyCallback(JPEG_HandleTypeDef * hjpeg,pJPEG_DataReadyCallbackTypeDef pCallback)1036 HAL_StatusTypeDef HAL_JPEG_RegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg,
1037                                                      pJPEG_DataReadyCallbackTypeDef pCallback)
1038 {
1039   HAL_StatusTypeDef status = HAL_OK;
1040 
1041   if (pCallback == NULL)
1042   {
1043     /* Update the error code */
1044     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
1045     return HAL_ERROR;
1046   }
1047   /* Process locked */
1048   __HAL_LOCK(hjpeg);
1049 
1050   if (HAL_JPEG_STATE_READY == hjpeg->State)
1051   {
1052     hjpeg->DataReadyCallback = pCallback;
1053   }
1054   else
1055   {
1056     /* Update the error code */
1057     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
1058     /* Return error status */
1059     status =  HAL_ERROR;
1060   }
1061 
1062   /* Release Lock */
1063   __HAL_UNLOCK(hjpeg);
1064   return status;
1065 }
1066 
1067 /**
1068   * @brief  UnRegister the Data Ready JPEG Callback
1069   *         Get Data Ready Callback is redirected to the weak HAL_JPEG_DataReadyCallback() predefined callback
1070   * @param  hjpeg JPEG handle
1071   * @retval HAL status
1072   */
HAL_JPEG_UnRegisterDataReadyCallback(JPEG_HandleTypeDef * hjpeg)1073 HAL_StatusTypeDef HAL_JPEG_UnRegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg)
1074 {
1075   HAL_StatusTypeDef status = HAL_OK;
1076 
1077   /* Process locked */
1078   __HAL_LOCK(hjpeg);
1079 
1080   if (HAL_JPEG_STATE_READY == hjpeg->State)
1081   {
1082     hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback;  /* Legacy weak DataReadyCallback  */
1083   }
1084   else
1085   {
1086     /* Update the error code */
1087     hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
1088     /* Return error status */
1089     status =  HAL_ERROR;
1090   }
1091 
1092   /* Release Lock */
1093   __HAL_UNLOCK(hjpeg);
1094   return status;
1095 }
1096 
1097 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
1098 
1099 /**
1100   * @}
1101   */
1102 
1103 /** @defgroup JPEG_Exported_Functions_Group2 Configuration functions
1104   *  @brief    JPEG Configuration functions.
1105   *
1106 @verbatim
1107   ==============================================================================
1108               ##### Configuration functions #####
1109   ==============================================================================
1110     [..]  This section provides functions allowing to:
1111       (+) HAL_JPEG_ConfigEncoding() : JPEG encoding configuration
1112       (+) HAL_JPEG_GetInfo() :  Extract the image configuration from the JPEG header during the decoding
1113       (+) HAL_JPEG_EnableHeaderParsing() :  Enable JPEG Header parsing for decoding
1114       (+) HAL_JPEG_DisableHeaderParsing() : Disable JPEG Header parsing for decoding
1115       (+) HAL_JPEG_SetUserQuantTables : Modify the default Quantization tables used for JPEG encoding.
1116 
1117 @endverbatim
1118   * @{
1119   */
1120 
1121 /**
1122   * @brief  Set the JPEG encoding configuration.
1123   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1124   *         the configuration information for JPEG module
1125   * @param  pConf pointer to a JPEG_ConfTypeDef structure that contains
1126   *         the encoding configuration
1127   * @retval HAL status
1128   */
HAL_JPEG_ConfigEncoding(JPEG_HandleTypeDef * hjpeg,JPEG_ConfTypeDef * pConf)1129 HAL_StatusTypeDef HAL_JPEG_ConfigEncoding(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pConf)
1130 {
1131   uint32_t error;
1132   uint32_t numberMCU;
1133   uint32_t hfactor;
1134   uint32_t vfactor;
1135   uint32_t hMCU;
1136   uint32_t vMCU;
1137 
1138   /* Check the JPEG handle allocation */
1139   if ((hjpeg == NULL) || (pConf == NULL))
1140   {
1141     return HAL_ERROR;
1142   }
1143   else
1144   {
1145     /* Check the parameters */
1146     assert_param(IS_JPEG_COLORSPACE(pConf->ColorSpace));
1147     assert_param(IS_JPEG_CHROMASUBSAMPLING(pConf->ChromaSubsampling));
1148     assert_param(IS_JPEG_IMAGE_QUALITY(pConf->ImageQuality));
1149 
1150     /* Process Locked */
1151     __HAL_LOCK(hjpeg);
1152 
1153     if (hjpeg->State == HAL_JPEG_STATE_READY)
1154     {
1155       hjpeg->State = HAL_JPEG_STATE_BUSY;
1156 
1157       hjpeg->Conf.ColorSpace          =  pConf->ColorSpace;
1158       hjpeg->Conf.ChromaSubsampling   =  pConf->ChromaSubsampling;
1159       hjpeg->Conf.ImageHeight         =  pConf->ImageHeight;
1160       hjpeg->Conf.ImageWidth          =  pConf->ImageWidth;
1161       hjpeg->Conf.ImageQuality        =  pConf->ImageQuality;
1162 
1163       /* Reset the Color Space : by default only one quantization table is used*/
1164       hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_COLORSPACE;
1165 
1166       /* Set Number of color components*/
1167       if (hjpeg->Conf.ColorSpace == JPEG_GRAYSCALE_COLORSPACE)
1168       {
1169         /*Gray Scale is only one component 8x8 blocks i.e 4:4:4*/
1170         hjpeg->Conf.ChromaSubsampling = JPEG_444_SUBSAMPLING;
1171 
1172         JPEG_SetColorGrayScale(hjpeg);
1173         /* Set quantization table 0*/
1174         error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
1175       }
1176       else if (hjpeg->Conf.ColorSpace == JPEG_YCBCR_COLORSPACE)
1177       {
1178         /*
1179            Set the Color Space for YCbCr : 2 quantization tables are used
1180            one for Luminance(Y) and one for both Chrominances (Cb & Cr)
1181           */
1182         hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_0;
1183 
1184         JPEG_SetColorYCBCR(hjpeg);
1185 
1186         /* Set quantization table 0*/
1187         error  = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
1188         /*By default quantization table 0 for component 0 and quantization table 1 for both components 1 and 2*/
1189         (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1));
1190 
1191         if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL)
1192         {
1193           /*Use user customized quantization tables , 1 table per component*/
1194           /* use 3 quantization tables , one for each component*/
1195           hjpeg->Instance->CONFR1 &= (~JPEG_CONFR1_COLORSPACE);
1196           hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_1;
1197 
1198           (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2));
1199 
1200           /*Use Quantization 1 table for component 1*/
1201           hjpeg->Instance->CONFR5 &= (~JPEG_CONFR5_QT);
1202           hjpeg->Instance->CONFR5 |=  JPEG_CONFR5_QT_0;
1203 
1204           /*Use Quantization 2 table for component 2*/
1205           hjpeg->Instance->CONFR6 &= (~JPEG_CONFR6_QT);
1206           hjpeg->Instance->CONFR6 |=  JPEG_CONFR6_QT_1;
1207         }
1208       }
1209       else /* ColorSpace == JPEG_CMYK_COLORSPACE */
1210       {
1211         JPEG_SetColorCMYK(hjpeg);
1212 
1213         /* Set quantization table 0*/
1214         error  = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
1215         /*By default quantization table 0 for All components*/
1216 
1217         if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL)
1218         {
1219           /*Use user customized quantization tables , 1 table per component*/
1220           /* use 4 quantization tables , one for each component*/
1221           hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE;
1222 
1223           (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1));
1224           (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2));
1225           (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable3, (hjpeg->Instance->QMEM3));
1226 
1227           /*Use Quantization 1 table for component 1*/
1228           hjpeg->Instance->CONFR5 |=  JPEG_CONFR5_QT_0;
1229 
1230           /*Use Quantization 2 table for component 2*/
1231           hjpeg->Instance->CONFR6 |=  JPEG_CONFR6_QT_1;
1232 
1233           /*Use Quantization 3 table for component 3*/
1234           hjpeg->Instance->CONFR7 |=  JPEG_CONFR7_QT;
1235         }
1236       }
1237 
1238       if (error != 0UL)
1239       {
1240         hjpeg->ErrorCode = HAL_JPEG_ERROR_QUANT_TABLE;
1241 
1242         /* Process Unlocked */
1243         __HAL_UNLOCK(hjpeg);
1244 
1245         /* Set the JPEG State to ready */
1246         hjpeg->State = HAL_JPEG_STATE_READY;
1247 
1248         return  HAL_ERROR;
1249       }
1250       /* Set the image size*/
1251       /* set the number of lines*/
1252       MODIFY_REG(hjpeg->Instance->CONFR1, JPEG_CONFR1_YSIZE, ((hjpeg->Conf.ImageHeight & 0x0000FFFFUL) << 16));
1253       /* set the number of pixels per line*/
1254       MODIFY_REG(hjpeg->Instance->CONFR3, JPEG_CONFR3_XSIZE, ((hjpeg->Conf.ImageWidth & 0x0000FFFFUL) << 16));
1255 
1256 
1257       if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) /* 4:2:0*/
1258       {
1259         hfactor = 16;
1260         vfactor = 16;
1261       }
1262       else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) /* 4:2:2*/
1263       {
1264         hfactor = 16;
1265         vfactor = 8;
1266       }
1267       else /* Default is 8x8 MCU,  4:4:4*/
1268       {
1269         hfactor = 8;
1270         vfactor = 8;
1271       }
1272 
1273       hMCU = (hjpeg->Conf.ImageWidth / hfactor);
1274       if ((hjpeg->Conf.ImageWidth % hfactor) != 0UL)
1275       {
1276         hMCU++; /*+1 for horizontal incomplete MCU */
1277       }
1278 
1279       vMCU = (hjpeg->Conf.ImageHeight / vfactor);
1280       if ((hjpeg->Conf.ImageHeight % vfactor) != 0UL)
1281       {
1282         vMCU++; /*+1 for vertical incomplete MCU */
1283       }
1284 
1285       numberMCU = (hMCU * vMCU) - 1UL; /* Bit Field JPEG_CONFR2_NMCU shall be set to NB_MCU - 1*/
1286       /* Set the number of MCU*/
1287       hjpeg->Instance->CONFR2 = (numberMCU & JPEG_CONFR2_NMCU);
1288 
1289       hjpeg->Context |= JPEG_CONTEXT_CONF_ENCODING;
1290 
1291       /* Process Unlocked */
1292       __HAL_UNLOCK(hjpeg);
1293 
1294       /* Set the JPEG State to ready */
1295       hjpeg->State = HAL_JPEG_STATE_READY;
1296 
1297       /* Return function status */
1298       return HAL_OK;
1299     }
1300     else
1301     {
1302       /* Process Unlocked */
1303       __HAL_UNLOCK(hjpeg);
1304 
1305       /* Return function status */
1306       return HAL_BUSY;
1307     }
1308   }
1309 }
1310 
1311 /**
1312   * @brief  Extract the image configuration from the JPEG header during the decoding
1313   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1314   *         the configuration information for JPEG module
1315   * @param  pInfo pointer to a JPEG_ConfTypeDef structure that contains
1316   *         The JPEG decoded header information
1317   * @retval HAL status
1318   */
HAL_JPEG_GetInfo(JPEG_HandleTypeDef * hjpeg,JPEG_ConfTypeDef * pInfo)1319 HAL_StatusTypeDef HAL_JPEG_GetInfo(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo)
1320 {
1321   uint32_t yblockNb;
1322   uint32_t cBblockNb;
1323   uint32_t cRblockNb;
1324 
1325   /* Check the JPEG handle allocation */
1326   if ((hjpeg == NULL) || (pInfo == NULL))
1327   {
1328     return HAL_ERROR;
1329   }
1330 
1331   /*Read the conf parameters */
1332   if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF_1)
1333   {
1334     pInfo->ColorSpace = JPEG_YCBCR_COLORSPACE;
1335   }
1336   else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == 0UL)
1337   {
1338     pInfo->ColorSpace = JPEG_GRAYSCALE_COLORSPACE;
1339   }
1340   else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF)
1341   {
1342     pInfo->ColorSpace = JPEG_CMYK_COLORSPACE;
1343   }
1344   else
1345   {
1346     return HAL_ERROR;
1347   }
1348 
1349   pInfo->ImageHeight = (hjpeg->Instance->CONFR1 & 0xFFFF0000UL) >> 16;
1350   pInfo->ImageWidth  = (hjpeg->Instance->CONFR3 & 0xFFFF0000UL) >> 16;
1351 
1352   if ((pInfo->ColorSpace == JPEG_YCBCR_COLORSPACE) || (pInfo->ColorSpace == JPEG_CMYK_COLORSPACE))
1353   {
1354     yblockNb  = (hjpeg->Instance->CONFR4 & JPEG_CONFR4_NB) >> 4;
1355     cBblockNb = (hjpeg->Instance->CONFR5 & JPEG_CONFR5_NB) >> 4;
1356     cRblockNb = (hjpeg->Instance->CONFR6 & JPEG_CONFR6_NB) >> 4;
1357 
1358     if ((yblockNb == 1UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
1359     {
1360       pInfo->ChromaSubsampling = JPEG_422_SUBSAMPLING; /*16x8 block*/
1361     }
1362     else if ((yblockNb == 0UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
1363     {
1364       pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
1365     }
1366     else if ((yblockNb == 3UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
1367     {
1368       pInfo->ChromaSubsampling = JPEG_420_SUBSAMPLING;
1369     }
1370     else /*Default is 4:4:4*/
1371     {
1372       pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
1373     }
1374   }
1375   else
1376   {
1377     pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
1378   }
1379 
1380   pInfo->ImageQuality = JPEG_GetQuality(hjpeg);
1381 
1382   /* Return function status */
1383   return HAL_OK;
1384 }
1385 
1386 /**
1387   * @brief  Enable JPEG Header parsing for decoding
1388   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1389   *               the configuration information for the JPEG.
1390   * @retval HAL status
1391   */
HAL_JPEG_EnableHeaderParsing(JPEG_HandleTypeDef * hjpeg)1392 HAL_StatusTypeDef HAL_JPEG_EnableHeaderParsing(JPEG_HandleTypeDef *hjpeg)
1393 {
1394   /* Process locked */
1395   __HAL_LOCK(hjpeg);
1396 
1397   if (hjpeg->State == HAL_JPEG_STATE_READY)
1398   {
1399     /* Change the JPEG state */
1400     hjpeg->State = HAL_JPEG_STATE_BUSY;
1401 
1402     /* Enable header processing*/
1403     hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR;
1404 
1405     /* Process unlocked */
1406     __HAL_UNLOCK(hjpeg);
1407 
1408     /* Change the JPEG state */
1409     hjpeg->State = HAL_JPEG_STATE_READY;
1410 
1411     return HAL_OK;
1412   }
1413   else
1414   {
1415     /* Process unlocked */
1416     __HAL_UNLOCK(hjpeg);
1417 
1418     return HAL_BUSY;
1419   }
1420 }
1421 
1422 /**
1423   * @brief  Disable JPEG Header parsing for decoding
1424   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1425   *               the configuration information for the JPEG.
1426   * @retval HAL status
1427   */
HAL_JPEG_DisableHeaderParsing(JPEG_HandleTypeDef * hjpeg)1428 HAL_StatusTypeDef HAL_JPEG_DisableHeaderParsing(JPEG_HandleTypeDef *hjpeg)
1429 {
1430   /* Process locked */
1431   __HAL_LOCK(hjpeg);
1432 
1433   if (hjpeg->State == HAL_JPEG_STATE_READY)
1434   {
1435     /* Change the JPEG state */
1436     hjpeg->State = HAL_JPEG_STATE_BUSY;
1437 
1438     /* Disable header processing*/
1439     hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_HDR;
1440 
1441     /* Process unlocked */
1442     __HAL_UNLOCK(hjpeg);
1443 
1444     /* Change the JPEG state */
1445     hjpeg->State = HAL_JPEG_STATE_READY;
1446 
1447     return HAL_OK;
1448   }
1449   else
1450   {
1451     /* Process unlocked */
1452     __HAL_UNLOCK(hjpeg);
1453 
1454     return HAL_BUSY;
1455   }
1456 }
1457 
1458 /**
1459   * @brief  Modify the default Quantization tables used for JPEG encoding.
1460   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1461   *         the configuration information for JPEG module
1462   * @param  QTable0  pointer to uint8_t , define the user quantification table for color component 1.
1463   *                  If NULL assume no need to update  the table and no error return
1464   * @param  QTable1  pointer to uint8_t , define the user quantification table for color component 2.
1465   *                  If NULL assume no need to update  the table and no error return.
1466   * @param  QTable2  pointer to uint8_t , define the user quantification table for color component 3,
1467   *                  If NULL assume no need to update  the table and no error return.
1468   * @param  QTable3  pointer to uint8_t , define the user quantification table for color component 4.
1469   *                  If NULL assume no need to update  the table and no error return.
1470   *
1471   * @retval HAL status
1472   */
1473 
1474 
HAL_JPEG_SetUserQuantTables(JPEG_HandleTypeDef * hjpeg,uint8_t * QTable0,uint8_t * QTable1,uint8_t * QTable2,uint8_t * QTable3)1475 HAL_StatusTypeDef  HAL_JPEG_SetUserQuantTables(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable0, uint8_t *QTable1,
1476                                                uint8_t *QTable2, uint8_t *QTable3)
1477 {
1478   /* Process Locked */
1479   __HAL_LOCK(hjpeg);
1480 
1481   if (hjpeg->State == HAL_JPEG_STATE_READY)
1482   {
1483     /* Change the DMA state */
1484     hjpeg->State = HAL_JPEG_STATE_BUSY;
1485 
1486     hjpeg->Context |= JPEG_CONTEXT_CUSTOM_TABLES;
1487 
1488     hjpeg->QuantTable0 = QTable0;
1489     hjpeg->QuantTable1 = QTable1;
1490     hjpeg->QuantTable2 = QTable2;
1491     hjpeg->QuantTable3 = QTable3;
1492 
1493     /* Process Unlocked */
1494     __HAL_UNLOCK(hjpeg);
1495 
1496     /* Change the DMA state */
1497     hjpeg->State = HAL_JPEG_STATE_READY;
1498 
1499     /* Return function status */
1500     return HAL_OK;
1501   }
1502   else
1503   {
1504     /* Process Unlocked */
1505     __HAL_UNLOCK(hjpeg);
1506 
1507     return HAL_BUSY;
1508   }
1509 }
1510 
1511 /**
1512   * @}
1513   */
1514 
1515 /** @defgroup JPEG_Exported_Functions_Group3 encoding/decoding processing functions
1516   *  @brief   processing functions.
1517   *
1518 @verbatim
1519   ==============================================================================
1520                       ##### JPEG processing functions #####
1521   ==============================================================================
1522     [..]  This section provides functions allowing to:
1523       (+) HAL_JPEG_Encode()     : JPEG encoding with polling process
1524       (+) HAL_JPEG_Decode()     : JPEG decoding with polling process
1525       (+) HAL_JPEG_Encode_IT()  : JPEG encoding with interrupt process
1526       (+) HAL_JPEG_Decode_IT()  : JPEG decoding with interrupt process
1527       (+) HAL_JPEG_Encode_DMA() : JPEG encoding with DMA process
1528       (+) HAL_JPEG_Decode_DMA() : JPEG decoding with DMA process
1529       (+) HAL_JPEG_Pause()      :   Pause the Input/Output processing
1530       (+) HAL_JPEG_Resume()     :  Resume the JPEG Input/Output processing
1531       (+) HAL_JPEG_ConfigInputBuffer()  : Config Encoding/Decoding Input Buffer
1532       (+) HAL_JPEG_ConfigOutputBuffer() : Config Encoding/Decoding Output Buffer
1533       (+) HAL_JPEG_Abort()              : Aborts the JPEG Encoding/Decoding
1534 
1535 @endverbatim
1536   * @{
1537   */
1538 
1539 /**
1540   * @brief  Starts JPEG encoding with polling processing
1541   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1542   *         the configuration information for JPEG module
1543   * @param  pDataInMCU Pointer to the Input buffer
1544   * @param  InDataLength size in bytes Input buffer
1545   * @param  pDataOut Pointer to the jpeg output data buffer
1546   * @param  OutDataLength size in bytes of the Output buffer
1547   * @param  Timeout Specify Timeout value
1548   * @retval HAL status
1549   */
HAL_JPEG_Encode(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataInMCU,uint32_t InDataLength,uint8_t * pDataOut,uint32_t OutDataLength,uint32_t Timeout)1550 HAL_StatusTypeDef  HAL_JPEG_Encode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
1551                                    uint8_t *pDataOut, uint32_t OutDataLength, uint32_t Timeout)
1552 {
1553   uint32_t tickstart;
1554 
1555   /* Check the parameters */
1556   assert_param((InDataLength >= 4UL));
1557   assert_param((OutDataLength >= 4UL));
1558 
1559   /* Check In/out buffer allocation and size */
1560   if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
1561   {
1562     return HAL_ERROR;
1563   }
1564   /* Process locked */
1565   __HAL_LOCK(hjpeg);
1566 
1567   if (hjpeg->State != HAL_JPEG_STATE_READY)
1568   {
1569     /* Process Unlocked */
1570     __HAL_UNLOCK(hjpeg);
1571 
1572     return HAL_BUSY;
1573   }
1574 
1575   if (hjpeg->State == HAL_JPEG_STATE_READY)
1576   {
1577     if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
1578     {
1579       /*Change JPEG state*/
1580       hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;
1581 
1582       /*Set the Context to Encode with Polling*/
1583       hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1584       hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_POLLING);
1585 
1586       /* Get tick */
1587       tickstart = HAL_GetTick();
1588 
1589       /*Store In/out buffers pointers and size*/
1590       hjpeg->pJpegInBuffPtr = pDataInMCU;
1591       hjpeg->pJpegOutBuffPtr = pDataOut;
1592       hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /* In Data length must be multiple
1593                                                                        of 4 Bytes (1 word)*/
1594       hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /* Out Data length must be multiple
1595                                                                        of 4 Bytes (1 word)*/
1596 
1597       /*Reset In/out data counter */
1598       hjpeg->JpegInCount = 0;
1599       hjpeg->JpegOutCount = 0;
1600 
1601       /*Init decoding process*/
1602       JPEG_Init_Process(hjpeg);
1603 
1604       /*JPEG data processing : In/Out FIFO transfer*/
1605       while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING))
1606       {
1607         if (Timeout != HAL_MAX_DELAY)
1608         {
1609           if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1610           {
1611 
1612             /* Update error code */
1613             hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;
1614 
1615             /* Process Unlocked */
1616             __HAL_UNLOCK(hjpeg);
1617 
1618             /*Change JPEG state*/
1619             hjpeg->State = HAL_JPEG_STATE_READY;
1620 
1621             return HAL_TIMEOUT;
1622           }
1623         }
1624       }
1625 
1626       /* Process Unlocked */
1627       __HAL_UNLOCK(hjpeg);
1628 
1629       /*Change JPEG state*/
1630       hjpeg->State = HAL_JPEG_STATE_READY;
1631 
1632     }
1633     else
1634     {
1635       /* Process Unlocked */
1636       __HAL_UNLOCK(hjpeg);
1637 
1638       return HAL_ERROR;
1639     }
1640   }
1641   /* Return function status */
1642   return HAL_OK;
1643 }
1644 
1645 /**
1646   * @brief  Starts JPEG decoding with polling processing
1647   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1648   *         the configuration information for JPEG module
1649   * @param  pDataIn Pointer to the input data buffer
1650   * @param  InDataLength size in bytes Input buffer
1651   * @param  pDataOutMCU Pointer to the Output data buffer
1652   * @param  OutDataLength size in bytes of the Output buffer
1653   * @param  Timeout Specify Timeout value
1654   * @retval HAL status
1655   */
HAL_JPEG_Decode(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataIn,uint32_t InDataLength,uint8_t * pDataOutMCU,uint32_t OutDataLength,uint32_t Timeout)1656 HAL_StatusTypeDef  HAL_JPEG_Decode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
1657                                    uint8_t *pDataOutMCU, uint32_t OutDataLength, uint32_t Timeout)
1658 {
1659   uint32_t tickstart;
1660 
1661   /* Check the parameters */
1662   assert_param((InDataLength >= 4UL));
1663   assert_param((OutDataLength >= 4UL));
1664 
1665   /* Check In/out buffer allocation and size */
1666   if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
1667   {
1668     return HAL_ERROR;
1669   }
1670 
1671   /* Process Locked */
1672   __HAL_LOCK(hjpeg);
1673 
1674   /* Get tick */
1675   tickstart = HAL_GetTick();
1676 
1677   if (hjpeg->State == HAL_JPEG_STATE_READY)
1678   {
1679     /*Change JPEG state*/
1680     hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;
1681 
1682     /*Set the Context to Decode with Polling*/
1683     /*Set the Context to Encode with Polling*/
1684     hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1685     hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_POLLING);
1686 
1687     /*Store In/out buffers pointers and size*/
1688     hjpeg->pJpegInBuffPtr = pDataIn;
1689     hjpeg->pJpegOutBuffPtr = pDataOutMCU;
1690     hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple
1691                                                                     of 4 Bytes (1 word)*/
1692     hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple
1693                                                                     of 4 Bytes (1 word)*/
1694 
1695     /*Reset In/out data counter */
1696     hjpeg->JpegInCount = 0;
1697     hjpeg->JpegOutCount = 0;
1698 
1699     /*Init decoding process*/
1700     JPEG_Init_Process(hjpeg);
1701 
1702     /*JPEG data processing : In/Out FIFO transfer*/
1703     while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING))
1704     {
1705       if (Timeout != HAL_MAX_DELAY)
1706       {
1707         if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1708         {
1709 
1710           /* Update error code */
1711           hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;
1712 
1713           /* Process Unlocked */
1714           __HAL_UNLOCK(hjpeg);
1715 
1716           /*Change JPEG state*/
1717           hjpeg->State = HAL_JPEG_STATE_READY;
1718 
1719           return HAL_TIMEOUT;
1720         }
1721       }
1722     }
1723 
1724     /* Process Unlocked */
1725     __HAL_UNLOCK(hjpeg);
1726 
1727     /*Change JPEG state*/
1728     hjpeg->State = HAL_JPEG_STATE_READY;
1729 
1730   }
1731   else
1732   {
1733     /* Process Unlocked */
1734     __HAL_UNLOCK(hjpeg);
1735 
1736     return HAL_BUSY;
1737   }
1738   /* Return function status */
1739   return HAL_OK;
1740 }
1741 
1742 /**
1743   * @brief  Starts JPEG encoding with interrupt processing
1744   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1745   *         the configuration information for JPEG module
1746   * @param  pDataInMCU Pointer to the Input buffer
1747   * @param  InDataLength size in bytes Input buffer
1748   * @param  pDataOut Pointer to the jpeg output data buffer
1749   * @param  OutDataLength size in bytes of the Output buffer
1750   * @retval HAL status
1751   */
HAL_JPEG_Encode_IT(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataInMCU,uint32_t InDataLength,uint8_t * pDataOut,uint32_t OutDataLength)1752 HAL_StatusTypeDef  HAL_JPEG_Encode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
1753                                       uint8_t *pDataOut, uint32_t OutDataLength)
1754 {
1755   /* Check the parameters */
1756   assert_param((InDataLength >= 4UL));
1757   assert_param((OutDataLength >= 4UL));
1758 
1759   /* Check In/out buffer allocation and size */
1760   if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
1761   {
1762     return HAL_ERROR;
1763   }
1764 
1765   /* Process Locked */
1766   __HAL_LOCK(hjpeg);
1767 
1768   if (hjpeg->State != HAL_JPEG_STATE_READY)
1769   {
1770     /* Process Unlocked */
1771     __HAL_UNLOCK(hjpeg);
1772 
1773     return HAL_BUSY;
1774   }
1775   else
1776   {
1777     if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
1778     {
1779       /*Change JPEG state*/
1780       hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;
1781 
1782       /*Set the Context to Encode with IT*/
1783       hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1784       hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_IT);
1785 
1786       /*Store In/out buffers pointers and size*/
1787       hjpeg->pJpegInBuffPtr = pDataInMCU;
1788       hjpeg->pJpegOutBuffPtr = pDataOut;
1789       hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple
1790                                                                       of 4 Bytes (1 word)*/
1791       hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple
1792                                                                       of 4 Bytes (1 word)*/
1793 
1794       /*Reset In/out data counter */
1795       hjpeg->JpegInCount = 0;
1796       hjpeg->JpegOutCount = 0;
1797 
1798       /*Init decoding process*/
1799       JPEG_Init_Process(hjpeg);
1800 
1801     }
1802     else
1803     {
1804       /* Process Unlocked */
1805       __HAL_UNLOCK(hjpeg);
1806 
1807       return HAL_ERROR;
1808     }
1809   }
1810   /* Return function status */
1811   return HAL_OK;
1812 }
1813 
1814 /**
1815   * @brief  Starts JPEG decoding with interrupt processing
1816   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1817   *         the configuration information for JPEG module
1818   * @param  pDataIn Pointer to the input data buffer
1819   * @param  InDataLength size in bytes Input buffer
1820   * @param  pDataOutMCU Pointer to the Output data buffer
1821   * @param  OutDataLength size in bytes of the Output buffer
1822   * @retval HAL status
1823   */
HAL_JPEG_Decode_IT(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataIn,uint32_t InDataLength,uint8_t * pDataOutMCU,uint32_t OutDataLength)1824 HAL_StatusTypeDef  HAL_JPEG_Decode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
1825                                       uint8_t *pDataOutMCU, uint32_t OutDataLength)
1826 {
1827   /* Check the parameters */
1828   assert_param((InDataLength >= 4UL));
1829   assert_param((OutDataLength >= 4UL));
1830 
1831   /* Check In/out buffer allocation and size */
1832   if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
1833   {
1834     return HAL_ERROR;
1835   }
1836 
1837   /* Process Locked */
1838   __HAL_LOCK(hjpeg);
1839 
1840   if (hjpeg->State == HAL_JPEG_STATE_READY)
1841   {
1842     /*Change JPEG state*/
1843     hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;
1844 
1845     /*Set the Context to Decode with IT*/
1846     hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1847     hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_IT);
1848 
1849     /*Store In/out buffers pointers and size*/
1850     hjpeg->pJpegInBuffPtr = pDataIn;
1851     hjpeg->pJpegOutBuffPtr = pDataOutMCU;
1852     hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple
1853                                                                     of 4 Bytes (1 word)*/
1854     hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple
1855                                                                     of 4 Bytes (1 word)*/
1856 
1857     /*Reset In/out data counter */
1858     hjpeg->JpegInCount = 0;
1859     hjpeg->JpegOutCount = 0;
1860 
1861     /*Init decoding process*/
1862     JPEG_Init_Process(hjpeg);
1863 
1864   }
1865   else
1866   {
1867     /* Process Unlocked */
1868     __HAL_UNLOCK(hjpeg);
1869 
1870     return HAL_BUSY;
1871   }
1872   /* Return function status */
1873   return HAL_OK;
1874 }
1875 
1876 /**
1877   * @brief  Starts JPEG encoding with DMA processing
1878   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1879   *         the configuration information for JPEG module
1880   * @param  pDataInMCU Pointer to the Input buffer
1881   * @param  InDataLength size in bytes Input buffer
1882   * @param  pDataOut Pointer to the jpeg output data buffer
1883   * @param  OutDataLength size in bytes of the Output buffer
1884   * @retval HAL status
1885   */
HAL_JPEG_Encode_DMA(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataInMCU,uint32_t InDataLength,uint8_t * pDataOut,uint32_t OutDataLength)1886 HAL_StatusTypeDef  HAL_JPEG_Encode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
1887                                        uint8_t *pDataOut, uint32_t OutDataLength)
1888 {
1889   /* Check the parameters */
1890   assert_param((InDataLength >= 4UL));
1891   assert_param((OutDataLength >= 4UL));
1892 
1893   /* Check In/out buffer allocation and size */
1894   if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
1895   {
1896     return HAL_ERROR;
1897   }
1898 
1899   /* Process Locked */
1900   __HAL_LOCK(hjpeg);
1901 
1902   if (hjpeg->State != HAL_JPEG_STATE_READY)
1903   {
1904     /* Process Unlocked */
1905     __HAL_UNLOCK(hjpeg);
1906 
1907     return HAL_BUSY;
1908   }
1909   else
1910   {
1911     if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
1912     {
1913       /*Change JPEG state*/
1914       hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;
1915 
1916       /*Set the Context to Encode with DMA*/
1917       hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1918       hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_DMA);
1919 
1920       /*Store In/out buffers pointers and size*/
1921       hjpeg->pJpegInBuffPtr = pDataInMCU;
1922       hjpeg->pJpegOutBuffPtr = pDataOut;
1923       hjpeg->InDataLength = InDataLength;
1924       hjpeg->OutDataLength = OutDataLength;
1925 
1926       /*Reset In/out data counter */
1927       hjpeg->JpegInCount = 0;
1928       hjpeg->JpegOutCount = 0;
1929 
1930       /*Init decoding process*/
1931       JPEG_Init_Process(hjpeg);
1932 
1933       /* JPEG encoding process using DMA */
1934       if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK)
1935       {
1936         /* Update State */
1937         hjpeg->State = HAL_JPEG_STATE_ERROR;
1938         /* Process Unlocked */
1939         __HAL_UNLOCK(hjpeg);
1940 
1941         return HAL_ERROR;
1942       }
1943 
1944     }
1945     else
1946     {
1947       /* Process Unlocked */
1948       __HAL_UNLOCK(hjpeg);
1949 
1950       return HAL_ERROR;
1951     }
1952   }
1953   /* Return function status */
1954   return HAL_OK;
1955 }
1956 
1957 /**
1958   * @brief  Starts JPEG decoding with DMA processing
1959   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
1960   *         the configuration information for JPEG module
1961   * @param  pDataIn Pointer to the input data buffer
1962   * @param  InDataLength size in bytes Input buffer
1963   * @param  pDataOutMCU Pointer to the Output data buffer
1964   * @param  OutDataLength size in bytes of the Output buffer
1965   * @retval HAL status
1966   */
HAL_JPEG_Decode_DMA(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataIn,uint32_t InDataLength,uint8_t * pDataOutMCU,uint32_t OutDataLength)1967 HAL_StatusTypeDef  HAL_JPEG_Decode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
1968                                        uint8_t *pDataOutMCU, uint32_t OutDataLength)
1969 {
1970   /* Check the parameters */
1971   assert_param((InDataLength >= 4UL));
1972   assert_param((OutDataLength >= 4UL));
1973 
1974   /* Check In/out buffer allocation and size */
1975   if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
1976   {
1977     return HAL_ERROR;
1978   }
1979 
1980   /* Process Locked */
1981   __HAL_LOCK(hjpeg);
1982 
1983   if (hjpeg->State == HAL_JPEG_STATE_READY)
1984   {
1985     /*Change JPEG state*/
1986     hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;
1987 
1988     /*Set the Context to Decode with DMA*/
1989     hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
1990     hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_DMA);
1991 
1992     /*Store In/out buffers pointers and size*/
1993     hjpeg->pJpegInBuffPtr = pDataIn;
1994     hjpeg->pJpegOutBuffPtr = pDataOutMCU;
1995     hjpeg->InDataLength = InDataLength;
1996     hjpeg->OutDataLength = OutDataLength;
1997 
1998     /*Reset In/out data counter */
1999     hjpeg->JpegInCount = 0;
2000     hjpeg->JpegOutCount = 0;
2001 
2002     /*Init decoding process*/
2003     JPEG_Init_Process(hjpeg);
2004 
2005     /* JPEG decoding process using DMA */
2006     if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK)
2007     {
2008       /* Update State */
2009       hjpeg->State = HAL_JPEG_STATE_ERROR;
2010       /* Process Unlocked */
2011       __HAL_UNLOCK(hjpeg);
2012 
2013       return HAL_ERROR;
2014     }
2015   }
2016   else
2017   {
2018     /* Process Unlocked */
2019     __HAL_UNLOCK(hjpeg);
2020 
2021     return HAL_BUSY;
2022   }
2023   /* Return function status */
2024   return HAL_OK;
2025 }
2026 
2027 /**
2028   * @brief  Pause the JPEG Input/Output processing
2029   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2030   *         the configuration information for JPEG module
2031   * @param  XferSelection This parameter can be one of the following values :
2032   *                           JPEG_PAUSE_RESUME_INPUT : Pause Input processing
2033   *                           JPEG_PAUSE_RESUME_OUTPUT: Pause Output processing
2034   *                           JPEG_PAUSE_RESUME_INPUT_OUTPUT: Pause Input and Output processing
2035   * @retval HAL status
2036   */
HAL_JPEG_Pause(JPEG_HandleTypeDef * hjpeg,uint32_t XferSelection)2037 HAL_StatusTypeDef  HAL_JPEG_Pause(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection)
2038 {
2039   uint32_t mask = 0;
2040 
2041   assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection));
2042 
2043   if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
2044   {
2045     if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
2046     {
2047       hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT;
2048       mask |= JPEG_DMA_IDMA;
2049     }
2050     if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
2051     {
2052       hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT;
2053       mask |= JPEG_DMA_ODMA;
2054     }
2055     JPEG_DISABLE_DMA(hjpeg, mask);
2056 
2057   }
2058   else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
2059   {
2060 
2061     if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
2062     {
2063       hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT;
2064       mask |= (JPEG_IT_IFT | JPEG_IT_IFNF);
2065     }
2066     if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
2067     {
2068       hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT;
2069       mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC);
2070     }
2071     __HAL_JPEG_DISABLE_IT(hjpeg, mask);
2072 
2073   }
2074   else
2075   {
2076     /* Nothing to do */
2077   }
2078 
2079   /* Return function status */
2080   return HAL_OK;
2081 }
2082 
2083 /**
2084   * @brief  Resume the JPEG Input/Output processing
2085   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2086   *         the configuration information for JPEG module
2087   * @param  XferSelection This parameter can be one of the following values :
2088   *                           JPEG_PAUSE_RESUME_INPUT : Resume Input processing
2089   *                           JPEG_PAUSE_RESUME_OUTPUT: Resume Output processing
2090   *                           JPEG_PAUSE_RESUME_INPUT_OUTPUT: Resume Input and Output processing
2091   * @retval HAL status
2092   */
HAL_JPEG_Resume(JPEG_HandleTypeDef * hjpeg,uint32_t XferSelection)2093 HAL_StatusTypeDef  HAL_JPEG_Resume(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection)
2094 {
2095   uint32_t mask = 0;
2096 
2097   assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection));
2098 
2099   if ((hjpeg->Context & (JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)) == 0UL)
2100   {
2101     /* if nothing paused to resume return error*/
2102     return HAL_ERROR;
2103   }
2104 
2105   if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
2106   {
2107 
2108     if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
2109     {
2110       hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT);
2111       mask |= JPEG_DMA_IDMA;
2112 
2113       /*JPEG Input DMA transfer data number must be multiple of DMA buffer size
2114         as the destination is a 32 bits register */
2115       hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL);
2116 
2117       if (hjpeg->InDataLength > 0UL)
2118       {
2119         /* Start DMA FIFO In transfer */
2120         if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
2121                              hjpeg->InDataLength) != HAL_OK)
2122         {
2123           hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
2124           hjpeg->State = HAL_JPEG_STATE_ERROR;
2125           return HAL_ERROR;
2126         }
2127       }
2128     }
2129     if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
2130     {
2131       hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT);
2132 
2133       if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL)
2134       {
2135         JPEG_DMA_PollResidualData(hjpeg);
2136       }
2137       else
2138       {
2139         mask |= JPEG_DMA_ODMA;
2140 
2141         /* Start DMA FIFO Out transfer */
2142         if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
2143                              hjpeg->OutDataLength) != HAL_OK)
2144         {
2145           hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
2146           hjpeg->State = HAL_JPEG_STATE_ERROR;
2147           return HAL_ERROR;
2148         }
2149       }
2150 
2151     }
2152     JPEG_ENABLE_DMA(hjpeg, mask);
2153 
2154   }
2155   else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
2156   {
2157     if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
2158     {
2159       hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT);
2160       mask |= (JPEG_IT_IFT | JPEG_IT_IFNF);
2161     }
2162     if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
2163     {
2164       hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT);
2165       mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC);
2166     }
2167     __HAL_JPEG_ENABLE_IT(hjpeg, mask);
2168 
2169   }
2170   else
2171   {
2172     /* Nothing to do */
2173   }
2174 
2175   /* Return function status */
2176   return HAL_OK;
2177 }
2178 
2179 /**
2180   * @brief  Config Encoding/Decoding Input Buffer.
2181   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2182   *         the configuration information for JPEG module.
2183   * @param  pNewInputBuffer Pointer to the new input data buffer
2184   * @param  InDataLength Size in bytes of the new Input data buffer
2185   * @retval HAL status
2186   */
HAL_JPEG_ConfigInputBuffer(JPEG_HandleTypeDef * hjpeg,uint8_t * pNewInputBuffer,uint32_t InDataLength)2187 void HAL_JPEG_ConfigInputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewInputBuffer, uint32_t InDataLength)
2188 {
2189   hjpeg->pJpegInBuffPtr =  pNewInputBuffer;
2190   hjpeg->InDataLength = InDataLength;
2191 }
2192 
2193 /**
2194   * @brief  Config Encoding/Decoding Output Buffer.
2195   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2196   *         the configuration information for JPEG module.
2197   * @param  pNewOutputBuffer Pointer to the new output data buffer
2198   * @param  OutDataLength Size in bytes of the new Output data buffer
2199   * @retval HAL status
2200   */
HAL_JPEG_ConfigOutputBuffer(JPEG_HandleTypeDef * hjpeg,uint8_t * pNewOutputBuffer,uint32_t OutDataLength)2201 void HAL_JPEG_ConfigOutputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewOutputBuffer, uint32_t OutDataLength)
2202 {
2203   hjpeg->pJpegOutBuffPtr = pNewOutputBuffer;
2204   hjpeg->OutDataLength = OutDataLength;
2205 }
2206 
2207 /**
2208   * @brief  Aborts the JPEG Encoding/Decoding.
2209   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2210   *         the configuration information for JPEG module
2211   * @retval HAL status
2212   */
HAL_JPEG_Abort(JPEG_HandleTypeDef * hjpeg)2213 HAL_StatusTypeDef HAL_JPEG_Abort(JPEG_HandleTypeDef *hjpeg)
2214 {
2215   uint32_t tickstart;
2216   uint32_t tmpContext;
2217   tmpContext = hjpeg->Context;
2218 
2219   /*Reset the Context operation and method*/
2220   hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA);
2221 
2222   if ((tmpContext & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
2223   {
2224     /* Stop the DMA In/out Xfer*/
2225     if (HAL_DMA_Abort(hjpeg->hdmaout) != HAL_OK)
2226     {
2227       if (hjpeg->hdmaout->ErrorCode == HAL_DMA_ERROR_TIMEOUT)
2228       {
2229         hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
2230       }
2231     }
2232     if (HAL_DMA_Abort(hjpeg->hdmain) != HAL_OK)
2233     {
2234       if (hjpeg->hdmain->ErrorCode == HAL_DMA_ERROR_TIMEOUT)
2235       {
2236         hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
2237       }
2238     }
2239 
2240   }
2241 
2242   /* Stop the JPEG encoding/decoding process*/
2243   hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
2244 
2245   /* Get tick */
2246   tickstart = HAL_GetTick();
2247 
2248   /* Check if the JPEG Codec is effectively disabled */
2249   while (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_COF) != 0UL)
2250   {
2251     /* Check for the Timeout */
2252     if ((HAL_GetTick() - tickstart) > JPEG_TIMEOUT_VALUE)
2253     {
2254       /* Update error code */
2255       hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;
2256 
2257       /* Change the DMA state */
2258       hjpeg->State = HAL_JPEG_STATE_ERROR;
2259       break;
2260     }
2261   }
2262 
2263   /* Disable All Interrupts */
2264   __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
2265 
2266   /* Disable All DMA requests */
2267   JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK);
2268 
2269   /* Flush input and output FIFOs*/
2270   hjpeg->Instance->CR |= JPEG_CR_IFF;
2271   hjpeg->Instance->CR |= JPEG_CR_OFF;
2272 
2273   /* Clear all flags */
2274   __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);
2275 
2276   /* Reset JpegInCount and JpegOutCount */
2277   hjpeg->JpegInCount = 0;
2278   hjpeg->JpegOutCount = 0;
2279 
2280   /*Reset the Context Pause*/
2281   hjpeg->Context &= ~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT);
2282 
2283   /* Change the DMA state*/
2284   if (hjpeg->ErrorCode != HAL_JPEG_ERROR_NONE)
2285   {
2286     hjpeg->State = HAL_JPEG_STATE_ERROR;
2287     /* Process Unlocked */
2288     __HAL_UNLOCK(hjpeg);
2289     /* Return function status */
2290     return HAL_ERROR;
2291   }
2292   else
2293   {
2294     hjpeg->State = HAL_JPEG_STATE_READY;
2295     /* Process Unlocked */
2296     __HAL_UNLOCK(hjpeg);
2297     /* Return function status */
2298     return HAL_OK;
2299   }
2300 
2301 }
2302 
2303 
2304 /**
2305   * @}
2306   */
2307 
2308 /** @defgroup JPEG_Exported_Functions_Group4 JPEG Decode/Encode callback functions
2309   *  @brief   JPEG process callback functions.
2310   *
2311 @verbatim
2312   ==============================================================================
2313               #####  JPEG Decode and Encode callback functions  #####
2314   ==============================================================================
2315     [..]  This section provides callback functions:
2316       (+) HAL_JPEG_InfoReadyCallback()  : Decoding JPEG Info ready callback
2317       (+) HAL_JPEG_EncodeCpltCallback() : Encoding complete callback.
2318       (+) HAL_JPEG_DecodeCpltCallback() : Decoding complete callback.
2319       (+) HAL_JPEG_ErrorCallback()      : JPEG error callback.
2320       (+) HAL_JPEG_GetDataCallback()    : Get New Data chunk callback.
2321       (+) HAL_JPEG_DataReadyCallback()  : Decoded/Encoded Data ready  callback.
2322 
2323 @endverbatim
2324   * @{
2325   */
2326 
2327 /**
2328   * @brief  Decoding JPEG Info ready callback.
2329   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2330   *         the configuration information for JPEG module
2331   * @param  pInfo pointer to a JPEG_ConfTypeDef structure that contains
2332   *         The JPEG decoded header information
2333   * @retval None
2334   */
HAL_JPEG_InfoReadyCallback(JPEG_HandleTypeDef * hjpeg,JPEG_ConfTypeDef * pInfo)2335 __weak void HAL_JPEG_InfoReadyCallback(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo)
2336 {
2337   /* Prevent unused argument(s) compilation warning */
2338   UNUSED(hjpeg);
2339   UNUSED(pInfo);
2340 
2341   /* NOTE : This function Should not be modified, when the callback is needed,
2342             the HAL_JPEG_HeaderParsingCpltCallback could be implemented in the user file
2343    */
2344 }
2345 
2346 /**
2347   * @brief  Encoding complete callback.
2348   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2349   *         the configuration information for JPEG module
2350   * @retval None
2351   */
HAL_JPEG_EncodeCpltCallback(JPEG_HandleTypeDef * hjpeg)2352 __weak void HAL_JPEG_EncodeCpltCallback(JPEG_HandleTypeDef *hjpeg)
2353 {
2354   /* Prevent unused argument(s) compilation warning */
2355   UNUSED(hjpeg);
2356 
2357   /* NOTE : This function Should not be modified, when the callback is needed,
2358             the HAL_JPEG_EncodeCpltCallback could be implemented in the user file
2359    */
2360 }
2361 
2362 /**
2363   * @brief  Decoding complete callback.
2364   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2365   *         the configuration information for JPEG module
2366   * @retval None
2367   */
HAL_JPEG_DecodeCpltCallback(JPEG_HandleTypeDef * hjpeg)2368 __weak void HAL_JPEG_DecodeCpltCallback(JPEG_HandleTypeDef *hjpeg)
2369 {
2370   /* Prevent unused argument(s) compilation warning */
2371   UNUSED(hjpeg);
2372 
2373   /* NOTE : This function Should not be modified, when the callback is needed,
2374             the HAL_JPEG_EncodeCpltCallback could be implemented in the user file
2375    */
2376 }
2377 
2378 /**
2379   * @brief  JPEG error callback.
2380   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2381   *         the configuration information for JPEG module
2382   * @retval None
2383   */
HAL_JPEG_ErrorCallback(JPEG_HandleTypeDef * hjpeg)2384 __weak void HAL_JPEG_ErrorCallback(JPEG_HandleTypeDef *hjpeg)
2385 {
2386   /* Prevent unused argument(s) compilation warning */
2387   UNUSED(hjpeg);
2388 
2389   /* NOTE : This function Should not be modified, when the callback is needed,
2390             the HAL_JPEG_ErrorCallback could be implemented in the user file
2391    */
2392 }
2393 
2394 /**
2395   * @brief  Get New Data chunk callback.
2396   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2397   *         the configuration information for JPEG module
2398   * @param  NbDecodedData Number of consumed data in the previous chunk in bytes
2399   * @retval None
2400   */
HAL_JPEG_GetDataCallback(JPEG_HandleTypeDef * hjpeg,uint32_t NbDecodedData)2401 __weak void HAL_JPEG_GetDataCallback(JPEG_HandleTypeDef *hjpeg, uint32_t NbDecodedData)
2402 {
2403   /* Prevent unused argument(s) compilation warning */
2404   UNUSED(hjpeg);
2405   UNUSED(NbDecodedData);
2406 
2407   /* NOTE : This function Should not be modified, when the callback is needed,
2408             the HAL_JPEG_GetDataCallback could be implemented in the user file
2409    */
2410 }
2411 
2412 /**
2413   * @brief  Decoded/Encoded Data ready  callback.
2414   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2415   *         the configuration information for JPEG module
2416   * @param  pDataOut pointer to the output data buffer
2417   * @param  OutDataLength number in bytes of data available in the specified output buffer
2418   * @retval None
2419   */
HAL_JPEG_DataReadyCallback(JPEG_HandleTypeDef * hjpeg,uint8_t * pDataOut,uint32_t OutDataLength)2420 __weak void HAL_JPEG_DataReadyCallback(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataOut, uint32_t OutDataLength)
2421 {
2422   /* Prevent unused argument(s) compilation warning */
2423   UNUSED(hjpeg);
2424   UNUSED(pDataOut);
2425   UNUSED(OutDataLength);
2426 
2427   /* NOTE : This function Should not be modified, when the callback is needed,
2428             the HAL_JPEG_DataReadyCallback could be implemented in the user file
2429    */
2430 }
2431 
2432 /**
2433   * @}
2434   */
2435 
2436 
2437 /** @defgroup JPEG_Exported_Functions_Group5 JPEG IRQ handler management
2438   *  @brief   JPEG IRQ handler.
2439   *
2440 @verbatim
2441   ==============================================================================
2442                 ##### JPEG IRQ handler management #####
2443   ==============================================================================
2444     [..]  This section provides JPEG IRQ handler function.
2445       (+) HAL_JPEG_IRQHandler()  : handles JPEG interrupt request
2446 
2447 @endverbatim
2448   * @{
2449   */
2450 
2451 /**
2452   * @brief  This function handles JPEG interrupt request.
2453   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2454   *         the configuration information for JPEG module
2455   * @retval None
2456   */
HAL_JPEG_IRQHandler(JPEG_HandleTypeDef * hjpeg)2457 void HAL_JPEG_IRQHandler(JPEG_HandleTypeDef *hjpeg)
2458 {
2459   switch (hjpeg->State)
2460   {
2461     case HAL_JPEG_STATE_BUSY_ENCODING:
2462     case HAL_JPEG_STATE_BUSY_DECODING:
2463       /* continue JPEG data encoding/Decoding*/
2464       /* JPEG data processing : In/Out FIFO transfer*/
2465       if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
2466       {
2467         (void) JPEG_Process(hjpeg);
2468       }
2469       else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
2470       {
2471         JPEG_DMA_ContinueProcess(hjpeg);
2472       }
2473       else
2474       {
2475         /* Nothing to do */
2476       }
2477       break;
2478 
2479     default:
2480       break;
2481   }
2482 }
2483 
2484 /**
2485   * @}
2486   */
2487 
2488 /** @defgroup JPEG_Exported_Functions_Group6 Peripheral State functions
2489   *  @brief   Peripheral State functions.
2490   *
2491 @verbatim
2492   ==============================================================================
2493                     ##### Peripheral State and Error functions #####
2494   ==============================================================================
2495     [..]  This section provides JPEG State and Errors function.
2496       (+) HAL_JPEG_GetState()  : permits to get in run-time the JPEG state.
2497       (+) HAL_JPEG_GetError()  : Returns the JPEG error code if any.
2498 
2499 @endverbatim
2500   * @{
2501   */
2502 
2503 /**
2504   * @brief  Returns the JPEG state.
2505   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2506   *         the configuration information for JPEG module
2507   * @retval JPEG state
2508   */
HAL_JPEG_GetState(const JPEG_HandleTypeDef * hjpeg)2509 HAL_JPEG_STATETypeDef HAL_JPEG_GetState(const JPEG_HandleTypeDef *hjpeg)
2510 {
2511   return hjpeg->State;
2512 }
2513 
2514 /**
2515   * @brief  Return the JPEG error code
2516   * @param  hjpeg  pointer to a JPEG_HandleTypeDef structure that contains
2517   *              the configuration information for the specified JPEG.
2518   * @retval JPEG Error Code
2519   */
HAL_JPEG_GetError(const JPEG_HandleTypeDef * hjpeg)2520 uint32_t HAL_JPEG_GetError(const JPEG_HandleTypeDef *hjpeg)
2521 {
2522   return hjpeg->ErrorCode;
2523 }
2524 
2525 /**
2526   * @}
2527   */
2528 
2529 /**
2530   * @}
2531   */
2532 
2533 
2534 /** @addtogroup JPEG_Private_Functions
2535   * @{
2536   */
2537 
2538 /**
2539   * @brief  Generates Huffman sizes/Codes Table from Bits/vals Table
2540   * @param  Bits pointer to bits table
2541   * @param  Huffsize pointer to sizes table
2542   * @param  Huffcode pointer to codes table
2543   * @param  LastK pointer to last Coeff (table dimension)
2544   * @retval HAL status
2545   */
JPEG_Bits_To_SizeCodes(const uint8_t * Bits,uint8_t * Huffsize,uint32_t * Huffcode,uint32_t * LastK)2546 static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode,
2547                                                 uint32_t *LastK)
2548 {
2549   uint32_t i;
2550   uint32_t j;
2551   uint32_t k;
2552   uint32_t code;
2553   uint32_t si;
2554 
2555   /* Figure C.1: Generation of table of Huffman code sizes */
2556   j = 0;
2557   for (k = 0; k < 16UL; k++)
2558   {
2559     i = (uint32_t)Bits[k];
2560     if ((j + i) > 256UL)
2561     {
2562       /* check for table overflow */
2563       return HAL_ERROR;
2564     }
2565     while (i != 0UL)
2566     {
2567       Huffsize[j] = (uint8_t) k + 1U;
2568       j++;
2569       i--;
2570     }
2571   }
2572   Huffsize[j] = 0;
2573   *LastK = j;
2574 
2575   /* Figure C.2: Generation of table of Huffman codes */
2576   code = 0;
2577   si = Huffsize[0];
2578   j = 0;
2579   while (Huffsize[j] != 0U)
2580   {
2581     while (((uint32_t) Huffsize[j]) == si)
2582     {
2583       Huffcode[j] = code;
2584       j++;
2585       code++;
2586     }
2587     /* code must fit in "size" bits (si), no code is allowed to be all ones*/
2588     if (si > 31UL)
2589     {
2590       return HAL_ERROR;
2591     }
2592     if (((uint32_t) code) >= (((uint32_t) 1) << si))
2593     {
2594       return HAL_ERROR;
2595     }
2596     code <<= 1;
2597     si++;
2598   }
2599   /* Return function status */
2600   return HAL_OK;
2601 }
2602 
2603 /**
2604   * @brief  Transform a Bits/Vals AC Huffman table to sizes/Codes huffman Table
2605   *         that can programmed to the JPEG encoder registers
2606   * @param  AC_BitsValsTable pointer to AC huffman bits/vals table
2607   * @param  AC_SizeCodesTable pointer to AC huffman Sizes/Codes table
2608   * @retval HAL status
2609   */
JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef * AC_BitsValsTable,JPEG_AC_HuffCodeTableTypeDef * AC_SizeCodesTable)2610 static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable,
2611                                                            JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable)
2612 {
2613   HAL_StatusTypeDef error;
2614   uint8_t huffsize[257];
2615   uint32_t huffcode[257];
2616   uint32_t k;
2617   uint32_t i;
2618   uint32_t lsb;
2619   uint32_t msb;
2620   uint32_t lastK;
2621 
2622   error = JPEG_Bits_To_SizeCodes(AC_BitsValsTable->Bits, huffsize, huffcode, &lastK);
2623   if (error != HAL_OK)
2624   {
2625     return  error;
2626   }
2627 
2628   /* Figure C.3: Ordering procedure for encoding procedure code tables */
2629   k = 0;
2630 
2631   while (k < lastK)
2632   {
2633     i = AC_BitsValsTable->HuffVal[k];
2634     if (i == 0UL)
2635     {
2636       i = JPEG_AC_HUFF_TABLE_SIZE - 2UL; /*i = 0x00 EOB code*/
2637     }
2638     else if (i == 0xF0UL) /* i = 0xF0 ZRL code*/
2639     {
2640       i = JPEG_AC_HUFF_TABLE_SIZE - 1UL;
2641     }
2642     else
2643     {
2644       msb = (i & 0xF0UL) >> 4;
2645       lsb = (i & 0x0FUL);
2646       i = (msb * 10UL) + lsb - 1UL;
2647     }
2648     if (i >= JPEG_AC_HUFF_TABLE_SIZE)
2649     {
2650       return HAL_ERROR; /* Huffman Table overflow error*/
2651     }
2652     else
2653     {
2654       AC_SizeCodesTable->HuffmanCode[i] = huffcode[k];
2655       AC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U;
2656       k++;
2657     }
2658   }
2659 
2660   /* Return function status */
2661   return HAL_OK;
2662 }
2663 
2664 /**
2665   * @brief  Transform a Bits/Vals DC Huffman table to sizes/Codes huffman Table
2666   *         that can programmed to the JPEG encoder registers
2667   * @param  DC_BitsValsTable pointer to DC huffman bits/vals table
2668   * @param  DC_SizeCodesTable pointer to DC huffman Sizes/Codes table
2669   * @retval HAL status
2670   */
JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef * DC_BitsValsTable,JPEG_DC_HuffCodeTableTypeDef * DC_SizeCodesTable)2671 static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable,
2672                                                            JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable)
2673 {
2674   HAL_StatusTypeDef error;
2675 
2676   uint32_t k;
2677   uint32_t i;
2678   uint32_t lastK;
2679   uint8_t huffsize[257];
2680   uint32_t huffcode[257];
2681   error = JPEG_Bits_To_SizeCodes(DC_BitsValsTable->Bits, huffsize, huffcode, &lastK);
2682   if (error != HAL_OK)
2683   {
2684     return  error;
2685   }
2686   /* Figure C.3: ordering procedure for encoding procedure code tables */
2687   k = 0;
2688 
2689   while (k < lastK)
2690   {
2691     i = DC_BitsValsTable->HuffVal[k];
2692     if (i >= JPEG_DC_HUFF_TABLE_SIZE)
2693     {
2694       return HAL_ERROR; /* Huffman Table overflow error*/
2695     }
2696     else
2697     {
2698       DC_SizeCodesTable->HuffmanCode[i] = huffcode[k];
2699       DC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U;
2700       k++;
2701     }
2702   }
2703 
2704   /* Return function status */
2705   return HAL_OK;
2706 }
2707 
2708 /**
2709   * @brief  Set the JPEG register with an DC huffman table at the given DC table address
2710   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2711   *         the configuration information for JPEG module
2712   * @param  HuffTableDC pointer to DC huffman table
2713   * @param  DCTableAddress Encoder DC huffman table address it could be HUFFENC_DC0 or HUFFENC_DC1.
2714   * @retval HAL status
2715   */
JPEG_Set_HuffDC_Mem(JPEG_HandleTypeDef * hjpeg,JPEG_DCHuffTableTypeDef * HuffTableDC,const __IO uint32_t * DCTableAddress)2716 static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC,
2717                                              const __IO uint32_t *DCTableAddress)
2718 {
2719   HAL_StatusTypeDef error;
2720   JPEG_DC_HuffCodeTableTypeDef dcSizeCodesTable;
2721   uint32_t i;
2722   uint32_t lsb;
2723   uint32_t msb;
2724   __IO uint32_t *address;
2725   __IO uint32_t *addressDef;
2726 
2727   if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC0))
2728   {
2729     address = (hjpeg->Instance->HUFFENC_DC0 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL));
2730   }
2731   else if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC1))
2732   {
2733     address = (hjpeg->Instance->HUFFENC_DC1 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL));
2734   }
2735   else
2736   {
2737     return HAL_ERROR;
2738   }
2739 
2740   if (HuffTableDC != NULL)
2741   {
2742     error = JPEG_DCHuff_BitsVals_To_SizeCodes(HuffTableDC, &dcSizeCodesTable);
2743     if (error != HAL_OK)
2744     {
2745       return  error;
2746     }
2747     addressDef = address;
2748     *addressDef = 0x0FFF0FFF;
2749     addressDef++;
2750     *addressDef = 0x0FFF0FFF;
2751 
2752     i = JPEG_DC_HUFF_TABLE_SIZE;
2753     while (i > 1UL)
2754     {
2755       i--;
2756       address --;
2757       msb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) |
2758             ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL);
2759       i--;
2760       lsb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) |
2761             ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL);
2762 
2763       *address = lsb | (msb << 16);
2764     }
2765   }
2766 
2767   /* Return function status */
2768   return HAL_OK;
2769 }
2770 
2771 /**
2772   * @brief  Set the JPEG register with an AC huffman table at the given AC table address
2773   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2774   *         the configuration information for JPEG module
2775   * @param  HuffTableAC pointer to AC huffman table
2776   * @param  ACTableAddress Encoder AC huffman table address it could be HUFFENC_AC0 or HUFFENC_AC1.
2777   * @retval HAL status
2778   */
JPEG_Set_HuffAC_Mem(JPEG_HandleTypeDef * hjpeg,JPEG_ACHuffTableTypeDef * HuffTableAC,const __IO uint32_t * ACTableAddress)2779 static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC,
2780                                              const __IO uint32_t *ACTableAddress)
2781 {
2782   HAL_StatusTypeDef error;
2783   JPEG_AC_HuffCodeTableTypeDef acSizeCodesTable;
2784   uint32_t i;
2785   uint32_t lsb;
2786   uint32_t msb;
2787   __IO uint32_t *address;
2788   __IO uint32_t *addressDef;
2789 
2790   if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC0))
2791   {
2792     address = (hjpeg->Instance->HUFFENC_AC0 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL));
2793   }
2794   else if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC1))
2795   {
2796     address = (hjpeg->Instance->HUFFENC_AC1 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL));
2797   }
2798   else
2799   {
2800     return HAL_ERROR;
2801   }
2802 
2803   if (HuffTableAC != NULL)
2804   {
2805     error = JPEG_ACHuff_BitsVals_To_SizeCodes(HuffTableAC, &acSizeCodesTable);
2806     if (error != HAL_OK)
2807     {
2808       return  error;
2809     }
2810     /* Default values settings: 162:167 FFFh , 168:175 FD0h_FD7h */
2811     /* Locations 162:175 of each AC table contain information used internally by the core */
2812 
2813     addressDef = address;
2814     for (i = 0; i < 3UL; i++)
2815     {
2816       *addressDef = 0x0FFF0FFF;
2817       addressDef++;
2818     }
2819     *addressDef = 0x0FD10FD0;
2820     addressDef++;
2821     *addressDef = 0x0FD30FD2;
2822     addressDef++;
2823     *addressDef = 0x0FD50FD4;
2824     addressDef++;
2825     *addressDef = 0x0FD70FD6;
2826     /* end of Locations 162:175  */
2827 
2828 
2829     i = JPEG_AC_HUFF_TABLE_SIZE;
2830     while (i > 1UL)
2831     {
2832       i--;
2833       address--;
2834       msb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) |
2835             ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL);
2836       i--;
2837       lsb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) |
2838             ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL);
2839 
2840       *address = lsb | (msb << 16);
2841     }
2842   }
2843 
2844   /* Return function status */
2845   return HAL_OK;
2846 }
2847 
2848 /**
2849   * @brief  Configure the JPEG encoder register huffman tables to used during
2850   *         the encdoing operation
2851   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2852   *         the configuration information for JPEG module
2853   * @retval None
2854   */
JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef * hjpeg)2855 static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg)
2856 {
2857   HAL_StatusTypeDef error;
2858 
2859   JPEG_Set_Huff_DHTMem(hjpeg);
2860   error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable,
2861                               (hjpeg->Instance->HUFFENC_AC0));
2862   if (error != HAL_OK)
2863   {
2864     return  error;
2865   }
2866 
2867   error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable,
2868                               (hjpeg->Instance->HUFFENC_AC1));
2869   if (error != HAL_OK)
2870   {
2871     return  error;
2872   }
2873 
2874   error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable,
2875                               hjpeg->Instance->HUFFENC_DC0);
2876   if (error != HAL_OK)
2877   {
2878     return  error;
2879   }
2880 
2881   error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable,
2882                               hjpeg->Instance->HUFFENC_DC1);
2883   if (error != HAL_OK)
2884   {
2885     return  error;
2886   }
2887   /* Return function status */
2888   return HAL_OK;
2889 }
2890 
2891 /**
2892   * @brief  Configure the JPEG register huffman tables to be included in the JPEG
2893   *         file header (used for encoding only)
2894   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
2895   *         the configuration information for JPEG module
2896   * @retval None
2897   */
JPEG_Set_Huff_DHTMem(JPEG_HandleTypeDef * hjpeg)2898 static void JPEG_Set_Huff_DHTMem(JPEG_HandleTypeDef *hjpeg)
2899 {
2900   JPEG_ACHuffTableTypeDef *HuffTableAC0 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable;
2901   JPEG_ACHuffTableTypeDef *HuffTableAC1 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable;
2902   JPEG_DCHuffTableTypeDef *HuffTableDC0 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable;
2903   JPEG_DCHuffTableTypeDef *HuffTableDC1 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable;
2904   uint32_t value;
2905   uint32_t index;
2906   __IO uint32_t *address;
2907 
2908   /* DC0 Huffman Table : BITS*/
2909   /* DC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address to DHTMEM + 3*/
2910   address = (hjpeg->Instance->DHTMEM + 3);
2911   index = 16;
2912   while (index > 3UL)
2913   {
2914 
2915     *address = (((uint32_t)HuffTableDC0->Bits[index - 1UL] & 0xFFUL) << 24) |
2916                (((uint32_t)HuffTableDC0->Bits[index - 2UL] & 0xFFUL) << 16) |
2917                (((uint32_t)HuffTableDC0->Bits[index - 3UL] & 0xFFUL) << 8) |
2918                ((uint32_t)HuffTableDC0->Bits[index - 4UL] & 0xFFUL);
2919     address--;
2920     index -= 4UL;
2921 
2922   }
2923   /* DC0 Huffman Table : Val*/
2924   /* DC0 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +4 to DHTMEM + 6 */
2925   address = (hjpeg->Instance->DHTMEM + 6);
2926   index = 12;
2927   while (index > 3UL)
2928   {
2929     *address = (((uint32_t)HuffTableDC0->HuffVal[index - 1UL] & 0xFFUL) << 24) |
2930                (((uint32_t)HuffTableDC0->HuffVal[index - 2UL] & 0xFFUL) << 16) |
2931                (((uint32_t)HuffTableDC0->HuffVal[index - 3UL] & 0xFFUL) << 8) |
2932                ((uint32_t)HuffTableDC0->HuffVal[index - 4UL] & 0xFFUL);
2933     address--;
2934     index -= 4UL;
2935   }
2936 
2937   /* AC0 Huffman Table : BITS*/
2938   /* AC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 7 to DHTMEM + 10*/
2939   address = (hjpeg->Instance->DHTMEM + 10UL);
2940   index = 16;
2941   while (index > 3UL)
2942   {
2943 
2944     *address = (((uint32_t)HuffTableAC0->Bits[index - 1UL] & 0xFFUL) << 24) |
2945                (((uint32_t)HuffTableAC0->Bits[index - 2UL] & 0xFFUL) << 16) |
2946                (((uint32_t)HuffTableAC0->Bits[index - 3UL] & 0xFFUL) << 8) |
2947                ((uint32_t)HuffTableAC0->Bits[index - 4UL] & 0xFFUL);
2948     address--;
2949     index -= 4UL;
2950 
2951   }
2952   /* AC0 Huffman Table : Val*/
2953   /* AC0 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 11 to DHTMEM + 51 */
2954   /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 51) belong to AC0 VALS table */
2955   address = (hjpeg->Instance->DHTMEM + 51);
2956   value = *address & 0xFFFF0000U;
2957   value = value | (((uint32_t)HuffTableAC0->HuffVal[161] & 0xFFUL) << 8) |
2958           ((uint32_t)HuffTableAC0->HuffVal[160] & 0xFFUL);
2959   *address = value;
2960 
2961   /*continue setting 160 AC0 huffman values */
2962   address--; /* address = hjpeg->Instance->DHTMEM + 50*/
2963   index = JPEG_AC_HUFF_TABLE_SIZE - 2UL;
2964   while (index > 3UL)
2965   {
2966     *address = (((uint32_t)HuffTableAC0->HuffVal[index - 1UL] & 0xFFUL) << 24) |
2967                (((uint32_t)HuffTableAC0->HuffVal[index - 2UL] & 0xFFUL) << 16) |
2968                (((uint32_t)HuffTableAC0->HuffVal[index - 3UL] & 0xFFUL) << 8) |
2969                ((uint32_t)HuffTableAC0->HuffVal[index - 4UL] & 0xFFUL);
2970     address--;
2971     index -= 4UL;
2972   }
2973 
2974   /* DC1 Huffman Table : BITS*/
2975   /* DC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM + 51 base address to DHTMEM + 55*/
2976   /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 51) belong to DC1 Bits table */
2977   address = (hjpeg->Instance->DHTMEM + 51);
2978   value = *address & 0x0000FFFFU;
2979   value = value | (((uint32_t)HuffTableDC1->Bits[1] & 0xFFUL) << 24) |
2980           (((uint32_t)HuffTableDC1->Bits[0] & 0xFFUL) << 16);
2981   *address = value;
2982 
2983   /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 55) belong to DC1 Bits table */
2984   address = (hjpeg->Instance->DHTMEM + 55);
2985   value = *address & 0xFFFF0000U;
2986   value = value | (((uint32_t)HuffTableDC1->Bits[15] & 0xFFUL) << 8) |
2987           ((uint32_t)HuffTableDC1->Bits[14] & 0xFFUL);
2988   *address = value;
2989 
2990   /*continue setting 12 DC1 huffman Bits from DHTMEM + 54 down to DHTMEM + 52*/
2991   address--;
2992   index = 12;
2993   while (index > 3UL)
2994   {
2995 
2996     *address = (((uint32_t)HuffTableDC1->Bits[index + 1UL] & 0xFFUL) << 24) |
2997                (((uint32_t)HuffTableDC1->Bits[index] & 0xFFUL) << 16) |
2998                (((uint32_t)HuffTableDC1->Bits[index - 1UL] & 0xFFUL) << 8) |
2999                ((uint32_t)HuffTableDC1->Bits[index - 2UL] & 0xFFUL);
3000     address--;
3001     index -= 4UL;
3002 
3003   }
3004   /* DC1 Huffman Table : Val*/
3005   /* DC1 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +55 to DHTMEM + 58 */
3006   /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 55) belong to DC1 Val table */
3007   address = (hjpeg->Instance->DHTMEM + 55);
3008   value = *address & 0x0000FFFFUL;
3009   value = value | (((uint32_t)HuffTableDC1->HuffVal[1] & 0xFFUL) << 24) |
3010           (((uint32_t)HuffTableDC1->HuffVal[0] & 0xFFUL) << 16);
3011   *address = value;
3012 
3013   /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 58) belong to DC1 Val table */
3014   address = (hjpeg->Instance->DHTMEM + 58);
3015   value = *address & 0xFFFF0000UL;
3016   value = value | (((uint32_t)HuffTableDC1->HuffVal[11] & 0xFFUL) << 8) |
3017           ((uint32_t)HuffTableDC1->HuffVal[10] & 0xFFUL);
3018   *address = value;
3019 
3020   /*continue setting 8 DC1 huffman val from DHTMEM + 57 down to DHTMEM + 56*/
3021   address--;
3022   index = 8;
3023   while (index > 3UL)
3024   {
3025     *address = (((uint32_t)HuffTableDC1->HuffVal[index + 1UL] & 0xFFUL) << 24) |
3026                (((uint32_t)HuffTableDC1->HuffVal[index] & 0xFFUL) << 16) |
3027                (((uint32_t)HuffTableDC1->HuffVal[index - 1UL] & 0xFFUL) << 8) |
3028                ((uint32_t)HuffTableDC1->HuffVal[index - 2UL] & 0xFFUL);
3029     address--;
3030     index -= 4UL;
3031   }
3032 
3033   /* AC1 Huffman Table : BITS*/
3034   /* AC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 58 to DHTMEM + 62*/
3035   /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 58) belong to AC1 Bits table */
3036   address = (hjpeg->Instance->DHTMEM + 58);
3037   value = *address & 0x0000FFFFU;
3038   value = value | (((uint32_t)HuffTableAC1->Bits[1] & 0xFFUL) << 24) |
3039           (((uint32_t)HuffTableAC1->Bits[0] & 0xFFUL) << 16);
3040   *address = value;
3041 
3042   /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 62) belong to Bits Val table */
3043   address = (hjpeg->Instance->DHTMEM + 62);
3044   value = *address & 0xFFFF0000U;
3045   value = value | (((uint32_t)HuffTableAC1->Bits[15] & 0xFFUL) << 8) | ((uint32_t)HuffTableAC1->Bits[14] & 0xFFUL);
3046   *address = value;
3047 
3048   /*continue setting 12 AC1 huffman Bits from DHTMEM + 61 down to DHTMEM + 59*/
3049   address--;
3050   index = 12;
3051   while (index > 3UL)
3052   {
3053 
3054     *address = (((uint32_t)HuffTableAC1->Bits[index + 1UL] & 0xFFUL) << 24) |
3055                (((uint32_t)HuffTableAC1->Bits[index] & 0xFFUL) << 16) |
3056                (((uint32_t)HuffTableAC1->Bits[index - 1UL] & 0xFFUL) << 8) |
3057                ((uint32_t)HuffTableAC1->Bits[index - 2UL] & 0xFFUL);
3058     address--;
3059     index -= 4UL;
3060 
3061   }
3062   /* AC1 Huffman Table : Val*/
3063   /* AC1 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 62 to DHTMEM + 102 */
3064   /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 62) belong to AC1 VALS table */
3065   address = (hjpeg->Instance->DHTMEM + 62);
3066   value = *address & 0x0000FFFFUL;
3067   value = value | (((uint32_t)HuffTableAC1->HuffVal[1] & 0xFFUL) << 24) |
3068           (((uint32_t)HuffTableAC1->HuffVal[0] & 0xFFUL) << 16);
3069   *address = value;
3070 
3071   /*continue setting 160 AC1 huffman values from DHTMEM + 63 to DHTMEM+102 */
3072   address = (hjpeg->Instance->DHTMEM + 102);
3073   index = JPEG_AC_HUFF_TABLE_SIZE - 2UL;
3074   while (index > 3UL)
3075   {
3076     *address = (((uint32_t)HuffTableAC1->HuffVal[index + 1UL] & 0xFFUL) << 24) |
3077                (((uint32_t)HuffTableAC1->HuffVal[index] & 0xFFUL) << 16) |
3078                (((uint32_t)HuffTableAC1->HuffVal[index - 1UL] & 0xFFUL) << 8) |
3079                ((uint32_t)HuffTableAC1->HuffVal[index - 2UL] & 0xFFUL);
3080     address--;
3081     index -= 4UL;
3082   }
3083 
3084 }
3085 
3086 /**
3087   * @brief  Configure the JPEG registers with a given quantization table
3088   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3089   *         the configuration information for JPEG module
3090   * @param  QTable pointer to an array of 64 bytes giving the quantization table
3091   * @param  QTableAddress destination quantization address in the JPEG peripheral
3092   *         it could be QMEM0, QMEM1, QMEM2 or QMEM3
3093   * @retval 0 if no error, 1 if error
3094   */
JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef * hjpeg,const uint8_t * QTable,__IO uint32_t * QTableAddress)3095 static uint32_t JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable,
3096                                           __IO uint32_t *QTableAddress)
3097 {
3098   uint32_t i;
3099   uint32_t j;
3100   uint32_t quantRow;
3101   uint32_t quantVal;
3102   uint32_t ScaleFactor;
3103   __IO uint32_t *tableAddress;
3104 
3105   tableAddress = QTableAddress;
3106 
3107   if ((hjpeg->Conf.ImageQuality >= 50UL) && (hjpeg->Conf.ImageQuality <= 100UL))
3108   {
3109     ScaleFactor = JPEG_HIGH_QUALITY_REFERENCE - (hjpeg->Conf.ImageQuality * 2UL);
3110   }
3111   else if (hjpeg->Conf.ImageQuality > 0UL)
3112   {
3113     ScaleFactor = JPEG_LOW_QUALITY_REFERENCE / ((uint32_t) hjpeg->Conf.ImageQuality);
3114   }
3115   else
3116   {
3117     return 1UL;
3118   }
3119 
3120   /*Quantization_table = (Standard_quanization_table * ScaleFactor + 50) / 100*/
3121   i = 0;
3122   while (i < (JPEG_QUANT_TABLE_SIZE - 3UL))
3123   {
3124     quantRow = 0;
3125     for (j = 0; j < 4UL; j++)
3126     {
3127       /* Note that the quantization coefficients must be specified in the table in zigzag order */
3128       quantVal = ((((uint32_t) QTable[JPEG_ZIGZAG_ORDER[i + j]]) * ScaleFactor) + 50UL) / 100UL;
3129 
3130       if (quantVal == 0UL)
3131       {
3132         quantVal = 1UL;
3133       }
3134       else if (quantVal > 255UL)
3135       {
3136         quantVal = JPEG_QUANTVAL_MAX;
3137       }
3138       else
3139       {
3140         /* Nothing to do, keep same value of quantVal */
3141       }
3142 
3143       quantRow |= ((quantVal & 0xFFUL) << (8UL * j));
3144     }
3145 
3146     i += 4UL;
3147     *tableAddress = quantRow;
3148     tableAddress ++;
3149   }
3150 
3151   /* Return function status */
3152   return 0UL;
3153 }
3154 
3155 /**
3156   * @brief  Configure the JPEG registers for YCbCr color space
3157   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3158   *         the configuration information for JPEG module
3159   * @retval None
3160   */
JPEG_SetColorYCBCR(JPEG_HandleTypeDef * hjpeg)3161 static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg)
3162 {
3163   uint32_t ySamplingH;
3164   uint32_t ySamplingV;
3165   uint32_t yblockNb;
3166 
3167   /*Set Number of color components to 3*/
3168   hjpeg->Instance->CONFR1 &=  ~JPEG_CONFR1_NF;
3169   hjpeg->Instance->CONFR1 |=  JPEG_CONFR1_NF_1;
3170 
3171   /* compute MCU block size and Y, Cb ,Cr sampling factors*/
3172   if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING)
3173   {
3174     ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
3175     ySamplingV  = JPEG_CONFR4_VSF_1;   /* Vs = 2*/
3176 
3177     yblockNb  = 0x30; /* 4 blocks of 8x8*/
3178   }
3179   else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING)
3180   {
3181     ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
3182     ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/
3183 
3184     yblockNb  = 0x10; /* 2 blocks of 8x8*/
3185   }
3186   else /*JPEG_444_SUBSAMPLING and default*/
3187   {
3188     ySamplingH  = JPEG_CONFR4_HSF_0;   /* Hs = 1*/
3189     ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/
3190 
3191     yblockNb  = 0; /* 1 block of 8x8*/
3192   }
3193 
3194   hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS);
3195   hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF_1 | JPEG_CONFR1_NS_1);
3196 
3197   /*Reset CONFR4 register*/
3198   hjpeg->Instance->CONFR4 =  0;
3199   /*Set Horizental and Vertical  sampling factor , number of blocks,
3200    Quantization table and Huffman AC/DC tables for component 0*/
3201   hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB));
3202 
3203   /*Reset CONFR5 register*/
3204   hjpeg->Instance->CONFR5 =  0;
3205   /*Set Horizental and Vertical  sampling factor , number of blocks,
3206     Quantization table and Huffman AC/DC tables for component 1*/
3207   hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0 | JPEG_CONFR5_QT_0 | JPEG_CONFR5_HA |
3208                               JPEG_CONFR5_HD);
3209 
3210   /*Reset CONFR6 register*/
3211   hjpeg->Instance->CONFR6 =  0;
3212   /*Set Horizental and Vertical  sampling factor and number of blocks for component 2*/
3213   /* In YCBCR , by default, both chrominance components (component 1 and component 2)
3214      use the same Quantization table (table 1) */
3215   /* In YCBCR , both chrominance components (component 1 and component 2) use the same Huffman tables (table 1) */
3216   hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0 | JPEG_CONFR6_QT_0 | JPEG_CONFR6_HA |
3217                               JPEG_CONFR6_HD);
3218 
3219 }
3220 
3221 /**
3222   * @brief  Configure the JPEG registers for GrayScale color space
3223   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3224   *         the configuration information for JPEG module
3225   * @retval None
3226   */
JPEG_SetColorGrayScale(JPEG_HandleTypeDef * hjpeg)3227 static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg)
3228 {
3229   /*Set Number of color components to 1*/
3230   hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS);
3231 
3232   /*in GrayScale use 1 single Quantization table (Table 0)*/
3233   /*in GrayScale use only one couple of AC/DC huffman table (table 0)*/
3234 
3235   /*Reset CONFR4 register*/
3236   hjpeg->Instance->CONFR4 =  0;
3237   /*Set Horizental and Vertical  sampling factor , number of blocks,
3238     Quantization table and Huffman AC/DC tables for component 0*/
3239   hjpeg->Instance->CONFR4 |=  JPEG_CONFR4_HSF_0 | JPEG_CONFR4_VSF_0 ;
3240 }
3241 
3242 /**
3243   * @brief  Configure the JPEG registers for CMYK color space
3244   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3245   *         the configuration information for JPEG module
3246   * @retval None
3247   */
JPEG_SetColorCMYK(JPEG_HandleTypeDef * hjpeg)3248 static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg)
3249 {
3250   uint32_t ySamplingH;
3251   uint32_t ySamplingV;
3252   uint32_t yblockNb;
3253 
3254   /*Set Number of color components to 4*/
3255   hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF | JPEG_CONFR1_NS);
3256 
3257   /* compute MCU block size and Y, Cb ,Cr sampling factors*/
3258   if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING)
3259   {
3260     ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
3261     ySamplingV  = JPEG_CONFR4_VSF_1;   /* Vs = 2*/
3262 
3263     yblockNb  = 0x30; /* 4 blocks of 8x8*/
3264   }
3265   else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING)
3266   {
3267     ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
3268     ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/
3269 
3270     yblockNb  = 0x10; /* 2 blocks of 8x8*/
3271   }
3272   else /*JPEG_444_SUBSAMPLING and default*/
3273   {
3274     ySamplingH  = JPEG_CONFR4_HSF_0;   /* Hs = 1*/
3275     ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/
3276 
3277     yblockNb  = 0; /* 1 block of 8x8*/
3278   }
3279 
3280   /*Reset CONFR4 register*/
3281   hjpeg->Instance->CONFR4 =  0;
3282   /*Set Horizental and Vertical  sampling factor , number of blocks,
3283     Quantization table and Huffman AC/DC tables for component 0*/
3284   hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB));
3285 
3286   /*Reset CONFR5 register*/
3287   hjpeg->Instance->CONFR5 =  0;
3288   /*Set Horizental and Vertical  sampling factor , number of blocks,
3289     Quantization table and Huffman AC/DC tables for component 1*/
3290   hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0);
3291 
3292   /*Reset CONFR6 register*/
3293   hjpeg->Instance->CONFR6 =  0;
3294   /*Set Horizental and Vertical  sampling factor , number of blocks,
3295     Quantization table and Huffman AC/DC tables for component 2*/
3296   hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0);
3297 
3298   /*Reset CONFR7 register*/
3299   hjpeg->Instance->CONFR7 =  0;
3300   /*Set Horizental and Vertical  sampling factor , number of blocks,
3301     Quantization table and Huffman AC/DC tables for component 3*/
3302   hjpeg->Instance->CONFR7 |= (JPEG_CONFR7_HSF_0 | JPEG_CONFR7_VSF_0);
3303 }
3304 
3305 /**
3306   * @brief  Init the JPEG encoding/decoding process in case of Polling or Interrupt and DMA
3307   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3308   *         the configuration information for JPEG module
3309   * @retval None
3310   */
JPEG_Init_Process(JPEG_HandleTypeDef * hjpeg)3311 static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg)
3312 {
3313   /*Reset pause*/
3314   hjpeg->Context &= (~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT));
3315 
3316   if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
3317   {
3318     /*Set JPEG Codec to Decoding mode */
3319     hjpeg->Instance->CONFR1 |= JPEG_CONFR1_DE;
3320   }
3321   else /* JPEG_CONTEXT_ENCODE */
3322   {
3323     /*Set JPEG Codec to Encoding mode */
3324     hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_DE;
3325   }
3326 
3327   /*Stop JPEG processing */
3328   hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
3329 
3330   /* Disable All Interrupts */
3331   __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
3332 
3333   /* Disable All DMA requests */
3334   JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK);
3335   /* Flush input and output FIFOs*/
3336   hjpeg->Instance->CR |= JPEG_CR_IFF;
3337   hjpeg->Instance->CR |= JPEG_CR_OFF;
3338 
3339   /* Clear all flags */
3340   __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);
3341 
3342   /*Start Encoding/Decoding*/
3343   hjpeg->Instance->CONFR0 |=  JPEG_CONFR0_START;
3344 
3345   if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
3346   {
3347     /*Enable IN/OUT, end of Conversation, and end of header parsing interruptions*/
3348     __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_IFT | JPEG_IT_IFNF | JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC | JPEG_IT_HPD);
3349   }
3350   else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
3351   {
3352     /*Enable End Of Conversation, and End Of Header parsing interruptions*/
3353     __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);
3354 
3355   }
3356   else
3357   {
3358     /* Nothing to do */
3359   }
3360 }
3361 
3362 /**
3363   * @brief  JPEG encoding/decoding process in case of Polling or Interrupt
3364   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3365   *         the configuration information for JPEG module
3366   * @retval JPEG_PROCESS_DONE if the process has ends else JPEG_PROCESS_ONGOING
3367   */
JPEG_Process(JPEG_HandleTypeDef * hjpeg)3368 static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg)
3369 {
3370   uint32_t tmpContext;
3371 
3372   /*End of header processing flag */
3373   if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
3374   {
3375     if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL)
3376     {
3377       /*Call Header parsing complete callback */
3378       (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf);
3379       /* Reset the ImageQuality */
3380       hjpeg->Conf.ImageQuality = 0;
3381       /* Note : the image quality is only available at the end of the decoding operation */
3382       /* at the current stage the calculated image quality is not correct so reset it */
3383 
3384       /*Call Info Ready callback */
3385 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3386       hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf);
3387 #else
3388       HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf);
3389 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3390 
3391       __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD);
3392 
3393       /* Clear header processing done flag */
3394       __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF);
3395     }
3396   }
3397 
3398   /*Input FIFO status handling*/
3399   if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL)
3400   {
3401     if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFTF) != 0UL)
3402     {
3403       /*Input FIFO threshold flag */
3404       /*JPEG_FIFO_TH_SIZE words can be written in */
3405       JPEG_ReadInputData(hjpeg, JPEG_FIFO_TH_SIZE);
3406     }
3407     else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFNFF) != 0UL)
3408     {
3409       /*Input FIFO Not Full flag */
3410       /*32-bit value can be written in */
3411       JPEG_ReadInputData(hjpeg, 1);
3412     }
3413     else
3414     {
3415       /* Nothing to do */
3416     }
3417   }
3418 
3419 
3420   /*Output FIFO flag handling*/
3421   if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
3422   {
3423     if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFTF) != 0UL)
3424     {
3425       /*Output FIFO threshold flag */
3426       /*JPEG_FIFO_TH_SIZE words can be read out */
3427       JPEG_StoreOutputData(hjpeg, JPEG_FIFO_TH_SIZE);
3428     }
3429     else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL)
3430     {
3431       /*Output FIFO Not Empty flag */
3432       /*32-bit value can be read out */
3433       JPEG_StoreOutputData(hjpeg, 1);
3434     }
3435     else
3436     {
3437       /* Nothing to do */
3438     }
3439   }
3440 
3441   /*End of Conversion handling :i.e EOC flag is high and OFTF low and OFNEF low*/
3442   if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF | JPEG_FLAG_OFTF | JPEG_FLAG_OFNEF) == JPEG_FLAG_EOCF)
3443   {
3444     /*Stop Encoding/Decoding*/
3445     hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
3446 
3447     if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
3448     {
3449       /* Disable All Interrupts */
3450       __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
3451     }
3452 
3453     /* Clear all flags */
3454     __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);
3455 
3456     /*Call End of conversion callback */
3457     if (hjpeg->JpegOutCount > 0UL)
3458     {
3459       /*Output Buffer is not empty, call DecodedDataReadyCallback*/
3460 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3461       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3462 #else
3463       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3464 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3465 
3466       hjpeg->JpegOutCount = 0;
3467     }
3468 
3469     /*Reset Context Operation*/
3470     tmpContext = hjpeg->Context;
3471     /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
3472     hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);
3473 
3474     /* Process Unlocked */
3475     __HAL_UNLOCK(hjpeg);
3476 
3477     /* Change the JPEG state */
3478     hjpeg->State = HAL_JPEG_STATE_READY;
3479 
3480     /*Call End of Encoding/Decoding callback */
3481     if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
3482     {
3483 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3484       hjpeg->DecodeCpltCallback(hjpeg);
3485 #else
3486       HAL_JPEG_DecodeCpltCallback(hjpeg);
3487 #endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
3488     }
3489     else /* JPEG_CONTEXT_ENCODE */
3490     {
3491 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3492       hjpeg->EncodeCpltCallback(hjpeg);
3493 #else
3494       HAL_JPEG_EncodeCpltCallback(hjpeg);
3495 #endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
3496     }
3497 
3498     return JPEG_PROCESS_DONE;
3499   }
3500 
3501 
3502   return JPEG_PROCESS_ONGOING;
3503 }
3504 
3505 /**
3506   * @brief  Store some output data from the JPEG peripheral to the output buffer.
3507   *         This function is used when the JPEG peripheral has new data to output
3508   *         in case of Polling or Interrupt process
3509   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3510   *         the configuration information for JPEG module
3511   * @param  nbOutputWords Number of output words (of 32 bits) ready from the JPEG peripheral
3512   * @retval None
3513   */
JPEG_StoreOutputData(JPEG_HandleTypeDef * hjpeg,uint32_t nbOutputWords)3514 static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords)
3515 {
3516   uint32_t index;
3517   uint32_t nb_words;
3518   uint32_t nb_bytes;
3519   uint32_t dataword;
3520 
3521   if (hjpeg->OutDataLength >= (hjpeg->JpegOutCount + (nbOutputWords * 4UL)))
3522   {
3523     for (index = 0; index < nbOutputWords; index++)
3524     {
3525       /*Transfer 32 bits from the JPEG output FIFO*/
3526       dataword = hjpeg->Instance->DOR;
3527       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL);
3528       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8);
3529       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16);
3530       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24);
3531       hjpeg->JpegOutCount += 4UL;
3532     }
3533     if (hjpeg->OutDataLength == hjpeg->JpegOutCount)
3534     {
3535       /*Output Buffer is full, call DecodedDataReadyCallback*/
3536 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3537       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3538 #else
3539       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3540 #endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
3541       hjpeg->JpegOutCount = 0;
3542     }
3543   }
3544   else if (hjpeg->OutDataLength > hjpeg->JpegOutCount)
3545   {
3546     nb_words = (hjpeg->OutDataLength - hjpeg->JpegOutCount) / 4UL;
3547     for (index = 0; index < nb_words; index++)
3548     {
3549       /*Transfer 32 bits from the JPEG output FIFO*/
3550       dataword = hjpeg->Instance->DOR;
3551       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL);
3552       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8);
3553       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16);
3554       hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24);
3555       hjpeg->JpegOutCount += 4UL;
3556     }
3557     if (hjpeg->OutDataLength == hjpeg->JpegOutCount)
3558     {
3559       /*Output Buffer is full, call DecodedDataReadyCallback*/
3560 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3561       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3562 #else
3563       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3564 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3565       hjpeg->JpegOutCount = 0;
3566     }
3567     else
3568     {
3569       nb_bytes = hjpeg->OutDataLength - hjpeg->JpegOutCount;
3570       dataword = hjpeg->Instance->DOR;
3571       for (index = 0; index < nb_bytes; index++)
3572       {
3573         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * (index & 0x3UL))) & 0xFFUL);
3574         hjpeg->JpegOutCount++;
3575       }
3576       /*Output Buffer is full, call DecodedDataReadyCallback*/
3577 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3578       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3579 #else
3580       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3581 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3582 
3583       hjpeg->JpegOutCount = 0;
3584 
3585       nb_bytes = 4UL - nb_bytes;
3586       for (index = nb_bytes; index < 4UL; index++)
3587       {
3588         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * index)) & 0xFFUL);
3589         hjpeg->JpegOutCount++;
3590       }
3591     }
3592   }
3593   else
3594   {
3595     /* Nothing to do */
3596   }
3597 }
3598 
3599 /**
3600   * @brief  Read some input Data from the input buffer.
3601   *         This function is used when the JPEG peripheral needs new data
3602   *         in case of Polling or Interrupt process
3603   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3604   *         the configuration information for JPEG module
3605   * @param  nbRequestWords Number of input words (of 32 bits) that the JPE peripheral request
3606   * @retval None
3607   */
JPEG_ReadInputData(JPEG_HandleTypeDef * hjpeg,uint32_t nbRequestWords)3608 static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords)
3609 {
3610   uint32_t nb_bytes = 0;
3611   uint32_t nb_words;
3612   uint32_t index;
3613   uint32_t dataword;
3614   uint32_t input_count;
3615 
3616   if ((hjpeg->InDataLength == 0UL) || (nbRequestWords == 0UL))
3617   {
3618     /* No more Input data : nothing to do*/
3619     (void) HAL_JPEG_Pause(hjpeg, JPEG_PAUSE_RESUME_INPUT);
3620   }
3621   else if (hjpeg->InDataLength > hjpeg->JpegInCount)
3622   {
3623     nb_bytes = hjpeg->InDataLength - hjpeg->JpegInCount;
3624   }
3625   else if (hjpeg->InDataLength == hjpeg->JpegInCount)
3626   {
3627     /*Call HAL_JPEG_GetDataCallback to get new data */
3628 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3629     hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount);
3630 #else
3631     HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount);
3632 #endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
3633 
3634     if (hjpeg->InDataLength > 4UL)
3635     {
3636       hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL;
3637     }
3638     hjpeg->JpegInCount = 0;
3639     nb_bytes = hjpeg->InDataLength;
3640   }
3641   else
3642   {
3643     /* Nothing to do */
3644   }
3645   if (((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (nb_bytes > 0UL))
3646   {
3647     nb_words = nb_bytes / 4UL;
3648     if (nb_words >= nbRequestWords)
3649     {
3650       for (index = 0; index < nbRequestWords; index++)
3651       {
3652         input_count = hjpeg->JpegInCount;
3653         hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \
3654                                 (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \
3655                                 (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \
3656                                 (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24));
3657 
3658         hjpeg->JpegInCount += 4UL;
3659       }
3660     }
3661     else /*nb_words < nbRequestWords*/
3662     {
3663       if (nb_words > 0UL)
3664       {
3665         for (index = 0; index < nb_words; index++)
3666         {
3667           input_count = hjpeg->JpegInCount;
3668           hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \
3669                                   (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \
3670                                   (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \
3671                                   (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24));
3672 
3673           hjpeg->JpegInCount += 4UL;
3674         }
3675       }
3676       else
3677       {
3678         /* end of file*/
3679         dataword = 0;
3680         for (index = 0; index < nb_bytes; index++)
3681         {
3682           dataword |= (uint32_t)hjpeg->pJpegInBuffPtr[hjpeg->JpegInCount] << (8UL * (index & 0x03UL));
3683           hjpeg->JpegInCount++;
3684         }
3685         hjpeg->Instance->DIR = dataword;
3686       }
3687     }
3688   }
3689 }
3690 
3691 /**
3692   * @brief  Start the JPEG DMA process (encoding/decoding)
3693   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3694   *         the configuration information for JPEG module
3695   * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING
3696   */
JPEG_DMA_StartProcess(JPEG_HandleTypeDef * hjpeg)3697 static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg)
3698 {
3699   if ((hjpeg->InDataLength < 4UL) || (hjpeg->OutDataLength < 4UL))
3700   {
3701     return HAL_ERROR;
3702   }
3703   /* Reset Ending DMA internal context flag*/
3704   hjpeg->Context &= ~JPEG_CONTEXT_ENDING_DMA;
3705 
3706   /* Disable DMA In/Out Request*/
3707   JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA);
3708 
3709   /* Set the JPEG DMA In transfer complete callback */
3710   hjpeg->hdmain->XferCpltCallback = JPEG_DMAInCpltCallback;
3711   /* Set the DMA In error callback */
3712   hjpeg->hdmain->XferErrorCallback = JPEG_DMAErrorCallback;
3713 
3714   /* Set the JPEG DMA Out transfer complete callback */
3715   hjpeg->hdmaout->XferCpltCallback = JPEG_DMAOutCpltCallback;
3716   /* Set the DMA Out error callback */
3717   hjpeg->hdmaout->XferErrorCallback = JPEG_DMAErrorCallback;
3718   /* Set the DMA Out Abort callback */
3719   hjpeg->hdmaout->XferAbortCallback = JPEG_DMAOutAbortCallback;
3720 
3721   /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/
3722   hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL);
3723 
3724   /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/
3725   hjpeg->OutDataLength = hjpeg->OutDataLength - (hjpeg->OutDataLength % 4UL);
3726 
3727   if ((hjpeg->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
3728   {
3729     if (hjpeg->hdmain->LinkedListQueue != NULL)
3730     {
3731       /* Set DMA data size */
3732       hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->InDataLength;
3733 
3734       /* Set DMA source address */
3735       hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegInBuffPtr;
3736 
3737       /* Set DMA destination address */
3738       hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DIR;
3739 
3740       if (HAL_DMAEx_List_Start_IT(hjpeg->hdmain) != HAL_OK)
3741       {
3742         return HAL_ERROR;
3743       }
3744     }
3745     else
3746     {
3747       /* Set the JPEG State to ready */
3748       hjpeg->State = HAL_JPEG_STATE_READY;
3749 
3750       /* Update JPEG error code */
3751       hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
3752 
3753       /* Process Unlocked */
3754       __HAL_UNLOCK(hjpeg);
3755 
3756       return HAL_ERROR;
3757     }
3758   }
3759   else
3760   {
3761     /* Start DMA FIFO In transfer */
3762     if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
3763                          hjpeg->InDataLength)  != HAL_OK)
3764     {
3765       hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
3766       return HAL_ERROR;
3767     }
3768   }
3769 
3770   if ((hjpeg->hdmaout->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
3771   {
3772     if (hjpeg->hdmaout->LinkedListQueue != NULL)
3773     {
3774       /* Set DMA data size */
3775       hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->OutDataLength;
3776 
3777       /* Set DMA source address */
3778       hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DOR;
3779 
3780       /* Set DMA destination address */
3781       hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegOutBuffPtr;
3782 
3783       if (HAL_DMAEx_List_Start_IT(hjpeg->hdmaout) != HAL_OK)
3784       {
3785         return HAL_ERROR;
3786       }
3787     }
3788     else
3789     {
3790       /* Set the JPEG State to ready */
3791       hjpeg->State = HAL_JPEG_STATE_READY;
3792 
3793       /* Update JPEG error code */
3794       hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
3795 
3796       /* Process Unlocked */
3797       __HAL_UNLOCK(hjpeg);
3798 
3799       return HAL_ERROR;
3800     }
3801   }
3802   else
3803   {
3804     /* Start DMA FIFO Out transfer */
3805     if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
3806                          hjpeg->OutDataLength)  != HAL_OK)
3807     {
3808       hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
3809       return HAL_ERROR;
3810     }
3811   }
3812 
3813   /* Enable JPEG In/Out DMA requests*/
3814   JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA | JPEG_DMA_ODMA);
3815 
3816   return HAL_OK;
3817 }
3818 
3819 /**
3820   * @brief  Continue the current JPEG DMA process (encoding/decoding)
3821   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3822   *         the configuration information for JPEG module
3823   * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING
3824   */
JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef * hjpeg)3825 static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg)
3826 {
3827   /*End of header processing flag rises*/
3828   if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
3829   {
3830     if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL)
3831     {
3832       /*Call Header parsing complete callback */
3833       (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf);
3834 
3835       /* Reset the ImageQuality */
3836       hjpeg->Conf.ImageQuality = 0;
3837       /* Note : the image quality is only available at the end of the decoding operation */
3838       /* at the current stage the calculated image quality is not correct so reset it */
3839 
3840       /*Call Info Ready callback */
3841 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3842       hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf);
3843 #else
3844       HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf);
3845 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3846 
3847       __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD);
3848 
3849       /* Clear header processing done flag */
3850       __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF);
3851     }
3852   }
3853 
3854   /*End of Conversion handling*/
3855   if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) != 0UL)
3856   {
3857     /*Disabkle JPEG In/Out DMA Requests*/
3858     JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA);
3859 
3860     hjpeg->Context |= JPEG_CONTEXT_ENDING_DMA;
3861 
3862     /*Stop Encoding/Decoding*/
3863     hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
3864 
3865     __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
3866 
3867     /* Clear all flags */
3868     __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);
3869 
3870     if (hjpeg->hdmain->State == HAL_DMA_STATE_BUSY)
3871     {
3872       /* Stop the DMA In Xfer*/
3873       (void) HAL_DMA_Abort(hjpeg->hdmain);
3874     }
3875 
3876     if (hjpeg->hdmaout->State == HAL_DMA_STATE_BUSY)
3877     {
3878       /* Stop the DMA out Xfer*/
3879       (void) HAL_DMA_Abort(hjpeg->hdmaout);
3880     }
3881 
3882     JPEG_DMA_EndProcess(hjpeg);
3883   }
3884 
3885 
3886 }
3887 
3888 /**
3889   * @brief  Finalize the current JPEG DMA process (encoding/decoding)
3890   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3891   *         the configuration information for JPEG module
3892   * @retval JPEG_PROCESS_DONE
3893   */
JPEG_DMA_EndProcess(JPEG_HandleTypeDef * hjpeg)3894 static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg)
3895 {
3896   uint32_t tmpContext;
3897   hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hjpeg->hdmaout);
3898 
3899   /*if Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
3900   if (hjpeg->JpegOutCount == hjpeg->OutDataLength)
3901   {
3902 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3903     hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3904 #else
3905     HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3906 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3907 
3908     hjpeg->JpegOutCount = 0;
3909   }
3910 
3911   /*Check if remaining data in the output FIFO*/
3912   if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL)
3913   {
3914     if (hjpeg->JpegOutCount > 0UL)
3915     {
3916       /*Output Buffer is not empty, call DecodedDataReadyCallback*/
3917 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3918       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3919 #else
3920       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3921 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3922 
3923       hjpeg->JpegOutCount = 0;
3924     }
3925 
3926     /*Stop Encoding/Decoding*/
3927     hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
3928 
3929     tmpContext = hjpeg->Context;
3930     /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
3931     hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);
3932 
3933     /* Process Unlocked */
3934     __HAL_UNLOCK(hjpeg);
3935 
3936     /* Change the JPEG state */
3937     hjpeg->State = HAL_JPEG_STATE_READY;
3938 
3939     /*Call End of Encoding/Decoding callback */
3940     if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
3941     {
3942 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3943       hjpeg->DecodeCpltCallback(hjpeg);
3944 #else
3945       HAL_JPEG_DecodeCpltCallback(hjpeg);
3946 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3947     }
3948     else /* JPEG_CONTEXT_ENCODE */
3949     {
3950 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3951       hjpeg->EncodeCpltCallback(hjpeg);
3952 #else
3953       HAL_JPEG_EncodeCpltCallback(hjpeg);
3954 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
3955     }
3956   }
3957   else if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
3958   {
3959     JPEG_DMA_PollResidualData(hjpeg);
3960   }
3961   else
3962   {
3963     /* Nothing to do */
3964   }
3965 
3966 }
3967 
3968 /**
3969   * @brief  Poll residual output data when DMA process (encoding/decoding)
3970   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
3971   *         the configuration information for JPEG module
3972   * @retval None.
3973   */
JPEG_DMA_PollResidualData(JPEG_HandleTypeDef * hjpeg)3974 static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg)
3975 {
3976   uint32_t tmpContext;
3977   uint32_t count;
3978   uint32_t dataOut;
3979 
3980   for (count = JPEG_FIFO_SIZE; count > 0UL; count--)
3981   {
3982     if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
3983     {
3984       if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL)
3985       {
3986         dataOut = hjpeg->Instance->DOR;
3987         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataOut & 0x000000FFUL);
3988         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataOut & 0x0000FF00UL) >> 8);
3989         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataOut & 0x00FF0000UL) >> 16);
3990         hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataOut & 0xFF000000UL) >> 24);
3991         hjpeg->JpegOutCount += 4UL;
3992 
3993         if (hjpeg->JpegOutCount == hjpeg->OutDataLength)
3994         {
3995           /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
3996 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
3997           hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
3998 #else
3999           HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
4000 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4001 
4002           hjpeg->JpegOutCount = 0;
4003         }
4004 
4005       }
4006     }
4007   }
4008 
4009   tmpContext = hjpeg->Context;
4010 
4011   if ((__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) || ((tmpContext & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL))
4012   {
4013     /*Stop Encoding/Decoding*/
4014     hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
4015 
4016     if (hjpeg->JpegOutCount > 0UL)
4017     {
4018       /*Output Buffer is not empty, call DecodedDataReadyCallback*/
4019 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4020       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
4021 #else
4022       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
4023 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4024 
4025       hjpeg->JpegOutCount = 0;
4026     }
4027 
4028     tmpContext = hjpeg->Context;
4029     /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
4030     hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);
4031 
4032     /* Process Unlocked */
4033     __HAL_UNLOCK(hjpeg);
4034 
4035     /* Change the JPEG state */
4036     hjpeg->State = HAL_JPEG_STATE_READY;
4037 
4038     /*Call End of Encoding/Decoding callback */
4039     if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
4040     {
4041 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4042       hjpeg->DecodeCpltCallback(hjpeg);
4043 #else
4044       HAL_JPEG_DecodeCpltCallback(hjpeg);
4045 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4046     }
4047     else /* JPEG_CONTEXT_ENCODE */
4048     {
4049 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4050       hjpeg->EncodeCpltCallback(hjpeg);
4051 #else
4052       HAL_JPEG_EncodeCpltCallback(hjpeg);
4053 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4054     }
4055   }
4056 }
4057 
4058 /**
4059   * @brief  DMA input transfer complete callback
4060   * @param  hdma pointer to a DMA_HandleTypeDef structure.
4061   * @retval None
4062   */
JPEG_DMAInCpltCallback(DMA_HandleTypeDef * hdma)4063 static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma)
4064 {
4065   JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
4066 
4067   /* Disable The JPEG IT so the DMA Input Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */
4068   __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
4069 
4070   if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) ==
4071       JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */
4072   {
4073     JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_IDMA);
4074 
4075     hjpeg->JpegInCount = hjpeg->InDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma);
4076 
4077     /*Call HAL_JPEG_GetDataCallback to get new data */
4078 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4079     hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount);
4080 #else
4081     HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount);
4082 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4083 
4084     if (hjpeg->InDataLength >= 4UL)
4085     {
4086       /*JPEG Input DMA transfer data number must be multiple of 32 bits word
4087         as the destination is a 32 bits (4 bytes) register */
4088       hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL;
4089     }
4090     else
4091     {
4092       /* Nothing to do */
4093     }
4094 
4095     if (((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (hjpeg->InDataLength > 0UL))
4096     {
4097       /* Start DMA FIFO In transfer */
4098       if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
4099                            hjpeg->InDataLength) != HAL_OK)
4100       {
4101         hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
4102         hjpeg->State = HAL_JPEG_STATE_ERROR;
4103 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4104         hjpeg->ErrorCallback(hjpeg);
4105 #else
4106         HAL_JPEG_ErrorCallback(hjpeg);
4107 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4108         return;
4109       }
4110       JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA);
4111     }
4112 
4113     /* JPEG Conversion still on going : Enable the JPEG IT */
4114     __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);
4115   }
4116 }
4117 
4118 /**
4119   * @brief  DMA output transfer complete callback
4120   * @param  hdma pointer to a DMA_HandleTypeDef structure.
4121   * @retval None
4122   */
JPEG_DMAOutCpltCallback(DMA_HandleTypeDef * hdma)4123 static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma)
4124 {
4125   JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
4126 
4127   /* Disable The JPEG IT so the DMA Output Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */
4128   __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
4129 
4130   if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) ==
4131       JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */
4132   {
4133     if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) == 0UL)
4134     {
4135       JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA);
4136       hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma);
4137 
4138       /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
4139 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4140       hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
4141 #else
4142       HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
4143 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4144 
4145       if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
4146       {
4147         /* Start DMA FIFO Out transfer */
4148         if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
4149                              hjpeg->OutDataLength) != HAL_OK)
4150         {
4151           hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
4152           hjpeg->State = HAL_JPEG_STATE_ERROR;
4153 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4154           hjpeg->ErrorCallback(hjpeg);
4155 #else
4156           HAL_JPEG_ErrorCallback(hjpeg);
4157 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4158           return;
4159         }
4160         JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_ODMA);
4161       }
4162     }
4163 
4164     /* JPEG Conversion still on going : Enable the JPEG IT */
4165     __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);
4166   }
4167 }
4168 
4169 
4170 /**
4171   * @brief  DMA Transfer error callback
4172   * @param  hdma pointer to a DMA_HandleTypeDef structure.
4173   * @retval None
4174   */
JPEG_DMAErrorCallback(DMA_HandleTypeDef * hdma)4175 static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma)
4176 {
4177   JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
4178 
4179   if (HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_NONE)
4180   {
4181     /*Stop Encoding/Decoding*/
4182     hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;
4183 
4184     /* Disable All Interrupts */
4185     __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
4186 
4187     /* Disable All DMA requests */
4188     JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK);
4189 
4190     hjpeg->State = HAL_JPEG_STATE_READY;
4191     hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
4192 #if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
4193     hjpeg->ErrorCallback(hjpeg);
4194 #else
4195     HAL_JPEG_ErrorCallback(hjpeg);
4196 #endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
4197   }
4198 }
4199 
4200 /**
4201   * @brief  DMA output Abort callback
4202   * @param  hdma pointer to a DMA_HandleTypeDef structure.
4203   * @retval None
4204   */
JPEG_DMAOutAbortCallback(DMA_HandleTypeDef * hdma)4205 static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma)
4206 {
4207   JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
4208 
4209   if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL)
4210   {
4211     JPEG_DMA_EndProcess(hjpeg);
4212   }
4213 }
4214 
4215 
4216 /**
4217   * @brief  Calculate the decoded image quality (from 1 to 100)
4218   * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
4219   *         the configuration information for JPEG module
4220   * @retval JPEG image quality from 1 to 100.
4221   */
JPEG_GetQuality(const JPEG_HandleTypeDef * hjpeg)4222 static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg)
4223 {
4224   uint32_t quality = 0;
4225   uint32_t quantRow;
4226   uint32_t quantVal;
4227   uint32_t scale;
4228   uint32_t i;
4229   uint32_t j;
4230   const __IO uint32_t *tableAddress = hjpeg->Instance->QMEM0;
4231 
4232   i = 0;
4233   while (i < (JPEG_QUANT_TABLE_SIZE - 3UL))
4234   {
4235     quantRow = *tableAddress;
4236     for (j = 0; j < 4UL; j++)
4237     {
4238       quantVal = (quantRow >> (8UL * j)) & 0xFFUL;
4239       if (quantVal == 1UL)
4240       {
4241         /* if Quantization value = 1 then quality is 100%*/
4242         quality += 100UL;
4243       }
4244       else
4245       {
4246         /* Note that the quantization coefficients must be specified in the table in zigzag order */
4247         scale = (quantVal * 100UL) / ((uint32_t) hjpeg->QuantTable0[JPEG_ZIGZAG_ORDER[i + j]]);
4248 
4249         if (scale <= 100UL)
4250         {
4251           quality += (200UL - scale) / 2UL;
4252         }
4253         else
4254         {
4255           quality += 5000UL / scale;
4256         }
4257       }
4258     }
4259 
4260     i += 4UL;
4261     tableAddress ++;
4262   }
4263 
4264   return (quality / 64UL);
4265 }
4266 /**
4267   * @}
4268   */
4269 
4270 /**
4271   * @}
4272   */
4273 #endif /* JPEG */
4274 #endif /* HAL_JPEG_MODULE_ENABLED */
4275 
4276 
4277 /**
4278   * @}
4279   */
4280