1 /*
2 * Copyright (c) 2017-2024, Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
21 */
22 //!
23 //! \file     codechal_encoder_base.h
24 //! \brief    Defines the encode interface for CodecHal.
25 //! \details  The encode interface is further sub-divided by standard, this file is for the base interface which is shared by all encode standards.
26 //!
27 
28 #ifndef __CODECHAL_ENCODER_BASE_H__
29 #define __CODECHAL_ENCODER_BASE_H__
30 
31 #include "codechal.h"
32 #include "codechal_setting.h"
33 #include "codechal_hw.h"
34 #include "codechal_debug.h"
35 #include "codechal_encode_sfc.h"
36 #include "codechal_encode_csc_ds.h"
37 #include "codechal_encode_tracked_buffer.h"
38 #include "codechal_encode_allocator.h"
39 #include "codechal_mmc.h"
40 #include "codechal_utilities.h"
41 #include "codec_def_encode.h"
42 #include "cm_rt_umd.h"
43 #include "media_perf_profiler.h"
44 #include <algorithm> // std::reverse
45 
46 //------------------------------------------------------------------------------
47 // Macros specific to MOS_CODEC_SUBCOMP_ENCODE sub-comp
48 //------------------------------------------------------------------------------
49 #define CODECHAL_ENCODE_ASSERT(_expr)                                                   \
50     MOS_ASSERT(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _expr)
51 
52 #define CODECHAL_ENCODE_ASSERTMESSAGE(_message, ...)                                    \
53     MOS_ASSERTMESSAGE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _message, ##__VA_ARGS__)
54 
55 #define CODECHAL_ENCODE_NORMALMESSAGE(_message, ...)                                    \
56     MOS_NORMALMESSAGE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _message, ##__VA_ARGS__)
57 
58 #define CODECHAL_ENCODE_VERBOSEMESSAGE(_message, ...)                                   \
59     MOS_VERBOSEMESSAGE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _message, ##__VA_ARGS__)
60 
61 #define CODECHAL_ENCODE_FUNCTION_ENTER                                                  \
62     MOS_FUNCTION_ENTER(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE)
63 
64 #define CODECHAL_ENCODE_CHK_STATUS(_stmt)                                               \
65     MOS_CHK_STATUS(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _stmt)
66 
67 #define CODECHAL_ENCODE_CHK_STATUS_MESSAGE(_stmt, _message, ...)                        \
68     MOS_CHK_STATUS_MESSAGE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _stmt, _message, ##__VA_ARGS__)
69 
70 #define CODECHAL_ENCODE_CHK_NULL(_ptr)                                                  \
71     MOS_CHK_NULL(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _ptr)
72 
73 #define CODECHAL_ENCODE_CHK_NULL_NO_STATUS(_ptr)                                        \
74     MOS_CHK_NULL_NO_STATUS(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _ptr)
75 
76 #define CODECHAL_ENCODE_CHK_COND(_expr, _message, ...)                           \
77     MOS_CHK_COND(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE,_expr,_message, ##__VA_ARGS__)
78 
79 #define CODECHAL_ENCODE_CHK_NULL_NO_STATUS_RETURN(_ptr)                                        \
80     MOS_CHK_NULL_NO_STATUS_RETURN(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _ptr)
81 
82 #define CODECHAL_ENCODE_CHK_NULL_RETURN(_ptr)                                                  \
83     MOS_CHK_NULL_RETURN(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _ptr)
84 
85 #define CODECHAL_ENCODE_CHK_STATUS_RETURN(_stmt)                                               \
86     MOS_CHK_STATUS_RETURN(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _stmt)
87 
88 #define CODECHAL_ENCODE_CHK_STATUS_MESSAGE_RETURN(_stmt, _message, ...)                        \
89     MOS_CHK_STATUS_MESSAGE_RETURN(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, _stmt, _message, ##__VA_ARGS__)
90 
91 #define CODECHAL_ENCODE_CHK_COND_RETURN(_expr, _message, ...)                           \
92     MOS_CHK_COND_RETURN(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE,_expr,_message, ##__VA_ARGS__)
93 
94 #define CODECHAL_ENCODE_CHK_NULL_WITH_DESTROY_RETURN(_ptr, destroyFunction) \
95     MOS_CHK_COND_WITH_DESTROY_RETURN_VALUE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, (nullptr == _ptr), destroyFunction, MOS_STATUS_NULL_POINTER, "error nullptr!")
96 
97 #define CODECHAL_ENCODE_CHK_STATUS_WITH_DESTROY_RETURN(_stmt, destroyFunction)                                                                                  \
98 {                                                                                                                                                               \
99     MOS_STATUS sts = (MOS_STATUS)(_stmt);                                                                                                                       \
100     MOS_CHK_COND_WITH_DESTROY_RETURN_VALUE(MOS_COMPONENT_CODEC, MOS_CODEC_SUBCOMP_ENCODE, (MOS_STATUS_SUCCESS != sts), destroyFunction, sts, "error status!")   \
101 }
102 
103 // User Feature Report Writeout
104 #define CodecHalEncode_WriteKey64(key, value, mosCtx)\
105 {\
106     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
107     UserFeatureWriteData.Value.i64Data  = (value);\
108     UserFeatureWriteData.ValueID        = (key);\
109     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
110 }
111 
112 #define CodecHalEncode_WriteKey(key, value, mosCtx)\
113 {\
114     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
115     UserFeatureWriteData.Value.i32Data  = (value);\
116     UserFeatureWriteData.ValueID        = (key);\
117     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
118 }
119 
120 #define CodecHalEncode_WriteStringKey(key, value, len, mosCtx)\
121 {\
122     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
123     UserFeatureWriteData.Value.StringData.pStringData = (value);\
124     UserFeatureWriteData.Value.StringData.uSize = (len);\
125     UserFeatureWriteData.ValueID        = (key);\
126     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
127 }
128 
129 //!
130 //! \brief Recycled buffers are buffers which are locked and populated each execute
131 //!        to be consumed by HW. The driver loops through these buffers, if for the
132 //!        current index it is detected that the buffers for that index are still in
133 //!        use by HW, the driver waits until the buffers are available. 6 of each
134 //!        recycled buffer type are allocated to achieve performance parity with the
135 //!        old method of not having any waits.
136 //!
137 #define CODECHAL_ENCODE_RECYCLED_BUFFER_NUM             6
138 
139 // Encode Sizes
140 #define CODECHAL_ENCODE_VME_BBUF_NUM                    2
141 #define CODECHAL_ENCODE_MIN_SCALED_SURFACE_SIZE         48
142 #define CODECHAL_ENCODE_BRC_PAK_STATISTICS_SIZE         64
143 #define CODECHAL_ENCODE_MAX_NUM_MAD_BUFFERS             CODEC_MAX_NUM_REF_FIELD
144 #define CODECHAL_VDENC_BRC_NUM_OF_PASSES                2
145 #define CODECHAL_VDENC_BRC_NUM_OF_PASSES_FOR_TILE_REPLAY 22
146 #define CODECHAL_DP_MAX_NUM_BRC_PASSES                  4
147 #define CODECHAL_VDENC_NUMIMEPREDICTORS                 8
148 #define CODECHAL_VDENC_NUMIMEPREDICTORS_SPEED           4
149 #define CODECHAL_VDENC_NUMIMEPREDICTORS_QUALITY         12
150 #define CODECHAL_CMDINITIALIZER_MAX_CMD_SIZE CODECHAL_CACHELINE_SIZE * 4
151 #define CODECHAL_ENCODE_NUM_MAX_VME_L0_REF              8 // multiref - G7.5+ - used from DDI
152 #define CODECHAL_ENCODE_NUM_MAX_VME_L1_REF              2 // multiref - G7.5+ - used from DDI
153 #define CODECHAL_ENCODE_ME_DATA_SIZE_MULTIPLIER         (CODECHAL_ENCODE_NUM_MAX_VME_L0_REF + CODECHAL_ENCODE_NUM_MAX_VME_L1_REF)
154 #define CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L0_REF        4 // multiref - G7.5+
155 #define CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L1_REF        1 // multiref - G7.5+
156 #define CODECHAL_VP9_MB_CODE_SIZE                       204
157 
158 // BRC
159 #define CODECHAL_ENCODE_MIN_BITS_PER_PIXEL              12  // 8b 420
160 #define CODECHAL_ENCODE_MAX_BITSTREAM_COMPRESSION       700
161 
162 typedef enum _CODECHAL_ENCODE_BRC_KERNEL_STATE_IDX
163 {
164     CODECHAL_ENCODE_BRC_IDX_INIT = 0,
165     CODECHAL_ENCODE_BRC_IDX_FrameBRC_UPDATE,
166     CODECHAL_ENCODE_BRC_IDX_RESET,
167     CODECHAL_ENCODE_BRC_IDX_IFRAMEDIST,
168     CODECHAL_ENCODE_BRC_IDX_BLOCKCOPY,
169     CODECHAL_ENCODE_BRC_IDX_MbBRC_UPDATE, // extra MbBRCUpdate kernel starting GEN9
170     CODECHAL_ENCODE_BRC_IDX_NUM
171 } CODECHAL_ENCODE_BRC_KERNEL_STATE_IDX;
172 
173 typedef struct KernelHeaderEncode
174 {
175     int nKernelCount;
176 
177     union
178     {
179         struct
180         {
181             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_DS4X_Frame;
182             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_DS4X_Field;
183             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_DS2X_Frame;
184             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_DS2X_Field;
185             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_HME_P;
186             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_HME_B;
187             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_HME_Streamin;
188             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_HME_HEVC_Streamin;
189             CODECHAL_KERNEL_HEADER Gen10_HEVC_VP9_VDEnc_HMEDetection;
190         };
191     };
192 
193 }KernelHeaderEncode;
194 
195 //!
196 //! \enum     BindingTableOffsetKernel
197 //! \brief    Binding table offset kernel
198 //!
199 enum BindingTableOffsetKernel
200 {
201     // VDEnc HME kernel
202     HmeBegin = 0,
203     HmeMvDataSurfaceCm = HmeBegin,
204     Hme16xMeMvDataSurfaceCm,
205     Hme32xMeMvDataSurfaceCm = Hme16xMeMvDataSurfaceCm,
206     HmeDistortionSurfaceCm,
207     HmeBrcDistortionCm,
208     HmeCurrForFwdRefCm,
209     HmeFwdRefIdx0Cm,
210     HmeReserved1Cm,
211     HmeFwdRefIdx1Cm,
212     HmeReserved2Cm,
213     HmeFwdRefIdx2Cm,
214     HmeReserved3Cm,
215     HmeFwdRefIdx3Cm,
216     HmeReserved4Cm,
217     HmeFwdRefIdx4Cm,
218     HmeReserved5Cm,
219     HmeFwdRefIdx5Cm,
220     HmeReserved6Cm,
221     HmeFwdRefIdx6Cm,
222     HmeReserved7Cm,
223     HmeFwdRefIdx7Cm,
224     HmeReserved8Cm,
225     HmeCurrForBwdRefCm,
226     HmeBwdRefIdx0Cm,
227     HmeReserved9Cm,
228     HmeBwdRefIdx1Cm,
229     HmeReserved10Cm,
230     HmeVdencStreaminOutputCm,
231     HmeVdencStreaminInputCm,
232     HmeEnd,
233 };
234 
235 //!
236 //! \enum   BrcUpdateFlag
237 //! \brief  Indicate the Brc Update Flag
238 //!
239 enum BrcUpdateFlag
240 {
241     brcUpdateIsField         = 0x01,
242     brcUpdateIsMbaff         = (0x01 << 1),
243     brcUpdateIsBottomField   = (0x01 << 2),
244     brcUpdateAutoPbFrameSize = (0x01 << 3),
245     brcUpdateIsActualQp      = (0x01 << 6),
246     brcUpdateIsReference     = (0x01 << 7)
247 };
248 
249 // User Feature Key Report Writeout
250 #define CodecHalEncodeWriteKey64(key, value, mosCtx)\
251 {\
252     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
253     UserFeatureWriteData.Value.i64Data  = (value);\
254     UserFeatureWriteData.ValueID        = (key);\
255     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
256 }
257 
258 #define CodecHalEncodeWriteKey(key, value, mosCtx)\
259 {\
260     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
261     UserFeatureWriteData.Value.i32Data  = (value);\
262     UserFeatureWriteData.ValueID        = (key);\
263     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
264 }
265 
266 #define CodecHalEncodeWriteStringKey(key, value, len, mosCtx)\
267 {\
268     MOS_USER_FEATURE_VALUE_WRITE_DATA   UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;\
269     UserFeatureWriteData.Value.StringData.pStringData = (value);\
270     UserFeatureWriteData.Value.StringData.uSize = (len);\
271     UserFeatureWriteData.ValueID        = (key);\
272     MOS_UserFeature_WriteValues_ID(nullptr, &UserFeatureWriteData, 1, mosCtx);\
273 }
274 
275 // ---------------------------
276 // Tables
277 // ---------------------------
278 
279 // ---------------------------
280 // Structures
281 // ---------------------------
282 
283 #define CODECHAL_ENCODE_SET_PERFTAG_INFO(perfTag, type) {                               \
284     perfTag.Value               = 0;                                                    \
285     perfTag.Mode                = m_mode & CODECHAL_ENCODE_MODE_BIT_MASK;               \
286     perfTag.CallType            = type;                                                 \
287     perfTag.PictureCodingType   = m_pictureCodingType > 3 ? 0 : m_pictureCodingType;    \
288     m_osInterface->pfnSetPerfTag(m_osInterface, perfTag.Value);                         \
289     m_osInterface->pfnIncPerfBufferID(m_osInterface);             }
290 
291 //!
292 //! \struct    CodechalEncodeMdfKernelResource
293 //! \brief     Codechal encode mdf kernel resource
294 //!
295 struct CodechalEncodeMdfKernelResource
296 {
297     void                            *pCommonISA;
298     CmProgram                       *pCmProgram;
299     CmKernel                        **ppKernel;
300     uint8_t                         *pCurbe;
301     CmThreadSpace                   *pTS;
302     CmBuffer                        **ppCmBuf;
303     CmSurface2D                     **ppCmSurf;
304     SurfaceIndex                    **ppCmVmeSurf;
305     CmEvent                         *e;
306 
307     uint8_t                         KernelNum;
308     uint8_t                         BufNum;
309     uint8_t                         SurfNum;
310     uint8_t                         VmeSurfNum;
311     uint16_t                        wCurbeSize;
312     uint16_t                        wReserved;
313 };
314 
315 //!
316 //! \struct MfeParams
317 //! \brief  Mfe encode parameters
318 //!
319 struct MfeParams
320 {
321     uint32_t                           streamId;             //!< Unique id
322     uint32_t                           submitIndex;          //!< Index during this submission
323     uint32_t                           submitNumber;         //!< Total stream number during this submission
324     uint32_t                           maxWidth;             //!< Maximum width for all frames
325     uint32_t                           maxHeight;            //!< Maximum height for all frames
326 };
327 
328 //!
329 //! \struct MfeSharedState
330 //! \brief  State shared across multiple streams
331 //!
332 struct MfeSharedState
333 {
334     CodechalHwInterface             *pHwInterface = nullptr;
335     PMOS_INTERFACE                  pOsInterface;
336     PMHW_KERNEL_STATE               pMfeMbEncKernelState;            //!< Set in the first stream, Used by the rest streams
337     uint32_t                        dwPicWidthInMB;                  //!< Keep the maximum width
338     uint32_t                        dwPicHeightInMB;                 //!< Keep the maximum height
339     uint16_t                        sliceHeight;                     //!< Keep the maximum slice height
340     uint32_t                        maxTheadWidth = 0;               //!< Keep the maximum width of the threadspace
341     uint32_t                        maxTheadHeight = 0;              //!< Keep the maximum Height of the threadspace
342     uint32_t                        *maxThreadWidthFrames = nullptr; //!< Keep the thread space width for all frames
343 
344     CmDevice                                *pCmDev = nullptr;       //!< Set in the first stream, Used by the rest streams
345     CmTask                                  *pCmTask = nullptr;
346     CmQueue                                 *pCmQueue = nullptr;
347     CodechalEncodeMdfKernelResource         *resMbencKernel = nullptr;
348     SurfaceIndex                            *vmeSurface = nullptr;
349     SurfaceIndex                            *commonSurface = nullptr;
350     std::vector<CodechalEncoderState*>      encoders;
351 };
352 
353 //!
354 //! \enum  EncOperation
355 //! \brief Encode operations
356 //!
357 enum EncOperation
358 {
359     ENC_SCALING4X = 0,
360     ENC_SCALING2X,
361     ENC_ME,
362     ENC_BRC,
363     ENC_MBENC,
364     ENC_MBENC_ADV,
365     ENC_RESETVLINESTRIDE,
366     ENC_MC,
367     ENC_MBPAK,
368     ENC_DEBLOCK,
369     ENC_PREPROC,
370     VDENC_ME,
371     ENC_WP,
372     ENC_SFD,                   //!< Static frame detection
373     ENC_SCOREBOARD,
374     ENC_MBENC_I_LUMA,
375     ENC_MPU,
376     ENC_TPU,
377     ENC_SCALING_CONVERSION,    //!< for HEVC
378     ENC_DYS,
379     ENC_INTRA_DISTORTION,
380     VDENC_ME_P,
381     VDENC_ME_B,
382     VDENC_STREAMIN,
383     VDENC_STREAMIN_HEVC,
384     VDENC_STREAMIN_HEVC_RAB
385 };
386 
387 //!
388 //! \enum  HmeLevel
389 //! \brief Indicate the Hme level
390 //!
391 enum HmeLevel
392 {
393     HME_LEVEL_4x  = 0,
394     HME_LEVEL_16x = 1,
395     HME_LEVEL_32x = 2
396 };
397 
398 //!
399 //! \enum     EncodeMeMode
400 //! \brief    Encode me mode
401 //!
402 enum EncodeMeMode
403 {
404     CODECHAL_ENCODE_ME16X_BEFORE_ME4X = 0,
405     CODECHAL_ENCODE_ME16X_ONLY = 1,
406     CODECHAL_ENCODE_ME4X_ONLY = 2,
407     CODECHAL_ENCODE_ME4X_AFTER_ME16X = 3
408 };
409 
410 //!
411 //! \enum     CodechalEncodeBrcNumPasses
412 //! \brief    used in GetNumBrcPakPasses
413 //!
414 enum CodechalEncodeBrcNumPasses
415 {
416     CODECHAL_ENCODE_BRC_SINGLE_PASS        = 1, // No IPCM case
417     CODECHAL_ENCODE_BRC_MINIMUM_NUM_PASSES = 2, // 2 to cover IPCM case
418     CODECHAL_ENCODE_BRC_DEFAULT_NUM_PASSES = 4,
419     CODECHAL_ENCODE_BRC_MAXIMUM_NUM_PASSES = 7
420 };
421 
422 //!
423 //! \struct HmeParams
424 //! \brief  Indicate the Hme parameters
425 //!
426 struct HmeParams
427 {
428     // ME
429     PMOS_SURFACE            ps4xMeMvDataBuffer;
430     PMOS_SURFACE            ps16xMeMvDataBuffer;
431     PMOS_SURFACE            ps32xMeMvDataBuffer;
432     PMOS_SURFACE            ps4xMeDistortionBuffer;
433     PMOS_RESOURCE           presMvAndDistortionSumSurface;
434     bool                    b4xMeDistortionBufferSupported;
435 };
436 
437 //!
438 //! \brief  Generic binding table
439 //!
440 struct GenericBindingTable
441 {
442     uint32_t   dwMediaState;
443     uint32_t   dwBindingTableStartOffset;
444     uint32_t   dwNumBindingTableEntries;
445     uint32_t   dwBindingTableEntries[64];
446 };
447 using PCODECHAL_ENCODE_BINDING_TABLE_GENERIC = GenericBindingTable*;
448 
449 //!
450 //! \struct MeKernelBindingTable
451 //! \brief  The struct of Me kernel binding table
452 //!
453 struct MeKernelBindingTable
454 {
455     uint32_t                        dwMEMVDataSurface;
456     uint32_t                        dwMECurrY;
457     uint32_t                        dwMEFwdRefY;
458     uint32_t                        dwMEBwdRefY;
459     uint32_t                        dwMECurrForFwdRef;
460     uint32_t                        dwMEFwdRef;
461     uint32_t                        dwMECurrForBwdRef;
462     uint32_t                        dwMEBwdRef;
463     uint32_t                        dw16xMEMVDataSurface;
464     uint32_t                        dw32xMEMVDataSurface;
465     uint32_t                        dwMEDist;
466     uint32_t                        dwMEBRCDist;
467     uint32_t                        dwMECurrForFwdRefIdx[CODECHAL_ENCODE_NUM_MAX_VME_L0_REF];
468     uint32_t                        dwMECurrForBwdRefIdx[CODECHAL_ENCODE_NUM_MAX_VME_L1_REF];
469 
470     // Frame Binding Table Entries
471     uint32_t                        dwMEFwdRefPicIdx[CODECHAL_ENCODE_NUM_MAX_VME_L0_REF];
472     uint32_t                        dwMEBwdRefPicIdx[CODECHAL_ENCODE_NUM_MAX_VME_L1_REF];
473 
474     // Field Binding Table Entries
475     uint32_t                        dwMEFwdRefPicTopIdx[CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L0_REF];
476     uint32_t                        dwMEFwdRefPicBotIdx[CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L0_REF];
477     uint32_t                        dwMEBwdRefPicTopIdx[CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L1_REF];
478     uint32_t                        dwMEBwdRefPicBotIdx[CODECHAL_ENCODE_FIELD_NUM_MAX_VME_L1_REF];
479 
480     uint32_t                        dwVdencStreamInSurface;
481     uint32_t                        dwVdencStreamInInputSurface;
482 
483     uint32_t                        dwBindingTableStartOffset;
484     uint32_t                        dwNumBindingTableEntries;
485 };
486 
487 //!
488 //! \struct MeSurfaceParams
489 //! \brief  The struct of Me surface parameters
490 //!
491 struct MeSurfaceParams
492 {
493     PCODEC_REF_LIST                 *ppRefList;
494     PCODEC_PIC_ID                   pPicIdx;
495     PCODEC_PICTURE                  pCurrOriginalPic;
496     PMOS_SURFACE                    ps4xMeMvDataBuffer;
497     uint32_t                        dw4xMeMvBottomFieldOffset;
498     PMOS_SURFACE                    ps16xMeMvDataBuffer;
499     uint32_t                        dw16xMeMvBottomFieldOffset;
500     PMOS_SURFACE                    ps32xMeMvDataBuffer;
501     uint32_t                        dw32xMeMvBottomFieldOffset;
502     uint32_t                        dw4xScaledBottomFieldOffset;
503     uint32_t                        dw16xScaledBottomFieldOffset;
504     uint32_t                        dw32xScaledBottomFieldOffset;
505     PMOS_SURFACE                    psMeDistortionBuffer;
506     uint32_t                        dwMeDistortionBottomFieldOffset;
507     PMOS_SURFACE                    psMeBrcDistortionBuffer;
508     PMOS_RESOURCE                   psMeVdencStreamInBuffer;
509     uint32_t                        dwMeBrcDistortionBottomFieldOffset;
510     uint32_t                        dwDownscaledWidthInMb;
511     uint32_t                        dwDownscaledHeightInMb;
512     uint32_t                        dwVDEncStreamInSurfaceSize;
513     uint32_t                        dwVerticalLineStride;
514     uint32_t                        dwVerticalLineStrideOffset;
515     bool                            b16xMeInUse;
516     bool                            b32xMeInUse;
517     bool                            b16xMeEnabled;
518     bool                            b32xMeEnabled;
519     bool                            bVdencStreamInEnabled;
520     PCODEC_PICTURE                  pL0RefFrameList;
521     PCODEC_PICTURE                  pL1RefFrameList;
522     uint32_t                        dwNumRefIdxL0ActiveMinus1;
523     uint32_t                        dwNumRefIdxL1ActiveMinus1;
524     PMHW_KERNEL_STATE               pKernelState;
525     MeKernelBindingTable*           pMeBindingTable;
526     bool                            bMbaff;
527     bool                            b4xMeDistortionBufferSupported;
528 };
529 
530 //!
531 //! \struct MeCurbeParams
532 //! \brief  The struct of Me Curbe parameters
533 //!
534 struct MeCurbeParams
535 {
536     PMHW_KERNEL_STATE               pKernelState;
537     HmeLevel                        hmeLvl;
538     bool                            b16xMeEnabled;
539     bool                            b32xMeEnabled;
540     bool                            segmapProvided;
541     uint8_t                         TargetUsage;
542     uint8_t                        *pMEMethodTable;
543     uint8_t                        *pBMEMethodTable;
544     int32_t                         MaxMvLen;
545 
546     // Picture parameters
547     CODEC_PICTURE                   CurrOriginalPic;  // Source sent in by BeginFrame
548     int8_t                          pic_init_qp_minus26;
549 
550     // Slice parameters
551     int8_t                          slice_qp_delta;
552     uint8_t                         num_ref_idx_l0_active_minus1;
553     uint8_t                         num_ref_idx_l1_active_minus1;
554     bool                            List0RefID0FieldParity;
555     bool                            List0RefID1FieldParity;
556     bool                            List0RefID2FieldParity;
557     bool                            List0RefID3FieldParity;
558     bool                            List0RefID4FieldParity;
559     bool                            List0RefID5FieldParity;
560     bool                            List0RefID6FieldParity;
561     bool                            List0RefID7FieldParity;
562     bool                            List1RefID0FieldParity;
563     bool                            List1RefID1FieldParity;
564     uint8_t                         *pCurbeBinary;
565 };
566 
567 //!
568 //! \struct    EncodeReadBrcPakStatsParams
569 //! \brief     Encode read brc pak states parameters
570 //!
571 struct EncodeReadBrcPakStatsParams
572 {
573     CodechalHwInterface    *pHwInterface;
574     PMOS_RESOURCE           presBrcPakStatisticBuffer;
575     PMOS_RESOURCE           presStatusBuffer;
576     uint32_t                dwStatusBufNumPassesOffset;
577     uint8_t                 ucPass;
578     MOS_GPU_CONTEXT         VideoContext;
579 };
580 
581 //!
582 //! \struct PakIntegrationBrcData
583 //! \brief  The struct of Huc input command 2
584 //!
585 struct PakIntegrationBrcData
586 {
587     uint32_t FrameByteCount;
588     uint32_t FrameByteCountNoHeader;
589     uint32_t HCP_ImageStatusControl;
590 };
591 
592 //!
593 //! \struct SearchPathDelta
594 //! \brief  The struct of Search Path Delta
595 //!
596 struct SearchPathDelta
597 {
598     uint8_t   SearchPathDelta_X       : 4;
599     uint8_t   SearchPathDelta_Y       : 4;
600 };
601 
602 //!
603 //! \struct SendKernelCmdsParams
604 //! \brief  Struct of send kernel commands parameters
605 //!
606 struct SendKernelCmdsParams
607 {
608     CODECHAL_MEDIA_STATE_TYPE           EncFunctionType = CODECHAL_NUM_MEDIA_STATES;
609     uint32_t                            uiDshIdx = 0;
610     uint8_t                             ucDmvPredFlag = 0;
611     bool                                bBrcResetRequested = false;
612     bool                                bEnable45ZWalkingPattern = false;
613     bool                                bEnableCustomScoreBoard = false;
614     PMHW_VFE_SCOREBOARD                 pCustomScoreBoard = nullptr;
615     PMHW_KERNEL_STATE                   pKernelState = nullptr;
616     bool                                bDshInUse = false;
617 };
618 
619 //!
620 //! \struct BrcQpReport
621 //! \brief  Struct of Query bit rate control and QP Status
622 //!
623 struct BrcQpReport
624 {
625     // uint32_t 0
626     union
627     {
628         struct
629         {
630             uint32_t   QPPrimeY                    : 8;
631             uint32_t   QPPrimeCb                   : 8;
632             uint32_t   QPPrimeCr                   : 8;
633             uint32_t   Reserved                    : 8;
634         };
635         struct
636         {
637             uint32_t   Value;
638         };
639     } DW0;
640 
641     // uint32_t 1 ~ 15
642     struct
643     {
644         uint32_t   Value[15];
645     };
646 };
647 
648 //!
649 //! \struct LookaheadStatus
650 //! \brief  Struct of Query bit rate control and QP Status
651 //!
652 struct LookaheadReport
653 {
654     uint32_t StatusReportNumber;
655     union
656     {
657         struct
658         {
659             uint32_t cqmHint    : 8;
660             uint32_t intraHint  : 1;
661             uint32_t reserved2  : 22;
662             uint32_t isValid    : 1;
663         };
664         uint32_t encodeHints;
665     };
666     uint32_t targetFrameSize;
667     uint32_t targetBufferFulness;
668     uint32_t pyramidDeltaQP;
669     uint8_t  adaptive_rounding;
670     uint8_t  miniGopSize;
671     uint8_t  reserved1[2];
672     uint32_t reserved3[10];
673 };
674 
675 //!
676 //! \struct    EncodeBrcBuffers
677 //! \brief     Encode brc buffers
678 //!
679 struct EncodeBrcBuffers
680 {
681     MOS_RESOURCE            resBrcHistoryBuffer;                                                    // BRC history buffer
682     MOS_RESOURCE            resBrcPakStatisticBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM];
683     uint32_t                uiCurrBrcPakStasIdxForRead;
684     uint32_t                uiCurrBrcPakStasIdxForWrite;
685     MOS_RESOURCE            resBrcImageStatesReadBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM];      // read only BRC image state buffer
686     MOS_RESOURCE            resBrcImageStatesWriteBuffer;                                          // write only BRC image state buffer
687     MOS_RESOURCE            resHevcBrcImageStatesWriteBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM]; // write only HEVC BRC image state buffers
688     MOS_RESOURCE            resPakQPInputTable;
689     MOS_RESOURCE            resBrcConstantDataBuffer;
690     MOS_RESOURCE            resEncoderCfgCommandReadBuffer;
691     MOS_RESOURCE            resEncoderCfgCommandWriteBuffer;
692     MOS_RESOURCE            resBrcPakStatsBeforeDumpBuffer;  // These buffers are used to dump all the MMIO read values
693     MOS_RESOURCE            resBrcPakStatsAfterDumpBuffer;   // which are super-set of PakStat
694     MOS_SURFACE             sBrcConstantDataBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM];
695     MOS_SURFACE             sMeBrcDistortionBuffer;
696     uint32_t                dwMeBrcDistortionBottomFieldOffset;
697     MOS_RESOURCE            resMbBrcConstDataBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM];
698     MOS_SURFACE             sBrcMbQpBuffer;
699     uint32_t                dwBrcMbQpBottomFieldOffset;
700     MOS_RESOURCE            resBrcPicHeaderInputBuffer;
701     MOS_RESOURCE            resBrcPicHeaderOutputBuffer;
702     MOS_RESOURCE            resMbEncAdvancedDsh;
703     MOS_RESOURCE            resMbEncBrcBuffer;
704     MOS_SURFACE             sBrcRoiSurface;                 // BRC ROI surface
705     PMHW_KERNEL_STATE       pMbEncKernelStateInUse;
706 };
707 
708 //!
709 //! \struct    CODECHAL_ENCODE_BUFFER
710 //! \brief     Codechal encode buffer
711 //!
712 struct CODECHAL_ENCODE_BUFFER
713 {
714     MOS_RESOURCE    sResource;
715     uint32_t        dwSize = 0;
716 };
717 using PCODECHAL_ENCODE_BUFFER = CODECHAL_ENCODE_BUFFER*;
718 
719 //!
720 //! \struct EncodeStatusReport
721 //! \brief  Encode status report structure
722 //!
723 struct EncodeStatusReport
724 {
725     enum BLOCK_SIZE
726     {
727         BLOCK_4X4   = 0,
728         BLOCK_16X16 = 1,
729     };
730 
731     struct FRAME_STATS_INFO
732     {
733         float    PSNRLuma;
734         float    PSNRCb;
735         float    PSNRCr;
736         uint64_t SADLuma;
737         float    Qp;
738 
739         union
740         {
741             uint32_t NumMB;
742             uint32_t NumCTU;
743         };
744 
745         BLOCK_SIZE BlockSize;
746         uint32_t   NumIntraBlock;
747         uint32_t   NumInterBlock;
748         uint32_t   NumSkippedBlock;
749         uint32_t   reserved[8];
750     };
751 
752     struct CTUHeader
753     {
754         union
755         {
756             struct
757             {
758                 uint32_t CUcountminus1 : 6;
759                 uint32_t MaxDepth : 2;
760                 uint32_t reserved : 24;
761             };
762             uint32_t DW0;
763         };
764         uint16_t CurrXAddr;
765         uint16_t CurrYAddr;
766         uint32_t reserved1;
767     };
768 
769     struct Int16Pair
770     {
771         int16_t x;
772         int16_t y;
773     };
774 
775     struct CUInfo
776     {
777         union
778         {
779             struct
780             {
781                 uint32_t CU_Size : 2;
782                 uint32_t CU_pred_mode : 1;
783                 uint32_t CU_part_mode : 3;
784                 uint32_t InterPred_IDC_MV0 : 2;
785                 uint32_t InterPred_IDC_MV1 : 2;
786                 uint32_t LumaIntraMode : 6;
787                 uint32_t ChromaIntraMode : 3;
788                 uint32_t reserved : 13;
789             };
790             uint32_t DW0;
791         };
792 
793         union
794         {
795             struct
796             {
797                 uint32_t LumaIntraMode4x4_1 : 6;
798                 uint32_t LumaIntraMode4x4_2 : 6;
799                 uint32_t LumaIntraMode4x4_3 : 6;
800                 uint32_t reserved1 : 14;
801             };
802             uint32_t DW1;
803         };
804 
805         int8_t   QP;
806         uint8_t  reserved2[3];
807         uint32_t SAD;
808 
809         Int16Pair MV[2][2];
810 
811         union
812         {
813             struct
814             {
815                 uint32_t L0_MV0_RefID : 4;
816                 uint32_t L0_MV1_RefID : 4;
817                 uint32_t L1_MV0_RefID : 4;
818                 uint32_t L1_MV1_RefID : 4;
819                 uint32_t reserved3 : 16;
820             };
821             uint32_t DW8;
822         };
823 
824         uint32_t reserved4[10];
825     };
826 
827     struct CTUInfo
828     {
829         CTUHeader CtuHeader;
830         CUInfo    CuInfo[64];
831         uint32_t  reserved;
832     };
833 
834     struct MBInfo
835     {
836         union
837         {
838             struct
839             {
840                 uint32_t MBType : 5;
841                 uint32_t InterMBMode : 2;
842                 uint32_t IntraMBMode : 2;
843                 uint32_t IntraMBFlag : 1;
844                 uint32_t SubMBShapes : 8;
845                 uint32_t SubMBShapeMode : 8;
846                 uint32_t ChromaIntraPredMode : 2;
847                 uint32_t reserved : 4;
848             };
849             uint32_t DW0;
850         };
851 
852         uint32_t SAD;
853         int8_t   Qp;
854         uint8_t  reserved1[3];
855 
856         uint16_t LumaIntraMode[4];
857 
858         uint32_t reserved2;
859     };
860 
861     struct BLOCK_STATS_INFO
862     {
863         union
864         {
865             uint32_t NumMB;
866             uint32_t NumCTU;
867         };
868 
869         union
870         {
871             CTUInfo *HEVCCTUArray;
872             MBInfo  *AVCMBArray;
873         };
874 
875         uint32_t reserved[8];
876     };
877 
878     struct BLOCK_SSIM_INFO
879     {
880         uint32_t NumBlockInColumns;
881         uint32_t NumBlockInRows;
882         uint8_t* BlockSsimArray;
883         uint32_t reserved1[2];
884         uint64_t reserved2[2];
885     };
886 
887     struct BLOCK_QUALITY_INFO
888     {
889         BLOCK_SSIM_INFO BlockSsim2DS;
890         BLOCK_SSIM_INFO BlockSsim4DS;
891         BLOCK_SSIM_INFO BlockSsim8DS;
892         BLOCK_SSIM_INFO BlockSsim16DS;
893         uint32_t        reserved1[32];
894         uint64_t        reserved2[12];
895     };
896 
897     CODECHAL_STATUS                 CodecStatus;            //!< Status for the picture associated with this status report
898     uint32_t                        StatusReportNumber;     //!< Status report number associated with the picture in this status report provided in CodechalEncoderState::Execute()
899     CODEC_PICTURE                   CurrOriginalPic;        //!< Uncompressed frame information for the picture associated with this status report
900     CODECHAL_ENCODE_FUNCTION_ID     Func;                   //!< Encode function requested at CodechalEncoderState::Execute()
901     PCODEC_REF_LIST                 pCurrRefList;           //!< Reference list for the current frame, used for dump purposes with CodecHal Debug Tool
902                                                             /*! \brief Specifies the order in which the statuses are expected.
903                                                             *
904                                                             *   The order in which a status is returned is requested at the DDI level and the order itself is determined by StatusReportNumber.
905                                                             *       FALSE indicates the statuses should be returned in reverse order.
906                                                             *       TRUE indicates the statuses should be returned in sequential order.
907                                                             */
908     bool                            bSequential;
909     /*! \brief Coded bitstream size reported by HW.
910     *
911     *   The size reported by HW is the total bitstream size that is encoded by HW including any bitstream buffer overrun.  That is, HW continues counting the encoded bytes past the programmed upperbound based on the allocated bitstream buffer size.  The framework can compare this value to the allocated buffer size to determine if there was overflow for this frame and can act accordingly.
912     */
913     uint32_t                        bitstreamSize;
914     /*! \brief Qp value for Y used for the first PAK pass.
915     *
916     *   It is not valid if CQP is set by framework.
917     */
918     int8_t                          QpY;
919     /*! \brief Suggested Qp delta value for Y.
920     *
921     *   Framework can add this delta Qp with the first pass QpY to get the final Qp used for multi-pass.  It is not valid if CQP is set by framework.
922     *   Note: Framework can use this reported QpY and suggestedQpYDelta to set QpY in picture parameter to minimize LCU level Qp delta.
923     */
924     int8_t                          SuggestedQpYDelta;
925     uint8_t                         NumberPasses;       //!< Number of PAK passes executed.
926     uint8_t                         AverageQp;          //!< The average QP of all MBs or LCUs of the frame.
927     HwCounter                       HWCounterValue;
928     uint64_t *                      hwctr;
929     union
930     {
931         struct
932         {
933             uint32_t PanicMode              : 1;    //!< Indicates that panic mode was triggered by HW for this frame.
934             uint32_t SliceSizeOverflow      : 1;    //!< When SliceLevelRateCtrl is used, indicates the requested slice size was not met for one or more generated slices.
935             uint32_t NumSlicesNonCompliant  : 1;    //!< When SliceLevelRateCtrl is used, indicates whether or not the number of generated slices exceeds specification limits.
936             uint32_t LongTermReference      : 1;
937             uint32_t FrameSkipped           : 1;
938             uint32_t SceneChangeDetected    : 1;
939             uint32_t                    : 26;
940         };
941         uint32_t QueryStatusFlags;
942     };
943     /*! \brief The average MAD (Mean Absolute Difference) across all macroblocks in the Y plane.
944     *
945     *    The MAD value is the mean of the absolute difference between the pixels in the original block and the corresponding pixels in the block being used for comparison, from motion compensation or intra spatial prediction. MAD reporting is disabled by default.
946     */
947     uint32_t                        MAD;
948     uint32_t                        loopFilterLevel;        //!< [VP9]
949     int8_t                          LongTermIndication;     //!< [VP9]
950     uint16_t                        NextFrameWidthMinus1;   //!< [VP9]
951     uint16_t                        NextFrameHeightMinus1;  //!< [VP9]
952     uint8_t                         NumberSlices;           //!< Number of slices generated for the frame.
953     uint16_t                        PSNRx100[3];            //!< PSNR for different channels
954     uint32_t                        NumberTilesInFrame;     //!< Number of tiles generated for the frame.
955     uint8_t                         UsedVdBoxNumber;        //!< Number of vdbox used.
956     uint32_t                        SizeOfSliceSizesBuffer; //!< Store the size of slice size buffer
957     uint16_t                        *pSliceSizes;           //!< Pointer to the slice size buffer
958     uint32_t                        SizeOfTileInfoBuffer;   //!< Store the size of tile info buffer
959     CodechalTileInfo*               pHEVCTileinfo;          //!< Pointer to the tile info buffer
960     uint32_t                        NumTileReported;        //!< The number of tiles reported in status
961 
962     /*! \brief indicate whether it is single stream encoder or MFE.
963     *
964     *    For single stream encoder (regular), this value should be set to default 0. For Multi-Frame-Encoder (MFE), this value is the StreamId that is set by application.
965     */
966     uint32_t                        StreamId;
967 
968     LookaheadReport*                pLookaheadStatus;       //!< Pointer to the lookahead status buffer. Valid in lookahead pass only.
969 
970     FRAME_STATS_INFO *pFrmStatsInfo;
971     BLOCK_STATS_INFO *pBlkStatsInfo;
972 
973     uint32_t                        reserved[4];            //!< align with apo path hal structure EncodeStatusReportData
974 
975     uint32_t                        MSE[3];
976 
977     BLOCK_QUALITY_INFO*             pBlkQualityInfo;
978 };
979 
980 //!
981 //! \struct EncodeStatusSliceReport
982 //! \brief  The struct stores Encode status buffers
983 //!
984 struct EncodeStatusSliceReport
985 {
986     uint32_t                        SliceSizeOverflow;
987     uint8_t                         NumberSlices;
988     uint32_t                        SizeOfSliceSizesBuffer;
989     PMOS_RESOURCE                   pSliceSize;
990     uint32_t                        reserved;
991 };
992 
993 //!
994 //! \struct EncodeStatus
995 //! \brief  The struct stores Encode status
996 //!
997 struct EncodeStatus
998 {
999     uint32_t                        dwStoredDataMfx;    //!< HW requires a QW aligned offset for data storage
1000     uint32_t                        dwPad;              //!< Pad
1001     struct
1002     {
1003         uint32_t                    dwStoredData;
1004         uint32_t                    dwPad;
1005     } qwStoredDataEnc[CODECHAL_NUM_MEDIA_STATES];           //!< Media states of stored encode data
1006     uint32_t                        dwStoredData;           //!< SW stored data
1007     uint32_t                        dwMFCBitstreamByteCountPerFrame;         //!< Media fixed function bitstream byte count per frame
1008     uint32_t                        dwMFCBitstreamSyntaxElementOnlyBitCount; //!< Media fixed function bitstream bit count for syntax element only
1009     uint32_t                        reserved;
1010     uint32_t                        dwImageStatusMask;      //!< MUST ENSURE THAT THIS IS QWORD ALIGNED as it's used for the conditional BB end
1011     MHW_VDBOX_IMAGE_STATUS_CONTROL  ImageStatusCtrl;        //!< Used for storing the control flags for the image status
1012     uint32_t                        HuCStatusRegMask;       //!< MUST ENSURE THAT THIS IS QWORD ALIGNED as it's used for the conditional BB end
1013     uint32_t                        HuCStatusReg;           //!< Register value saving HuC Status
1014     MHW_VDBOX_PAK_NUM_OF_SLICES     NumSlices;              //!< Num of slices for encode
1015     uint32_t                        dwErrorFlags;           //!< The definition is different on SNB/IVB, hence DWORD
1016     union
1017     {
1018         BrcQpReport                 BrcQPReport;            //!< Query bit rate control and QP Status
1019         LookaheadReport             lookaheadStatus;        //!< Lookahead status. valid in lookahead pass only
1020     };
1021     uint32_t                        dwNumberPasses;         //!< Number of passes
1022     uint32_t                        dwHeaderBytesInserted;  //!< The size including header, prevention bytes and dummy "0xff" inserted by SW driver
1023     CodechalQpStatusCount           QpStatusCount;          //!< This is used to obtain the cumulative QP
1024     EncodeStatusReport              encodeStatusReport;     //!< The detailed encode status report structure
1025     uint16_t                        wPictureCodingType;     //!< Type of picture coding
1026     uint32_t                        LoopFilterLevel;        //!< The level of loop filter
1027     MHW_VDBOX_IMAGE_STATUS_CONTROL  ImageStatusCtrlOfLastBRCPass;   //!< The level of loop filter
1028     uint32_t                        dwSceneChangedFlag;     //!< The flag indicate if the scene is changed
1029     uint64_t                        sumSquareError[3];      //!< The list of sum square error
1030     uint32_t                        dwSADLuma;              //!< SAD for Y channel
1031     uint32_t                        dwIntraBlockCount;      //!< Intra block count
1032     uint32_t                        dwInterBlockCount;      //!< Inter block count
1033     uint32_t                        dwSkipBlockCount;       //!< Skip block count
1034     EncodeStatusSliceReport         sliceReport;
1035     uint32_t                        HuCStatus2Reg;          //!< Register value saving HuC Status2
1036 };
1037 
1038 //!
1039 //! \struct EncodeStatusBuffer
1040 //! \brief  The sturct of encode status buffer
1041 //!
1042 struct EncodeStatusBuffer
1043 {
1044     uint8_t                                 *pEncodeStatus;                  //!> needs to be first to ensure alingment of dwStoredDataMfx/Vme
1045     MOS_RESOURCE                            resStatusBuffer;                //!> Handle of eStatus buffer
1046     uint32_t                                *pData;                         //!> Pointer of the buffer of actual data
1047     uint16_t                                wFirstIndex;                    //!> Indicate the first index of status
1048     uint16_t                                wCurrIndex;                     //!> Indicate current index of status
1049     uint32_t                                dwStoreDataOffset;              //!> The offset of stored data
1050     uint32_t                                dwBSByteCountOffset;            //!> The offset of BS byte count
1051     uint32_t                                dwBSSEBitCountOffset;           //!> The offset of BS SE byte count
1052     uint32_t                                dwImageStatusMaskOffset;        //!> The offset of image status mask
1053     uint32_t                                dwImageStatusCtrlOffset;        //!> The offset of status control
1054     uint32_t                                dwHuCStatusMaskOffset;          //!> The offset of HuC status register mask
1055     uint32_t                                dwHuCStatusRegOffset;           //!> The offset of HuC status register
1056     uint32_t                                dwNumSlicesOffset;              //!> The offset of silce num
1057     uint32_t                                dwErrorFlagOffset;              //!> The offset of error flag
1058     uint32_t                                dwBRCQPReportOffset;            //!> The offset of bitrate control QP report
1059     uint32_t                                dwNumPassesOffset;              //!> The offset of passes number
1060     uint32_t                                dwQpStatusCountOffset;          //!> The offset of QP status count
1061     uint32_t                                dwImageStatusCtrlOfLastBRCPassOffset; //!> The offset of image status control of last bitrate control pass
1062     uint32_t                                dwSceneChangedOffset;           //!> The offset of the scene changed flag
1063     uint32_t                                dwSumSquareErrorOffset;         //!> The offset of list of sum square error
1064     uint32_t                                dwSliceReportOffset;            //!> The offset of slice size report structure
1065     uint32_t                                dwLookaheadStatusOffset;        //!> The offset of lookahead status
1066     uint32_t                                dwSADLumaOffset;                //!> The offset of SAD Luma
1067     uint32_t                                dwIntraBlockCountOffset;        //!> The offset of intra block count
1068     uint32_t                                dwInterBlockCountOffset;        //!> The offset of inter block count
1069     uint32_t                                dwSkipBlockCountOffset;         //!> The offset of skip block count
1070     uint32_t                                dwSize;                         //!> Size of status buffer
1071     uint32_t                                dwReportSize;                   //!> Size of report
1072     uint32_t                                dwHuCStatus2RegOffset;          //!> The offset of HuC status2 register
1073 };
1074 
1075 //!
1076 //! \struct CodechalEncodeBbuf
1077 //! \brief  Struct for Batch buffer
1078 //!
1079 struct CodechalEncodeBbuf
1080 {
1081     MHW_BATCH_BUFFER        BatchBuffer;
1082     uint32_t                dwSize;
1083     uint32_t                dwNumMbsInBBuf;
1084     bool                    fieldScale;
1085 };
1086 
1087 //!
1088 //! \struct CodechalEncodeIdOffsetParams
1089 //! \brief  Indicate the ID Offset parameters
1090 //!
1091 struct CodechalEncodeIdOffsetParams
1092 {
1093     uint32_t                                Standard;
1094     CODECHAL_MEDIA_STATE_TYPE               EncFunctionType;
1095     uint16_t                                wPictureCodingType;
1096     uint8_t                                 ucDmvPredFlag;
1097     bool                                    interlacedField;
1098 };
1099 
1100 //!
1101 //! \struct VdencHucErrorStatus
1102 //! \brief  Huc Error Flags
1103 //!
1104 struct VdencHucErrorStatus
1105 {
1106     uint32_t                dwErrorFlag[4];
1107 };
1108 
1109 //!
1110 //! \enum    EncodeMode
1111 //! \brief   Encode mode
1112 //!
1113 enum EncodeMode
1114 {
1115     encodeNormalMode = 0,
1116     encodePerformanceMode = 1,
1117     encodeQualityMode = 2
1118 };
1119 
1120 class CodechalEncodeWP;
1121 #if USE_CODECHAL_DEBUG_TOOL
1122 class CodechalDebugEncodePar;
1123 #endif
1124 
1125 //!
1126 //! \class    CodechalEncoderGenState
1127 //! \brief    Codechal encoder gen state
1128 //!
1129 class CodechalEncoderGenState
1130 {
1131 public:
1132     CodechalEncoderGenState(CodechalEncoderState* encoder);
1133 
~CodechalEncoderGenState()1134     virtual ~CodechalEncoderGenState() {}
1135 
1136     CodechalEncoderState*           m_encoder = nullptr;
1137     // Encoder private data
1138     CodechalHwInterface*            m_hwInterface = nullptr;
1139     PMOS_INTERFACE                  m_osInterface = nullptr;
1140     CodechalDebugInterface*         m_debugInterface = nullptr;
1141     MhwMiInterface*                 m_miInterface = nullptr;                   //!< Common Mi Interface
1142     MhwRenderInterface*             m_renderEngineInterface = nullptr;               //!< Render engine interface
1143     PMHW_STATE_HEAP_INTERFACE       m_stateHeapInterface = nullptr;                  //!< State heap interface
1144 
SetCurbeMe(MeCurbeParams * params)1145     virtual MOS_STATUS SetCurbeMe(
1146         MeCurbeParams* params)
1147     {
1148         return MOS_STATUS_SUCCESS;
1149     }
1150 
SendMeSurfaces(PMOS_COMMAND_BUFFER cmdBuffer,MeSurfaceParams * params)1151     virtual MOS_STATUS SendMeSurfaces(
1152         PMOS_COMMAND_BUFFER cmdBuffer,
1153         MeSurfaceParams* params)
1154     {
1155         return MOS_STATUS_SUCCESS;
1156     }
1157 };
1158 
1159 //!
1160 //! \class CodechalEncoderState
1161 //! \brief This base class defines the common member fields, functions etc used by all encoder.
1162 //!
1163 class CodechalEncoderState : public Codechal
1164 {
1165 public:
1166     CodechalHwInterface *m_hwInterface = nullptr;
1167     //!
1168     //! \enum     RefId
1169     //! \brief    Reference id
1170     //!
1171     enum RefId
1172     {
1173         CODECHAL_ENCODE_REF_ID_0 = 0,
1174         CODECHAL_ENCODE_REF_ID_1 = 1,
1175         CODECHAL_ENCODE_REF_ID_2 = 2,
1176         CODECHAL_ENCODE_REF_ID_3 = 3,
1177         CODECHAL_ENCODE_REF_ID_4 = 4,
1178         CODECHAL_ENCODE_REF_ID_5 = 5,
1179         CODECHAL_ENCODE_REF_ID_6 = 6,
1180         CODECHAL_ENCODE_REF_ID_7 = 7,
1181     };
1182 
1183     // this is used for Mpeg2 encoding BRC as well,
1184     // therefore, the last entry is for Mpeg2
1185     const uint8_t m_bMeMethodGeneric[NUM_TARGET_USAGE_MODES + 1] = {0, 4, 4, 6, 6, 6, 6, 4, 7};
1186 
1187     const uint8_t m_meMethodGeneric[NUM_TARGET_USAGE_MODES + 1] = {0, 4, 4, 6, 6, 6, 6, 4, 7};
1188 
1189     const uint32_t m_superCombineDistGeneric[NUM_TARGET_USAGE_MODES + 1] ={0, 1, 1, 5, 5, 5, 9, 9, 0};
1190 
1191     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISCBR                      = 0x0010;
1192     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISVBR                      = 0x0020;
1193     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISAVBR                     = 0x0040;
1194     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISCQL                      = 0x0080;
1195     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_FIELD_PIC                  = 0x0100;
1196     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISICQ                      = 0x0200;
1197     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISVCM                      = 0x0400;
1198     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_IGNORE_PICTURE_HEADER_SIZE = 0x2000;
1199     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_ISQVBR                     = 0x4000;
1200     static constexpr uint32_t CODECHAL_ENCODE_BRCINIT_DISABLE_MBBRC              = 0x8000;
1201     static constexpr uint32_t m_numLaDataEntry                                   = 128;  //!< number of entries in lookahead data buffer and lookahead stats buffer
1202 
1203     // SearchPath Table, index [CodingType][MEMethod][]
1204     const uint32_t m_encodeSearchPath[2][8][16] =
1205     {
1206         // I-Frame & P-Frame
1207         {
1208             // MEMethod: 0
1209             {
1210                 0x120FF10F, 0x1E22E20D, 0x20E2FF10, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x4EF1F1F1, 0xF1F21211,
1211                 0x0DFFFFE0, 0x11201F1F, 0x1105F1CF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1212             },
1213         // MEMethod: 1
1214             {
1215                 0x120FF10F, 0x1E22E20D, 0x20E2FF10, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x4EF1F1F1, 0xF1F21211,
1216                 0x0DFFFFE0, 0x11201F1F, 0x1105F1CF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1217             },
1218         // MEMethod: 2
1219             {
1220                 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
1221                 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1222             },
1223         // MEMethod: 3
1224             {
1225                 0x01010101, 0x11010101, 0x01010101, 0x11010101, 0x01010101, 0x11010101, 0x01010101, 0x11010101,
1226                 0x01010101, 0x11010101, 0x01010101, 0x00010101, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1227             },
1228         // MEMethod: 4
1229             {
1230                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1231                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1232             },
1233         // MEMethod: 5
1234             {
1235                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1236                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1237             },
1238         // MEMethod: 6
1239             {
1240                 0x120FF10F, 0x1E22E20D, 0x20E2FF10, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x4EF1F1F1, 0xF1F21211,
1241                 0x0DFFFFE0, 0x11201F1F, 0x1105F1CF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1242             },
1243         // MEMethod: 7 used for mpeg2 encoding P frames
1244             {
1245                 0x1F11F10F, 0x2E22E2FE, 0x20E220DF, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x02F1F1F1, 0x1F201111,
1246                 0xF1EFFF0C, 0xF01104F1, 0x10FF0A50, 0x000FF1C0, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1247             }
1248         },
1249         // B-Frame
1250         {
1251             // MEMethod: 0
1252             {
1253                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1254                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1255             },
1256         // MEMethod: 1
1257             {
1258                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1259                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1260             },
1261         // MEMethod: 2
1262             {
1263                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1264                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1265             },
1266         // MEMethod: 3
1267             {
1268                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1269                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1270             },
1271         // MEMethod: 4
1272             {
1273                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1274                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1275             },
1276         // MEMethod: 5
1277             {
1278                 0x0101F00F, 0x0F0F1010, 0xF0F0F00F, 0x01010101, 0x10101010, 0x0F0F0F0F, 0xF0F0F00F, 0x0101F0F0,
1279                 0x01010101, 0x10101010, 0x0F0F1010, 0x0F0F0F0F, 0xF0F0F00F, 0xF0F0F0F0, 0x00000000, 0x00000000
1280             },
1281         // MEMethod: 6
1282             {
1283                 0x120FF10F, 0x1E22E20D, 0x20E2FF10, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x4EF1F1F1, 0xF1F21211,
1284                 0x0DFFFFE0, 0x11201F1F, 0x1105F1CF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1285             },
1286         // MEMethod: 7 used for mpeg2 encoding B frames
1287             {
1288                 0x1F11F10F, 0x2E22E2FE, 0x20E220DF, 0x2EDD06FC, 0x11D33FF1, 0xEB1FF33D, 0x02F1F1F1, 0x1F201111,
1289                 0xF1EFFF0C, 0xF01104F1, 0x10FF0A50, 0x000FF1C0, 0x00000000, 0x00000000, 0x00000000, 0x00000000
1290             }
1291         }
1292     };
1293 
1294     // ME kernel
1295     enum
1296     {
1297         CODECHAL_ENCODE_ME_IDX_P     = 0,
1298         CODECHAL_ENCODE_ME_IDX_B     = 1,
1299         CODECHAL_ENCODE_ME_IDX_VDENC = 1,
1300         CODECHAL_ENCODE_ME_IDX_NUM   = 2
1301     };
1302 
1303     //!
1304     //! \struct    MediaObjectInlineData
1305     //! \brief     Media object inline data
1306     //!
1307     struct MediaObjectInlineData
1308     {
1309         // uint32_t 0
1310         union
1311         {
1312             struct
1313             {
1314                 uint32_t   mbHorizontalOrigin : 8;    // in MB unit
1315                 uint32_t   mbVerticalOrigin   : 8;    // in MB unit
1316                 uint32_t                      : 16;
1317             };
1318             // For BRC Block Copy kernels
1319             struct
1320             {
1321                 uint32_t   blockHeight        : 16;
1322                 uint32_t   bufferOffset       : 16;
1323             };
1324             struct
1325             {
1326                 uint32_t   value;
1327             };
1328         } DW0;
1329     };
1330 
1331     //!
1332     //! \brief    Constructor
1333     //!
1334     CodechalEncoderState(
1335         CodechalHwInterface* hwInterface,
1336         CodechalDebugInterface* debugInterface,
1337         PCODECHAL_STANDARD_INFO standardInfo);
1338 
1339     //!
1340     //! \brief    Destructor
1341     //!
1342     virtual ~CodechalEncoderState();
1343 
1344     // Encoder private data
1345     MhwVdboxMfxInterface*           m_mfxInterface = nullptr;                       //!< Mfx Interface
1346     MhwVdboxHcpInterface*           m_hcpInterface = nullptr;                       //!< Hcp Interface
1347     MhwVdboxHucInterface*           m_hucInterface = nullptr;                       //!< Huc Interface
1348     MhwVdboxVdencInterface*         m_vdencInterface = nullptr;                     //!< Vdenc Interface
1349     MhwMiInterface*                 m_miInterface = nullptr;                        //!< Mi Interface
1350     MhwRenderInterface*             m_renderEngineInterface = nullptr;              //!< Render engine interface
1351     PMHW_STATE_HEAP_INTERFACE       m_stateHeapInterface = nullptr;                 //!< State heap interface
1352     CodechalEncodeAllocator*        m_allocator = nullptr;                          //!< Resource allocator
1353     CodechalEncodeTrackedBuffer*    m_trackedBuf = nullptr;                         //!< Tracked buffer state
1354 
1355     PLATFORM                        m_platform = {};                                //!< The platorm info
1356     MEDIA_FEATURE_TABLE             *m_skuTable = nullptr;                          //!< SKU table
1357     MEDIA_WA_TABLE                  *m_waTable = nullptr;                           //!< WA table
1358     CodecHalMmcState*               m_mmcState = nullptr;                           //!< Memory compression
1359     MEDIA_SYSTEM_INFO               *m_gtSystemInfo = nullptr;                      //!< GT system infomation
1360     MOS_GPU_NODE                    m_videoGpuNode = MOS_GPU_NODE_MAX;              //!< GPU node of video
1361     MOS_GPU_CONTEXT                 m_videoContext = MOS_GPU_CONTEXT_INVALID_HANDLE;              //!< GPU context of video
1362     MOS_GPU_CONTEXT                 m_videoContextExt[4] = {};                           //!< Extand GPU context
1363     MOS_GPU_CONTEXT                 m_renderContext = MOS_GPU_CONTEXT_INVALID_HANDLE;             //!< GPU context of render
1364     bool                            m_pakEnabled = false;                           //!< flag to indicate if PAK is enabled
1365     bool                            m_encEnabled = false;                           //!< flag to indicate if ENC is enabled
1366     bool                            m_videoNodeAssociationCreated = false;          //!< flag to indicate if video node association is created
1367     bool                            m_computeContextEnabled = false;                //!< flag to indicate if compute context is enabled
1368     bool                            m_needCheckCpEnabled = false;                   //!< Indicate if checking cp is needed when prepare default nodes
1369     bool                            m_vdboxOneDefaultUsed = false;                  //!< Indicate VDBOX 1 is always used when prepare default nodes
1370 
1371     CodechalEncoderGenState*        m_encoderGenState = nullptr;          //!< Pointer to Gen Specific Encoder State
1372     CodechalEncodeCscDs*            m_cscDsState = nullptr;               //!< pointer to CSC Downscaling state
1373     CodechalEncodeWP*               m_wpState = nullptr;                  //!< pointer to weighted prediction state
1374     CODECHAL_FUNCTION               m_codecFunction = CODECHAL_FUNCTION_INVALID;                  //!< The encode state's codec function used
1375     uint32_t                        m_standard = 0;                       //!< The encode state's standard
1376     uint32_t                        m_mode = 0;                           //!< The encode mode
1377     MHW_WALKER_MODE                 m_walkerMode = MHW_WALKER_MODE_NOT_SET;                       //!< The encode walker's mode
1378     uint8_t                         m_kernelMode = 0;                     //!< normal, performance, quality.
1379 
1380     bool                            m_mfeEnabled = false;                //!< Mfe enabled
1381     bool                            m_mfeMbEncEanbled = false;           //!< Mfe MBEnc kernel enabled
1382     bool                            m_mfeLastStream = false;             //!< Is last stream during this submission
1383     bool                            m_mfeFirstStream = false;            //!< Is first stream during this submission
1384     bool                            m_mfeInitialized = false;            //!< Used for initializing MFE resources during first execute
1385     MfeParams                       m_mfeEncodeParams = {};              //!< Mfe encode params during this submission
1386     MfeSharedState *                m_mfeEncodeSharedState = nullptr;    //!< shared state from the parent context
1387 
1388     // Common Kernel Parameters
1389     uint8_t*                        m_kernelBase = nullptr;              //!< Kernel base address
1390     uint32_t                        m_kuid = 0;                          //!< Kernel unified ID
1391 
1392     // Per-frame Application Settings
1393     EncoderParams                   m_encodeParams = {};          //!< Encode parameters used in each frame
1394     uint32_t                        *m_dataHwCount = nullptr;     //!< HW count data
1395     MOS_RESOURCE                     m_resHwCount = {};                //!< Resource of HW count
1396     MOS_SURFACE                     m_prevRawSurface = {};        //!< Pointer to MOS_SURFACE of previous raw surface
1397     MOS_SURFACE                     m_rawSurface = {};            //!< Pointer to MOS_SURFACE of raw surface
1398     MOS_SURFACE                     m_reconSurface = {};          //!< Pointer to MOS_SURFACE of reconstructed surface
1399     MOS_RESOURCE                    m_resBitstreamBuffer = {};         //!< Pointer to MOS_SURFACE of bitstream surface
1400     PMOS_RESOURCE                   m_presMetadataBuffer = {};         //!< Pointer to metadata buffer
1401     MetaDataOffset                  m_metaDataOffset = {};             //!< meta data offset
1402     MOS_RESOURCE                    m_resMbCodeSurface = {};           //!< Pointer to MOS_SURFACE of MbCode surface
1403     MOS_RESOURCE                    m_resMvDataSurface = {};           //!< Pointer to MOS_SURFACE of MvData surface
1404     uint32_t                        m_mbDataBufferSize = 0;
1405     HwCounter                       m_regHwCount[CODECHAL_ENCODE_STATUS_NUM + 1] = {};    //!< HW count register value
1406 
1407     CODEC_PICTURE                   m_currOriginalPic = {};       //!< Raw.
1408     CODEC_PICTURE                   m_currReconstructedPic = {};  //!< Recon.
1409     uint16_t                        m_pictureCodingType = 0;      //!< I, P, or B frame
1410     int16_t                         m_frameNum = 0;               //!< Frame number
1411     bool                            m_firstFrame = true;          //!< Flag to indicate if it is first frame
1412     bool                            m_firstTwoFrames = false;     //!< Flag to indicate if they are first two frames
1413     bool                            m_firstField = true;          //!< Flag to indicate if it is first field
1414     bool                            m_resolutionChanged = false;  //!< Flag to indicate if resolution is changed
1415     bool                            m_scalingEnabled = false;     //!< 4x Scaling kernel needs to be called for this frame
1416     bool                            m_2xScalingEnabled = false;   //!< 2x Scaling kernel only used by HEVC now
1417     bool                            m_useRawForRef = false;       //!< Flag to indicate if using raw surface for reference
1418     bool                            m_disableReconMMCD = false;   //!< disable Recon surface's MMC
1419     bool                            m_repeatFrame = false;        //!< Flag to indicate if current frame is repeat frame
1420     bool                            m_pollingSyncEnabled = false; //!< Flag to indicate if GPU polling based sync for raw surface copy is enabled
1421     uint32_t                        m_syncMarkerOffset = 0;       //!< Sync marker offset in raw surface for GPU polling based sync
1422     uint32_t                        m_syncMarkerValue = 0;        //!< Sync marker value in raw surface for GPU polling based sync
1423     uint8_t                         m_prevReconFrameIdx = 0;      //!< Previous reconstruct frame index
1424     uint8_t                         m_currReconFrameIdx = 0;      //!< Current reconstruct frame index
1425 
1426     uint32_t                        m_frameWidth = 0;             //!< Frame width in luma samples
1427     uint32_t                        m_frameHeight = 0;            //!< Frame height in luma samples
1428     uint32_t                        m_frameFieldHeight = 0;       //!< Frame height in luma samples
1429     uint32_t                        m_oriFrameHeight = 0;         //!< Original frame height
1430     uint16_t                        m_frame_crop_bottom_offset = 0;       //!< frame_crop_bottom_offset
1431     uint16_t                        m_frame_mbs_only_flag      = 0;         //!< frame_mbs_only_flag
1432     uint32_t                        m_oriFrameWidth = 0;          //!< Original frame width
1433     uint32_t                        m_createWidth = 0;            //!< Max Frame Width for resolution reset
1434     uint32_t                        m_createHeight = 0;           //!< Max Frame Height for resolution reset
1435     uint16_t                        m_picWidthInMb = 0;           //!< Picture Width in MB width count
1436     uint16_t                        m_picHeightInMb = 0;          //!< Picture Height in MB height count
1437     uint16_t                        m_frameFieldHeightInMb = 0;   //!< Frame/field Height in MB
1438     uint32_t                        m_bitstreamUpperBound = 0;    //!< Bitstream upper bound
1439     uint8_t                         m_oriFieldCodingFlag = 0;     //!< Original field coding flag
1440     uint32_t                        m_maxBtCount = 0;             //!< Max bt count
1441     bool                            m_cmKernelEnable = false;     //!< Flag to indicate if cm kernel is enabled
1442     bool                            m_feiEnable = false;          //!< FEI is enabled
1443 
1444     // Synchronization
1445     MOS_RESOURCE                    m_resSyncObjectRenderContextInUse = {}; //!< Resource of the sync object to indicate render context is in use
1446     MOS_RESOURCE                    m_resSyncObjectVideoContextInUse = {};  //!< Resource of the sync object to indicate video context is in use
1447     bool                            m_waitForPak = false;              //!< Flag to indicate if waiting for PAK
1448     bool                            m_signalEnc = false;               //!< Flag used to signal ENC
1449     uint32_t                        m_semaphoreObjCount = 0;           //!< Count of semaphore objects
1450     uint32_t                        m_semaphoreMaxCount = 0;           //!< Max count of semaphore
1451 
1452     // Status Reporting
1453     bool                            m_codecGetStatusReportDefined = false;          //!< Need to be set to true by any codec/gen that has their own impleementation.
1454     uint32_t                        m_storeData = 0;                                //!< Stored data
1455     bool                            m_statusQueryReportingEnabled = false;                            //!< Flag to indicate if we support eStatus query reporting on current Platform
1456     EncodeStatusBuffer              m_encodeStatusBuf = {};                         //!< Stores all the status_query related data for PAK engine
1457     EncodeStatusBuffer              m_encodeStatusBufRcs = {};                      //!< Stores all the status_query related data for render ring (RCS)
1458     MHW_VDBOX_IMAGE_STATUS_CONTROL  m_imgStatusControlBuffer = {};                  //!< Stores image eStatus control data
1459     uint32_t                        m_statusReportFeedbackNumber = 0;               //!< Status report feed back number
1460     bool                            m_frameTrackingEnabled = false;                 //!< Flag to indicate if we enable KMD frame tracking
1461     uint32_t                        m_numberTilesInFrame = 0;                       //!< Track number of tiles per frame
1462     bool                            m_inlineEncodeStatusUpdate = false;             //!< check whether use inline encode status update or seperate BB
1463     AtomicScratchBuffer             m_atomicScratchBuf = {};                             //!< Stores atomic operands and result
1464     bool                            m_skipFrameBasedHWCounterRead = false;          //!< Skip reading Frame base HW counter for status report
1465     bool                            m_disableStatusReport = false;                  //!< Indicate status report is not needed.
1466 
1467     // Shared Parameters
1468     BSBuffer                        m_bsBuffer = {};                                //!< Bitstream buffer
1469     bool                            m_newSeqHeader = false;                         //!< New sequence header flag
1470     bool                            m_newPpsHeader = false;                         //!< New PPS header flag
1471     bool                            m_newVuiData = false;                           //!< New Vui data flag
1472     bool                            m_newSeq = false;                               //!< New sequence flag
1473     bool                            m_lastPicInSeq = false;                         //!< Flag to indicate if it is last picture in sequence
1474     bool                            m_lastPicInStream = false;                      //!< Flag to indicate if it is last picture in stream
1475     uint8_t                         m_numRefPair = 0;                               //!< number of reference pair (forward & backward)
1476     uint8_t                         m_numPasses = 0;                                //!< Number passes
1477     uint8_t                         m_currPass = 0;                                 //!< Current pass
1478     bool                            m_forceSinglePakPass = false;                   //!< Flag to enable forcing single pak pass
1479     bool                            m_useCmScalingKernel = false;                   //!< Flag to use cm scaling kernel
1480     bool                            m_useMwWlkrForAsmScalingKernel = false;         //!< Use media walker for ASM scaling kernel flag
1481     bool                            m_combinedDownScaleAndDepthConversion = false;  //!< Combied downscale and depth conversion
1482     bool                            m_bRenderOcaEnabled = false;                    //!< Should encoder support OCA for RCS
1483     uint32_t                        m_brcPakStatisticsSize = 0;                     //!< Bitrate control PAK statistics size
1484     uint32_t                        m_brcHistoryBufferSize = 0;                     //!< Bitrate control history buffer size
1485     uint32_t                        m_mbencBrcBufferSize = 0;                       //!< Mbenc bitrate control buffer size
1486     uint8_t                         m_numVdbox = 0;                                 //!< Number of vdbox
1487     uint8_t                         m_numUsedVdbox = 0;                             //!< Number of vdbox used
1488 
1489     // ENC/PAK batch buffer and surface indices
1490     PCODEC_REF_LIST                 m_currRefList = nullptr;        //!< Current reference list
1491     uint8_t                         m_currRecycledBufIdx = 0;       //!< Current recycled buffer index
1492     uint8_t                         m_currEncBbSet = 0;             //!< Current encode bb set
1493     uint8_t                         m_currMbCodeIdx = 0;            //!< Current mb code index
1494     uint8_t                         m_currMadBufferIdx = 0;         //!< Current mad buffer
1495     uint32_t                        m_recycledBufStatusNum[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM] = {0};  //!< Recycled buffer status num list
1496     uint32_t                        m_recycledBufWaitMs = 0;        //!< Recycled buffer wait (ms)
1497 
1498     // User Feature Key Capabilities
1499     bool                            m_hmeSupported = false;               //!< Flag to indicate if HME is supported
1500     bool                            m_noMeKernelForPFrame = false;        //!< HEVC does not have P-frame, no need to load P-frame ME kernel
1501     bool                            m_16xMeSupported = false;             //!< 16x ME supported
1502     bool                            m_16xMeUserfeatureControl = false;    //!< User feature control if 16x ME is supported
1503     bool                            m_32xMeSupported = false;             //!< 32x ME supported
1504     bool                            m_useNonLegacyStreamin = false;       //!< Use non-legacy stream in
1505     bool                            m_32xMeUserfeatureControl = false;    //!< User feature control if 32x ME is supported
1506     bool                            m_2xMeSupported = false;              //!< 2x DS surface, currently only used by Gen10 Hevc Encode
1507     bool                            m_suppressReconPicSupported = false;  //!< Suppress reconstructed picture supported flag
1508     bool                            m_useHwScoreboard = true;             //!< Flag to indicate if HW score board is used
1509     bool                            m_hwWalker = false;                   //!< HW walker used
1510     bool                            m_panicEnable                = false;                   //!< Rc panic enabled flag
1511     bool                            m_sliceShutdownEnable = false;        //!< Slice Shutdown Enable
1512     uint32_t                        m_encodeVfeMaxThreads = 0;            //!< Encode vfe max threads number
1513     uint32_t                        m_encodeVfeMaxThreadsScaling = 0;     //!< Encode vfe max threads scaling number
1514     uint32_t                        m_hwScoreboardType = 0;               //!< HW score board type
1515     bool                            m_flatnessCheckSupported = false;     //!< Flatness check supported flag
1516     bool                            m_groupIdSelectSupported = false;     //!< Group id select supported flag
1517     uint8_t                         m_groupId = 0;                        //!< Group id
1518     bool                            m_multipassBrcSupported = false;      //!< Multi-pass bitrate control supported flag
1519     uint8_t                         m_targetUsageOverride = 0;            //!< Target usage override
1520     bool                            m_userFeatureKeyReport = false;       //!< User feature key report flag
1521     bool                            m_singlePassDys = false;              //!< sungle pass dynamic scaling supported flag
1522 
1523     // CmdGen HuC FW for HEVC/VP9 VDEnc
1524     MOS_RESOURCE                    m_resVdencCmdInitializerDmemBuffer = {};   //!< Resource of vdenc command initializer DMEM buffer
1525     MOS_RESOURCE                    m_resVdencCmdInitializerDataBuffer[2] = {};   //!< Resource of vdenc command initializer data buffer
1526 
1527     // VDEnc params
1528     bool                            m_vdencEnabled = false;               //!< Vdenc enabled flag
1529     bool                            m_vdencBrcEnabled = false;            //!< Vdenc bitrate control enabled flag
1530     bool                            m_vdencStreamInEnabled = false;       //!< Vdenc stream in enabled flag
1531     bool                            m_vdencNoTailInsertion = false;       //!< Vdenc no tail insertion enabled flag
1532     uint32_t                        m_vdencBrcStatsBufferSize = 0;        //!< Vdenc bitrate control buffer size
1533     uint32_t                        m_vdencBrcPakStatsBufferSize = 0;     //!< Vdenc bitrate control PAK buffer size
1534     uint32_t                        m_vdencBrcNumOfSliceOffset = 0;       //!< Vdenc bitrate control number of slice offset
1535     bool                            m_waReadVDEncOverflowStatus = false;  //!< Read vdenc overflow status used flag
1536     bool                            m_vdencBrcImgStatAllocated = false;   //!< Vdenc bitrate control image state allocated flag
1537     uint32_t                        m_vdencMvTemporalBufferSize = 0;      //!< Vdenc temporal MV buffer size
1538 
1539     // VDEnc dynamic slice control params
1540     uint32_t                       m_vdencFlushDelayCount = 0;   //!< Vdenc flush delay count
1541 
1542     HMODULE                        m_swBrcMode = nullptr;        //!< Software bitrate control mode
1543 
1544     // IQmatrix params
1545     bool                            m_picQuant = false;          //!< picture quant
1546     bool                            m_newQmatrixData = false;    //!< New Qmatrix data
1547     PCODEC_ENCODER_SLCDATA          m_slcData = nullptr;         //!< record slice header size & position
1548     uint32_t                        m_numSlices = 0;             //!< Number of slices
1549     uint32_t                        m_numHuffBuffers = 0;        //!< Number of Huffman buffers
1550 
1551     // ENC input/output buffers
1552     uint32_t                        m_mbCodeStrideInDW = 0;         //!< Offset + Size of MB + size of MV
1553     uint32_t                        m_mbCodeOffset = 0;             //!< MB data offset
1554     uint32_t                        m_mvOffset = 0;                 //!< MV data offset, in 64 byte
1555     uint32_t                        m_mbCodeSize = 0;               //!< MB code buffer size
1556     uint32_t                        m_mbcodeBottomFieldOffset = 0;  //!< MB code offset frame/TopField - zero, BottomField - nonzero
1557     uint32_t                        m_mvDataSize = 0;               //!< MV data size
1558     uint32_t                        m_mvBottomFieldOffset = 0;      //!< MV data offset frame/TopField - zero, BottomField - nonzero
1559     MOS_RESOURCE                    m_resDistortionBuffer = {};          //!< MBEnc Distortion Buffer
1560     MOS_RESOURCE                    m_resMadDataBuffer[CODECHAL_ENCODE_MAX_NUM_MAD_BUFFERS] = {}; //!< Buffers to store Mean of Absolute Differences
1561     bool                            m_madEnabled = false;                                    //!< Mad enabled flag
1562 
1563     bool                            m_arbitraryNumMbsInSlice = false;                        //!< Flag to indicate if the sliceMapSurface needs to be programmed or not
1564     MOS_SURFACE                     m_sliceMapSurface[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM] = {};  //!< Slice map surface
1565     uint32_t                        m_sliceMapBottomFieldOffset = 0;                         //!< Slice map bottom field offset
1566 
1567     // VDENC and PAK Data Buffer
1568     PMOS_RESOURCE                   m_resVdencStatsBuffer = nullptr;               //!< Resource of Vdenc status buffer
1569     PMOS_RESOURCE                   m_resVdencCuObjStreamOutBuffer = nullptr;      //!< Resource of Vdenc Cu object stream out buffer
1570     PMOS_RESOURCE                   m_resVdencPakObjCmdStreamOutBuffer = nullptr;  //!< Resource of Vdenc Pak object command stream out buffer
1571     PMOS_RESOURCE                   m_resPakStatsBuffer = nullptr;                 //!< Resource of Pak status buffer
1572     PMOS_RESOURCE                   m_resSliceCountBuffer = nullptr;               //!< Resource of slice count buffer
1573     PMOS_RESOURCE                   m_resVdencModeTimerBuffer = nullptr;           //!< Resource of Vdenc mode timer buffer
1574 
1575     // VDEnc StreamIn Buffer
1576     MOS_RESOURCE                    m_resVdencStreamInBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM] = {};  //!< Resources of Vdenc stream in buffer
1577 
1578     // Maximum number of slices allowed by video spec
1579     uint32_t                        m_maxNumSlicesAllowed = 0;          //!< Max number of slices allowed
1580 
1581     //VDEnc HuC FW status
1582     MOS_RESOURCE                    m_resPakMmioBuffer = {};                 //!< Resource of PAK MMIO buffer
1583     MOS_RESOURCE                    m_resHucErrorStatusBuffer = {};          //!< Resource of Huc Error Status buffer
1584     MOS_RESOURCE                    m_resHucStatus2Buffer = {};              //!< Resource of HuC status 2 buffer
1585     MOS_RESOURCE                    m_resHucFwBuffer = {};                   //!< Resource of HuC Fw buffer
1586     PMOS_RESOURCE                   m_resVdencBrcUpdateDmemBufferPtr[2] = {nullptr, nullptr}; //!< One for 1st pass of next frame, and the other for the next pass of current frame.
1587 
1588     // PAK Scratch Buffers
1589     MOS_RESOURCE                    m_resDeblockingFilterRowStoreScratchBuffer = {};                 //!< Handle of deblock row store surface
1590     MOS_RESOURCE                    m_resMPCRowStoreScratchBuffer = {};                              //!< Handle of mpc row store surface
1591     MOS_RESOURCE                    m_resStreamOutBuffer[CODECHAL_ENCODE_RECYCLED_BUFFER_NUM] = {};  //!< Handle of streamout data surface
1592 
1593     // Scaling
1594     MHW_KERNEL_STATE                m_scaling4xKernelStates[CODEC_NUM_FIELDS_PER_FRAME];  //!< Scaling 4x Kernel States
1595     ScalingBindingTable             m_scaling4xBindingTable = {};                        //!< Scaling 4x Binding Table
1596     MHW_KERNEL_STATE                m_scaling2xKernelStates[CODEC_NUM_FIELDS_PER_FRAME];  //!< Scaling 2x Kernel States
1597     ScalingBindingTable             m_scaling2xBindingTable = {};                        //!< Scaling 2x Binding Table
1598     uint32_t                        m_scalingCurbeSize = 0;                               //!< Scaling curbe size
1599     bool                            m_interlacedFieldDisabled = false;                    //!< interlaced field disabled flag
1600     CodechalEncodeBbuf              m_scalingBBUF[CODECHAL_ENCODE_VME_BBUF_NUM] = {};     //!< This Batch Buffer is used for scaling kernel.
1601     uint32_t                        m_scaledBottomFieldOffset = 0;                        //!< Scaled Bottom Field Offset
1602     uint32_t                        m_scaled16xBottomFieldOffset = 0;                     //!< Scaled 16x Bottom Field Offset
1603     uint32_t                        m_scaled32xBottomFieldOffset = 0;                     //!< Scaled 32x Bottom Field Offset
1604     uint32_t                        m_scalingBBufIdx = 0;                                 //!< Scaling batch buffer index
1605     uint8_t                         m_minScaledDimension = 0;                             //!< min scaled dimension
1606     uint8_t                         m_minScaledDimensionInMb = 0;                         //!< min scaled dimension in Mb
1607     uint32_t                        m_downscaledWidth2x = 0;                              //!< Downscale width 2x
1608     uint32_t                        m_downscaledHeight2x = 0;                             //!< Downscale height 2x
1609     uint32_t                        m_downscaledWidth4x = 0;                              //!< Downscale width 4x
1610     uint32_t                        m_downscaledHeight4x = 0;                             //!< Downscale height 4x
1611     uint32_t                        m_downscaledWidthInMb4x = 0;                          //!< Downscale width in Mb 4x
1612     uint32_t                        m_downscaledHeightInMb4x = 0;                         //!< Downscale height in Mb 4x
1613     uint32_t                        m_downscaledFrameFieldHeightInMb4x = 0;               //!< Downscale frame field height in Mb 4x
1614     uint32_t                        m_downscaledWidth16x = 0;                             //!< Downscale width 16x
1615     uint32_t                        m_downscaledHeight16x = 0;                            //!< Downscale height 16x
1616     uint32_t                        m_downscaledWidthInMb16x = 0;                         //!< Downscale width in Mb 16x
1617     uint32_t                        m_downscaledHeightInMb16x = 0;                        //!< Downscale height in Mb 16x
1618     uint32_t                        m_downscaledFrameFieldHeightInMb16x = 0;              //!< Downscale frame field height in Mb 16x
1619     uint32_t                        m_downscaledWidth32x = 0;                             //!< Downscale width 2x
1620     uint32_t                        m_downscaledHeight32x = 0;                            //!< Downscale height 2x
1621     uint32_t                        m_downscaledWidthInMb32x = 0;                         //!< Downscale width 2x
1622     uint32_t                        m_downscaledHeightInMb32x = 0;                        //!< Downscale height 2x
1623     uint32_t                        m_downscaledFrameFieldHeightInMb32x = 0;              //!< Downscale frame field height in Mb 32x
1624 
1625     bool                            m_fieldScalingOutputInterleaved = false;              //!< Field scaling output interleaved flag
1626     MOS_SURFACE                     m_flatnessCheckSurface = {};                          //!< Flatness check surface
1627     uint32_t                        m_flatnessCheckBottomFieldOffset = 0;                 //!< Flatness check bottom field offset
1628     bool                            m_flatnessCheckEnabled = false;                       //!< Flatness check enabled flag
1629     bool                            m_mbStatsEnabled = false;                             //!< MB status enabled flag
1630     bool                            m_adaptiveTransformDecisionEnabled = false;                             //!< Adaptive Transform Decision Enabled flag
1631     bool                            m_forceBrcMbStatsEnabled           = false;                             //!< Force Brc Mb statistics Enabled flag
1632     uint32_t                        m_mbvProcStatsBottomFieldOffset    = 0;                                 //!< MB VProc statistics Bottom Field Offset
1633     CODECHAL_ENCODE_BUFFER          m_resMbStatisticsSurface;                                               //!< Resource of Mb statistics surface
1634     bool                            m_mbStatsSupported = false;                           //!< Mb statistics supported flag
1635     MOS_RESOURCE                    m_resMbStatsBuffer = {};                                   //!< Resource of Mb statistics buffer
1636     uint32_t                        m_mbStatsBottomFieldOffset = 0;                       //!< Mb statistics bottom field offset
1637 
1638     // ME
1639     MHW_KERNEL_STATE                m_meKernelStates[CODECHAL_ENCODE_ME_IDX_NUM];     //!< ME kernel states
1640     MeKernelBindingTable            m_meBindingTable = {};                            //!< ME binding table
1641     bool                            bStreamOutEnable = false;
1642     MOS_RESOURCE                    StreamOutBuffer = {};               // StreamOut buffer
1643 
1644     //GVA paramters to change inter and intra rounding
1645     bool                            bCoeffRoundTag = false;
1646     uint32_t                        uiRoundIntra = 0;
1647     uint32_t                        uiRoundInter = 0;
1648 
1649     // Ds+Copy kernel optimization
1650     uint8_t                         m_outputChromaFormat = (uint8_t)HCP_CHROMA_FORMAT_YUV420;     //!< 1: 420 2: 422 3: 444
1651     bool                            m_gopIsIdrFrameOnly = false;                                  //!< GOP structure contains I-frame only
1652     PMOS_SURFACE                    m_rawSurfaceToEnc = nullptr;                                  //!< raw surf to enc
1653     PMOS_SURFACE                    m_rawSurfaceToPak = nullptr;                                  //!< raw surf to pak
1654 
1655     // HME VDEnc
1656     GenericBindingTable             m_vdencMeKernelBindingTable = {};   //!< Vdenc ME kernel binding table
1657     MHW_KERNEL_STATE                m_vdencMeKernelState;               //!< Vdenc ME kernel state for Low Delay B
1658     MHW_KERNEL_STATE                m_vdencMeKernelStateRAB = {};       //!< Vdenc ME kernel state for Random Access B
1659 
1660     GenericBindingTable             m_vdencStreaminKernelBindingTable = {};  //!< Vdenc stream in kernel binding table
1661     MHW_KERNEL_STATE                m_vdencStreaminKernelState;         //!< Vdenc stream in kernel state for Low Delay B
1662     MHW_KERNEL_STATE                m_vdencStreaminKernelStateRAB;      //!< Vdenc stream in kernel state for Random Access B
1663 
1664     // Common kernel
1665     uint32_t                        m_kuidCommon = 0;                    //!< Common kernel UID
1666     bool                            m_useCommonKernel = false;           //!< Use common kernel
1667     bool                            m_wpUseCommonKernel = false;         //!< WP uses common kernel
1668 
1669     // Generic ENC parameters
1670     uint32_t                        m_verticalLineStride = 0;            //!< vertical line stride
1671     uint32_t                        m_verticalLineStrideOffset = 0;      //!< vertical line stride offset
1672 
1673     // CMD buffer sizes
1674     uint32_t                        m_pictureStatesSize = 0;             //!< Picture states size
1675     uint32_t                        m_extraPictureStatesSize = 0;        //!< Picture states size extra
1676     uint32_t                        m_sliceStatesSize = 0;               //!< Slice states size
1677     uint32_t                        m_vmeStatesSize = 0;                 //!< VME states size
1678     uint32_t                        m_hucCommandsSize = 0;               //!< HuC command size
1679 
1680     // Patch List Size
1681     uint32_t                        m_picturePatchListSize = 0;          //!< Picture patch list size
1682     uint32_t                        m_extraPicturePatchListSize = 0;     //!< Picture patch list size extra
1683     uint32_t                        m_slicePatchListSize = 0;            //!< Slice patch list size
1684     uint32_t                        m_vmePatchListSize = 0;              //!< not used yet, for future development
1685 
1686     // Single Task Phase parameters
1687     bool                            m_singleTaskPhaseSupported = false;      //!< Single task phase supported flag
1688     bool                            m_firstTaskInPhase = false;              //!< first task in phase flag
1689     bool                            m_lastTaskInPhase = false;               //!< last task in phase flag
1690     bool                            m_lastEncPhase = false;                  //!< first enc phase flag
1691     bool                            m_singleTaskPhaseSupportedInPak = false; //!< Single task phase supported in pak flag
1692     uint32_t                        m_headerBytesInserted = 0;               //!< Header bytes inserted flag
1693 
1694     // Null Rendering Flags
1695     bool                            m_videoContextUsesNullHw = false;        //!< Using null HW flags for video context
1696     bool                            m_renderContextUsesNullHw = false;       //!< Using null HW flags for render context
1697 
1698     // Slice Shutdown parameters
1699     bool                            m_setRequestedEUSlices = false;          //!< Flag to indicate the need to set requested EU slices
1700     bool                            m_setRequestedSubSlices = false;         //!< Flag to indicate the need to set requested EU sub-slices
1701     bool                            m_setRequestedEUs = false;               //!< Flag to indicate the need to set requested EUs
1702     uint32_t                        m_sliceShutdownDefaultState = 0;         //!< Default state of slice shutdown
1703     uint32_t                        m_sliceShutdownRequestState = 0;         //!< Request state of slice shutdown
1704     uint32_t                        m_ssdResolutionThreshold = 0;            //!< Resolution threshold for slice shutdown
1705     uint32_t                        m_ssdTargetUsageThreshold = 0;           //!< Target usage threshold for slice shutdown
1706     uint32_t                        m_targetUsage = 0;                       //!< Target usage
1707 
1708     // Skip frame params
1709     uint8_t                         m_skipFrameFlag = 0;        //!< Skip frame flag
1710     uint32_t                        m_numSkipFrames = 0;        //!< Number of skip frame
1711     uint32_t                        m_sizeSkipFrames = 0;       //!< acccumulative size of skipped frames for skipflag = 2
1712     uint32_t                        m_sizeCurrSkipFrame = 0;    //!< size of curr skipped frame for skipflag = 2
1713 
1714     // Lookahead
1715     uint8_t                         m_lookaheadDepth = 0;       //!< Number of frames to lookahead
1716     uint8_t                         m_currLaDataIdx = 0;        //!< Current lookahead data index
1717     uint32_t                        m_averageFrameSize = 0;     //!< Average frame size based on targed bitrate and frame rate, in unit of bits
1718     uint32_t                        m_prevTargetFrameSize = 0;  //!< Target frame size of previous frame.
1719     uint32_t                        m_targetBufferFulness = 0;  //!< Target encode buffer fulness in bits, used by BRC and calculated from initial buffer fulness, target frame size (from DDI) and average frame size
1720 
1721     MHW_VDBOX_NODE_IND              m_vdboxIndex = MHW_VDBOX_NODE_MAX;               //!< Index of vdbox
1722     MediaPerfProfiler               *m_perfProfiler = nullptr;  //!< Performance data profiler
1723     PMOS_GPUCTX_CREATOPTIONS        m_gpuCtxCreatOpt = nullptr; //!< Used for creating GPU context
1724     bool                            intraModeMaskControl = false;
1725     uint32_t                        intraModeMask = 0;  // to disable intra mode
1726     bool                            interMbTransformSizeControl = false;
1727     bool                            interMbTransform8x8Enabled = false;
1728 
1729     PMOS_RESOURCE                   presMbInlineData = nullptr;
1730     PMOS_RESOURCE                   presMbConstSurface = nullptr;
1731     PMOS_RESOURCE                   presVMEOutSurface = nullptr;
1732 
1733     MOS_RESOURCE                    m_predicationBuffer = {};     //! \brief Internal buffer for predication
1734 
1735 #if (_DEBUG || _RELEASE_INTERNAL)
1736     bool m_mmcUserFeatureUpdated;  //!< indicate if the user feature is updated with MMC state
1737 #endif
1738 
1739     CmDevice *m_cmDev     = nullptr;
1740     CmTask *  m_cmTask    = nullptr;
1741     CmQueue * m_cmQueue   = nullptr;
1742     CmDevice *m_origCmDev = nullptr;
1743 
1744 #define CM_EVENT_NUM 128
1745     CmEvent *m_cmEvent[CM_EVENT_NUM] = {nullptr};
1746     short    m_cmEventIdx = 0;  // current  event idx
1747     short    m_cmEventCheckIdx = 0;
1748 
1749 #ifdef FEI_ENABLE_CMRT
1750     CodechalEncodeMdfKernelResource resDSKernel;
1751 #endif
1752 
1753     bool m_colorbitSupported = false;
1754 
1755 #if USE_CODECHAL_DEBUG_TOOL
1756     CodechalDebugEncodePar          *m_encodeParState = nullptr;         //!< Encode Par state
1757 #endif
1758 
1759     //!
1760     //! \brief  Entry to allocate and intialize the encode instance
1761     //! \param  [in] codecHalSettings
1762     //!         The settings to inialize the encode instance
1763     //! \return MOS_STATUS
1764     //!         MOS_STATUS_SUCCESS if success, else fail reason
1765     //!
1766     MOS_STATUS Allocate(CodechalSetting * codecHalSettings) override;
1767 
1768     //!
1769     //! \brief  The entry to encode each frame.
1770     //! \param  [in] params
1771     //!         Pointer to encode parameters of this frame
1772     //! \return MOS_STATUS
1773     //!         MOS_STATUS_SUCCESS if success, else fail reason
1774     //!
1775     MOS_STATUS Execute(void *params) override;
1776 
1777     //!
1778     //! \brief  The entry to get status report.
1779     //! \param  [out] status
1780     //!         The point to encode status
1781     //! \param  [in] numStatus
1782     //!         The requested number of status reports
1783     //! \return MOS_STATUS
1784     //!         MOS_STATUS_SUCCESS if success, else fail reason
1785     //!
1786     MOS_STATUS GetStatusReport(void *status, uint16_t numStatus) override;
1787 
1788     //!
1789     //! \brief  Get Status Report for the common codec part
1790     //! \param  [out] encodeStatus
1791     //!         Encoder status
1792     //! \param  [out] encodeStatusReport
1793     //!         Encoder status report
1794     //! \return MOS_STATUS
1795     //!         MOS_STATUS_SUCCESS if success, else fail reason
1796     //!
1797     MOS_STATUS GetStatusReportCommon(
1798         EncodeStatus* encodeStatus,
1799         EncodeStatusReport* encodeStatusReport);
1800 
1801     //!
1802     //! \brief  Get Status Report extension
1803     //! \param  [out] encodeStatus
1804     //!         Encoder status
1805     //! \param  [out] encodeStatusReport
1806     //!         Encoder status report
1807     //! \param  [in] index
1808     //!         The index of status report number
1809     //! \return MOS_STATUS
1810     //!         MOS_STATUS_SUCCESS if success, else fail reason
1811     //!
GetStatusReportExt(EncodeStatus * encodeStatus,EncodeStatusReport * encodeStatusReport,uint16_t index)1812     virtual MOS_STATUS GetStatusReportExt(
1813         EncodeStatus* encodeStatus,
1814         EncodeStatusReport* encodeStatusReport,
1815         uint16_t index)
1816     {
1817         return MOS_STATUS_SUCCESS;
1818     };
1819 
1820     //!
1821     //! \brief  Read counter value for encode.
1822     //! \param  [in] index
1823     //!         The index of status report number
1824     //! \param  [in, out] encodeStatusReport
1825     //!         The address of encodeStatusReport
1826     //! \return MOS_STATUS
1827     //!         MOS_STATUS_SUCCESS if success, else fail reason
1828     //!
1829     MOS_STATUS ReadCounterValue(uint16_t index, EncodeStatusReport* encodeStatusReport);
1830 
1831     //!
1832     //! \brief  Initialize the encoder state
1833     //! \param  [in] settings
1834     //!         Pointer to the initialize settings
1835     //! \return MOS_STATUS
1836     //!         MOS_STATUS_SUCCESS if success, else fail reason
1837     //!
1838     virtual MOS_STATUS Initialize(
1839         CodechalSetting * settings);
1840 
1841     //!
1842     //! \brief  Allocate resources for encoder
1843     //! \return MOS_STATUS
1844     //!         MOS_STATUS_SUCCESS if success, else fail reason
1845     //!
1846     virtual MOS_STATUS AllocateResources();
1847 
1848     //!
1849     //! \brief  Free resources in encoder
1850     //! \return void
1851     //!
1852     virtual void FreeResources();
1853 
1854     //!
1855     //! \brief  Initialize the picture
1856     //! \param  [in] params
1857     //!         Encoder parameters
1858     //! \return MOS_STATUS
1859     //!         MOS_STATUS_SUCCESS if success, else fail reason
1860     //!
1861     virtual MOS_STATUS InitializePicture(const EncoderParams& params) = 0;
1862 
1863     //!
1864     //! \brief  Execute kernel functions
1865     //! \return MOS_STATUS
1866     //!         MOS_STATUS_SUCCESS if success, else fail reason
1867     //!
1868     virtual MOS_STATUS ExecuteKernelFunctions() = 0;
1869 
1870     //!
1871     //! \brief  Execute picture level in encoder
1872     //! \return MOS_STATUS
1873     //!         MOS_STATUS_SUCCESS if success, else fail reason
1874     //!
1875     virtual MOS_STATUS ExecutePictureLevel() = 0;
1876 
1877     //!
1878     //! \brief  Execute slice level in encoder
1879     //! \return MOS_STATUS
1880     //!         MOS_STATUS_SUCCESS if success, else fail reason
1881     //!
1882     virtual MOS_STATUS ExecuteSliceLevel() = 0;
1883 
1884     //!
1885     //! \brief  Get Status Report
1886     //! \details Each Codec need to define its own GetStatusReport
1887     //! \param  [out] encodeStatus
1888     //!         Encoder status
1889     //! \param  [out] encodeStatusReport
1890     //!         Encoder status report
1891     //! \return MOS_STATUS
1892     //!         MOS_STATUS_SUCCESS if success, else fail reason
1893     //!
1894     virtual MOS_STATUS GetStatusReport(
1895         EncodeStatus* encodeStatus,
1896         EncodeStatusReport* encodeStatusReport) = 0;
1897 
1898     //!
1899     //! \brief  User Feature Key Report
1900     //! \return MOS_STATUS
1901     //!         MOS_STATUS_SUCCESS if success, else fail reason
1902     //!
1903     virtual MOS_STATUS UserFeatureKeyReport();
1904 
1905     //!
1906     //! \brief    Help function to submit a command buffer
1907     //!
1908     //! \param    [in] cmdBuffer
1909     //!           Pointer to command buffer
1910     //! \param    [in] nullRendering
1911     //!           Null rendering flag
1912     //!
1913     //! \return   MOS_STATUS
1914     //!           MOS_STATUS_SUCCESS if success, else fail reason
1915     //!
1916     virtual MOS_STATUS SubmitCommandBuffer(
1917         PMOS_COMMAND_BUFFER cmdBuffer,
1918         bool             bNullRendering);
1919 
1920     //!
1921     //! \brief  Check Supported Format
1922     //! \param  [in] surface
1923     //!         Input surface to check
1924     //! \return bool
1925     //!         true if supported, false if not
1926     //!
1927     virtual bool CheckSupportedFormat(
1928         PMOS_SURFACE surface);
1929 
1930     //!
1931     //! \brief  Encode Copy Skip Frame
1932     //! \return MOS_STATUS
1933     //!         MOS_STATUS_SUCCESS if success, else fail reason
1934     //!
EncodeCopySkipFrame()1935     virtual MOS_STATUS EncodeCopySkipFrame()
1936     {
1937         return MOS_STATUS_SUCCESS;
1938     }
1939 
1940     //!
1941     //! \brief  Read Image Status
1942     //! \param  [in, out] cmdBuffer
1943     //!         Input and output cmdbuffer
1944     //! \return MOS_STATUS
1945     //!         MOS_STATUS_SUCCESS if success, else fail reason
1946     //!
1947     virtual MOS_STATUS ReadImageStatus(
1948         PMOS_COMMAND_BUFFER cmdBuffer);
1949 
1950     //!
1951     //! \brief  Read Mfc Status
1952     //! \param  [in, out] cmdBuffer
1953     //!         Input and output cmdbuffer
1954     //! \return MOS_STATUS
1955     //!         MOS_STATUS_SUCCESS if success, else fail reason
1956     //!
1957     virtual MOS_STATUS ReadMfcStatus(
1958         PMOS_COMMAND_BUFFER cmdBuffer);
1959 
1960     //!
1961     //! \brief  Send Prolog With Frame Tracking
1962     //! \param  [in, out] cmdBuffer
1963     //!         Input and output cmdbuffer
1964     //! \param  [in] frameTrackingRequested
1965     //!         frame Tracking Requested
1966     //! \return MOS_STATUS
1967     //!         MOS_STATUS_SUCCESS if success, else fail reason
1968     //!
1969     virtual MOS_STATUS SendPrologWithFrameTracking(
1970         PMOS_COMMAND_BUFFER cmdBuffer,
1971         bool frameTrackingRequested,
1972         MHW_MI_MMIOREGISTERS* mmioRegister = nullptr);
1973 
1974     //!
1975     //! \brief  Inserts predication command for a command buffer
1976     //! \param  [in] cmdBuffer
1977     //!         Command buffer
1978     //! \return MOS_STATUS
1979     //!         MOS_STATUS_SUCCESS if success, else fail reason
1980     //!
1981     MOS_STATUS SendPredicationCommand(
1982         PMOS_COMMAND_BUFFER cmdBuffer);
1983 
1984     //!
1985     //! \brief  Inserts marker commands for a command buffer
1986     //! \param  [in] cmdBuffer
1987     //!         Command buffer
1988     //! \param  [in] isRender
1989     //!         Whether render engine workload or not
1990     //! \return MOS_STATUS
1991     //!         MOS_STATUS_SUCCESS if success, else fail reason
1992     //!
1993     MOS_STATUS SendMarkerCommand(
1994         PMOS_COMMAND_BUFFER cmdBuffer,
1995         bool isRender);
1996 
1997     //!
1998     //! \brief  Calculate Command Buffer Size
1999     //!
2000     //! \return uint32_t
2001     //!         Command buffer size calculated
2002     //!
2003     virtual uint32_t CalculateCommandBufferSize();
2004 
2005     //!
2006     //! \brief  Prepare Nodes
2007     //! \param  [in, out] videoGpuNode
2008     //!         GPU node prepared
2009     //! \param  [in, out] setVideoNode
2010     //!         flag indicates if node needs to set
2011     //! \return void
2012     //!
2013     virtual void PrepareNodes(
2014         MOS_GPU_NODE& videoGpuNode,
2015         bool&         setVideoNode);
2016 
2017     //!
2018     //! \brief  Set up params for gpu context creation
2019     //! \return   MOS_STATUS
2020     //!           MOS_STATUS_SUCCESS if success, else fail reason
2021     //!
2022     virtual MOS_STATUS SetGpuCtxCreatOption();
2023 
2024     //!
2025     //! \brief  Sets video gpu context
2026     //!
SetVideoContext(MOS_GPU_CONTEXT videoContext)2027     void SetVideoContext(MOS_GPU_CONTEXT videoContext) { m_videoContext = videoContext; }
2028 
2029     //!
2030     //! \brief  Create Gpu Contexts
2031     //!
2032     //! \return MOS_STATUS
2033     //!         MOS_STATUS_SUCCESS if success, else fail reason
2034     //!
2035     virtual MOS_STATUS CreateGpuContexts();
2036 
2037     //!
2038     //! \brief  Verify Space Available
2039     //! \return MOS_STATUS
2040     //!         MOS_STATUS_SUCCESS if success, else fail reason
2041     //!
2042     MOS_STATUS VerifySpaceAvailable();
2043 
2044     //!
2045     //! \brief  Add MEDIA_VFE command to command buffer
2046     //! \param  [in, out] cmdBuffer
2047     //!         cmdbuffer to send cmds
2048     //! \param  [in] params
2049     //!         Parameters for send cmds
2050     //! \return MOS_STATUS
2051     //!         MOS_STATUS_SUCCESS if success, else fail reason
2052     //!
2053     virtual MOS_STATUS AddMediaVfeCmd(
2054         PMOS_COMMAND_BUFFER cmdBuffer,
2055         SendKernelCmdsParams *params);
2056 
2057     //!
2058     //! \brief  Send Generic Kernel Cmds
2059     //! \param  [in, out] cmdBuffer
2060     //!         cmdbuffer to send cmds
2061     //! \param  [in] params
2062     //!         Parameters for send cmds
2063     //! \return MOS_STATUS
2064     //!         MOS_STATUS_SUCCESS if success, else fail reason
2065     //!
2066     MOS_STATUS SendGenericKernelCmds(
2067         PMOS_COMMAND_BUFFER   cmdBuffer,
2068         SendKernelCmdsParams *params);
2069 
2070     //!
2071     //! \brief  Start Status Report
2072     //! \param  [in, out] cmdBuffer
2073     //!         cmdbuffer to send cmds
2074     //! \param  [in] encFunctionType
2075     //!         encFunctionType for send cmds
2076     //! \return MOS_STATUS
2077     //!         MOS_STATUS_SUCCESS if success, else fail reason
2078     //!
2079     MOS_STATUS StartStatusReport(
2080         PMOS_COMMAND_BUFFER cmdBuffer,
2081         CODECHAL_MEDIA_STATE_TYPE encFunctionType);
2082 
2083     //!
2084     //! \brief  End Status Report
2085     //! \param  [in, out] cmdBuffer
2086     //!         cmdbuffer to send cmds
2087     //! \param  [in] encFunctionType
2088     //!         encFunctionType for send cmds
2089     //! \return MOS_STATUS
2090     //!         MOS_STATUS_SUCCESS if success, else fail reason
2091     //!
2092     MOS_STATUS EndStatusReport(
2093         PMOS_COMMAND_BUFFER cmdBuffer,
2094         CODECHAL_MEDIA_STATE_TYPE encFunctionType);
2095 
2096     //!
2097     //! \brief  Set Status Report Parameters
2098     //! \param  [in] currRefList
2099     //!         current RefList used to set
2100     //! \return MOS_STATUS
2101     //!         MOS_STATUS_SUCCESS if success, else fail reason
2102     //!
2103     MOS_STATUS SetStatusReportParams(
2104         PCODEC_REF_LIST currRefList);
2105 
2106     //!
2107     //! \brief  Motion Estimation Disable Check
2108     //!
2109     //! \return void
2110     //!
2111     virtual void MotionEstimationDisableCheck();
2112 
2113     //!
2114     //! \brief  Execute the encode
2115     //!
2116     //! \param  [in] encodeParams
2117     //!         Encode parameters used
2118     //!
2119     //! \return MOS_STATUS
2120     //!         MOS_STATUS_SUCCESS if success, else fail reason
2121     //!
2122     MOS_STATUS ExecuteEnc(
2123         EncoderParams* encodeParams);
2124 
2125     //! \brief  Execute FEI PreEnc
2126     //!
2127     //! \param  [in] encodeParams
2128     //!         Encode parameters used
2129     //!
2130     //! \return MOS_STATUS
2131     //!         MOS_STATUS_SUCCESS if success, else fail reason
2132     //!
ExecutePreEnc(EncoderParams * encodeParams)2133     virtual MOS_STATUS ExecutePreEnc(
2134             EncoderParams* encodeParams) { return MOS_STATUS_SUCCESS; }
2135 
2136     //!
2137     //! \brief  Destroy Me Resources
2138     //!
2139     //! \param  [in] param
2140     //!         Hme parameters used
2141     //!
2142     //! \return MOS_STATUS
2143     //!         MOS_STATUS_SUCCESS if success, else fail reason
2144     //!
2145     MOS_STATUS DestroyMeResources(
2146         HmeParams* param);
2147 
2148     //!
2149     //! \brief  Clean Up Resource
2150     //!
2151     //! \param  [in, out] resource
2152     //!         Resource to clean up
2153     //! \param  [in] allocParams
2154     //!         allocParams used to clean
2155     //!
2156     //! \return MOS_STATUS
2157     //!         MOS_STATUS_SUCCESS if success, else fail reason
2158     //!
2159     MOS_STATUS CleanUpResource(
2160         PMOS_RESOURCE            resource,
2161         PMOS_ALLOC_GFXRES_PARAMS allocParams);
2162 
2163     //!
2164     //! \brief  Allocate Resources 4x Me
2165     //!
2166     //! \param  [in] param
2167     //!         Hme parameters used
2168     //!
2169     //! \return MOS_STATUS
2170     //!         MOS_STATUS_SUCCESS if success, else fail reason
2171     //!
2172     MOS_STATUS AllocateResources4xMe(
2173         HmeParams* param);
2174 
2175     //!
2176     //! \brief  Allocate Resources 16x Me
2177     //!
2178     //! \param  [in] param
2179     //!         Hme parameters used
2180     //!
2181     //! \return MOS_STATUS
2182     //!         MOS_STATUS_SUCCESS if success, else fail reason
2183     //!
2184     MOS_STATUS AllocateResources16xMe(
2185         HmeParams* param);
2186 
2187     //!
2188     //! \brief  Allocate Resources 32x Me
2189     //!
2190     //! \param  [in] param
2191     //!         Hme parameters used
2192     //!
2193     //! \return MOS_STATUS
2194     //!         MOS_STATUS_SUCCESS if success, else fail reason
2195     //!
2196     MOS_STATUS AllocateResources32xMe(
2197         HmeParams* param);
2198 
2199     //!
2200     //! \brief  Initialize Common
2201     //!
2202     //! \return MOS_STATUS
2203     //!         MOS_STATUS_SUCCESS if success, else fail reason
2204     //!
2205     MOS_STATUS InitCommon();
2206 
2207     //!
2208     //! \brief  Resize Internal Buffer on Resolution Change
2209     //!
2210     virtual void ResizeOnResChange();
2211 
2212     //!
2213     //! \brief   Check Resolution Change and CSC
2214     //!
2215     //! \details On resolution change, resize internal buffer
2216     //!          Check raw surface to set flag for CSC operation
2217     //!
2218     //! \return  MOS_STATUS
2219     //!          MOS_STATUS_SUCCESS if success, else fail reason
2220     //!
2221     virtual MOS_STATUS CheckResChangeAndCsc();
2222 
2223     //!
2224     //! \brief  Destroy encode state
2225     //!
2226     //! \return void
2227     //!
2228     void Destroy() override;
2229 
2230     //!
2231     //! \brief  Allocate Scaling Resources
2232     //!
2233     //! \return MOS_STATUS
2234     //!         MOS_STATUS_SUCCESS if success, else fail reason
2235     //!
2236     MOS_STATUS AllocateScalingResources();
2237 
2238     //!
2239     //! \brief  Execute Me Kernel
2240     //!
2241     //! \param  [in] meParams
2242     //!         meParams used to execute kernel
2243     //! \param  [in] meSurfaceParams
2244     //!         meSurfaceParams used to execute kernel
2245     //! \param  [in] hmeLevel
2246     //!         hme Level used to execute kernel
2247     //!
2248     //! \return MOS_STATUS
2249     //!         MOS_STATUS_SUCCESS if success, else fail reason
2250     //!
2251     virtual MOS_STATUS ExecuteMeKernel(
2252         MeCurbeParams *meParams,
2253         MeSurfaceParams *meSurfaceParams,
2254         HmeLevel hmeLevel);
2255 
2256     //!
2257     //! \brief  Initialize Status Report
2258     //!
2259     //! \return MOS_STATUS
2260     //!         MOS_STATUS_SUCCESS if success, else fail reason
2261     //!
2262     MOS_STATUS InitStatusReport();
2263 
2264     //!
2265     //! \brief  Update Encode Status
2266     //!
2267     //! \param  [in, out] cmdBuffer
2268     //!         cmdbuffer to send cmds
2269     //! \param  [in] forceOperation
2270     //!         forceOperation flag used
2271     //!
2272     //! \return MOS_STATUS
2273     //!         MOS_STATUS_SUCCESS if success, else fail reason
2274     //!
2275     MOS_STATUS UpdateEncodeStatus(
2276         PMOS_COMMAND_BUFFER cmdBuffer,
2277         bool                forceOperation);
2278 
2279     //!
2280     //! \brief  Reset Encode Status
2281     //!
2282     //! \return MOS_STATUS
2283     //!         MOS_STATUS_SUCCESS if success, else fail reason
2284     //!
2285     MOS_STATUS ResetStatusReport();
2286 
2287     //!
2288     //! \brief  Read Brc Pak Statistics
2289     //!
2290     //! \param  [in, out] cmdBuffer
2291     //!         cmdbuffer to send cmds
2292     //! \param  [in] params
2293     //!         parameters used
2294     //!
2295     //! \return MOS_STATUS
2296     //!         MOS_STATUS_SUCCESS if success, else fail reason
2297     //!
2298     MOS_STATUS ReadBrcPakStatistics(
2299         PMOS_COMMAND_BUFFER cmdBuffer,
2300         EncodeReadBrcPakStatsParams* params);
2301 
2302     //!
2303     //! \brief  Update command buffer attribute
2304     //!
2305     //! \param  [in] cmdBuffer
2306     //!         cmdbuffer to send cmds
2307     //! \param  [in] renderEngineInUse
2308     //!         renderEngineInUse flag used
2309     //!
2310     //! \return MOS_STATUS
2311     //!         MOS_STATUS_SUCCESS if success, else fail reason
2312     //!
2313     virtual MOS_STATUS UpdateCmdBufAttribute(
2314         PMOS_COMMAND_BUFFER cmdBuffer,
2315         bool                renderEngineInUse);
2316 
2317     //!
2318     //! \brief    Function pointer of Get Kernel Header And Size
2319     //!
2320     //! \return   MOS_STATUS
2321     //!           MOS_STATUS_SUCCESS if success, else fail reason
2322     //!
2323     MOS_STATUS(*pfnGetKernelHeaderAndSize) (
2324         void                            *binary,
2325         EncOperation                    operation,
2326         uint32_t                        krnStateIdx,
2327         void                            *krnHeader,
2328         uint32_t                        *krnSize);
2329 
2330     //!
2331     //! \brief    Function to allocate MDF required resources
2332     //!
2333     //! \return   MOS_STATUS
2334     //!           MOS_STATUS_SUCCESS if success, else fail reason
2335     //!
2336     virtual MOS_STATUS AllocateMDFResources();
2337 
2338     //!
2339     //! \brief    Function to destroy MDF required resources
2340     //!
2341     //! \return   MOS_STATUS
2342     //!           MOS_STATUS_SUCCESS if success, else fail reason
2343     //!
2344     virtual MOS_STATUS DestroyMDFResources();
2345 
2346     //!
2347     //! \brief    Function to set MFE Shared State
2348     //!
2349     //! \details  Pointer on passed object will be saved in the local field,
2350     //!           content of source object might be changed later
2351     //!           (for example, CmDevice might be set or chagned)
2352     //!
2353     //! \return   MOS_STATUS
2354     //!           MOS_STATUS_SUCCESS if success, else fail reason
2355     //!
2356     virtual MOS_STATUS SetMfeSharedState(MfeSharedState *pMfeSharedState);
2357 
2358     //!
2359     //! \brief  Function to add MDF kernel
2360     //!
2361     //! \param  [in] device
2362     //!         pointer to CmDevice
2363     //! \param  [in] queue
2364     //!         pointer to CmQueue
2365     //! \param  [in] kernel
2366     //!         pointer to CmKernel
2367     //! \param  [in] task
2368     //!         pointer to CmTask
2369     //! \param  [in] threadspace
2370     //!         pointer to CmThreadSpace
2371     //! \param  [in] event
2372     //!         reference to CmEvent*
2373     //! \param  [in] isEnqueue
2374     //!         bool
2375     //!
2376     //! \return MOS_STATUS
2377     //!         MOS_STATUS_SUCCESS if success, else fail reason
2378     //!
2379     MOS_STATUS AddKernelMdf(
2380         CmDevice      *device,
2381         CmQueue       *queue,
2382         CmKernel      *kernel,
2383         CmTask        *task,
2384         CmThreadSpace *threadspace,
2385         CmEvent       *&event,
2386         bool           isEnqueue);
2387 
2388     //!
2389     //! \brief  Function to create Mdf Kernel resource
2390     //!
2391     //! \param  [out] resource
2392     //!         pointer to CodechalEncodeMdfKernelResource
2393     //! \param  [in] kernelNum
2394     //!         uint8_t, kernel number
2395     //! \param  [in] bufNum
2396     //!         uint8_t, buffer number
2397     //! \param  [in] surfNum
2398     //!         uint8_t, surface number
2399     //! \param  [in] vmeSurfNum
2400     //!         uint8_t, vme surface number
2401     //! \param  [in] curbeSize
2402     //!         uint16_t, curbe structure size
2403     //!
2404     //! \return MOS_STATUS
2405     //!         MOS_STATUS_SUCCESS if success, else fail reason
2406     //!
2407     MOS_STATUS CreateMDFKernelResource(
2408         CodechalEncodeMdfKernelResource *resource,
2409         uint8_t                          kernelNum,
2410         uint8_t                          bufNum,
2411         uint8_t                          surfNum,
2412         uint8_t                          vmeSurfNum,
2413         uint16_t                         curbeSize);
2414 
2415     //!
2416     //! \brief    Function to destroy Mdf kernel resource
2417     //!
2418     //! \param    [in] resource
2419     //!           pointer to CodechalEncodeMdfKernelResource
2420     //!
2421     //! \return   MOS_STATUS
2422     //!           MOS_STATUS_SUCCESS if success, else fail reason
2423     //!
2424     MOS_STATUS DestroyMDFKernelResource(
2425         CodechalEncodeMdfKernelResource *resource);
2426 
2427     //!
2428     //! \brief    Function to free Mdf kernel surfaces
2429     //!
2430     //! \param    [in] resource
2431     //!           pointer to CodechalEncodeMdfKernelResource
2432     //!
2433     //! \return   MOS_STATUS
2434     //!           MOS_STATUS_SUCCESS if success, else fail reason
2435     //!
2436     MOS_STATUS FreeMDFKernelSurfaces(
2437         CodechalEncodeMdfKernelResource *resource);
2438 
2439     //!
2440     //! \brief  Returns number of PAK Passes based on BRC Precision flag
2441     //!
2442     //! \param  [in] usBRCPrecision
2443     //!         refer to CodechalEncodeBrcNumPasses
2444     //!
2445     //! \return uint8_t
2446     //!         number of pak passes
2447     //!
2448     uint8_t GetNumBrcPakPasses(uint16_t usBRCPrecision);
2449 
2450     //!
2451     //! \brief  Setup Walker Context
2452     //! \param  [in, out] cmdBuffer
2453     //!         Input and output cmdbuffer
2454     //! \param  [in] Pointer to kernel state
2455     //!
2456     //! \return MOS_STATUS
2457     //!         MOS_STATUS_SUCCESS if success, else fail reason
2458     //!
2459     virtual MOS_STATUS SetupWalkerContext(
2460         MOS_COMMAND_BUFFER* cmdBuffer,
2461         SendKernelCmdsParams* params);
2462 
2463     MOS_STATUS ResolveMetaData(
2464         PMOS_RESOURCE pHwLayoutMetaData,
2465         PMOS_RESOURCE pResolvedLayoutMetadata) override;
2466 
2467     MOS_STATUS ReportErrorFlag(
2468         PMOS_RESOURCE pMetadataBuffer,
2469         uint32_t      size,
2470         uint32_t      offset,
2471         uint32_t      flag) override;
2472 
PrepareHWMetaData(PMOS_RESOURCE presMetadataBuffer,PMOS_RESOURCE presLcuBaseAddressBuffer,PMOS_COMMAND_BUFFER cmdBuffer)2473     virtual MOS_STATUS PrepareHWMetaData(
2474         PMOS_RESOURCE           presMetadataBuffer,
2475         PMOS_RESOURCE           presLcuBaseAddressBuffer,
2476         PMOS_COMMAND_BUFFER     cmdBuffer)
2477     {
2478         return MOS_STATUS_SUCCESS;
2479     }
2480 
2481     //!
2482     //! \brief    Add store HUC_STATUS2 register
2483     //!
2484     //! \param    [in] cmdBuffer
2485     //!           Pointer to the command buffer
2486     //!
2487     //! \return   MOS_STATUS
2488     //!           MOS_STATUS_SUCCESS if success, else fail reason
2489     //!
2490     MOS_STATUS StoreHuCStatus2Report(PMOS_COMMAND_BUFFER cmdBuffer);
2491     //!
2492     //! \brief    Gets hardware interface.
2493     //! \return   CodechalHwInterface
2494     //!           return hardware interface
2495     //!
GetHwInterface()2496     CodechalHwInterface *GetHwInterface() { return m_hwInterface; }
2497 #if USE_CODECHAL_DEBUG_TOOL
2498     virtual MOS_STATUS DumpMbEncPakOutput(PCODEC_REF_LIST currRefList, CodechalDebugInterface* debugInterface);
DumpFrameStatsBuffer(CodechalDebugInterface * debugInterface)2499     virtual MOS_STATUS DumpFrameStatsBuffer(CodechalDebugInterface* debugInterface) { return MOS_STATUS_SUCCESS; }
2500 
2501     //!
2502     //! \brief  Add/Subtract a value to specified gfx memory
2503     //!
2504     //! \param  [in] cmdBuffer
2505     //!         command buffer
2506     //! \param  [in] presStoreBuffer
2507     //!         buffer to modify
2508     //! \param  [in] offset
2509     //!         member offset in the buffer
2510     //! \param  [in] value
2511     //!         value to add/subtract
2512     //! \param  [in] bAdd
2513     //!         add or subtract
2514     //!
2515     //! \return MOS_STATUS
2516     //!           MOS_STATUS_SUCCESS if success, else fail reason
2517     //!
2518     MOS_STATUS AddBufferWithIMMValue(
2519         PMOS_COMMAND_BUFFER         cmdBuffer,
2520         PMOS_RESOURCE               presStoreBuffer,
2521         uint32_t                    offset,
2522         uint32_t                    value,
2523         bool                        bAdd);
2524 
2525     //!
2526     //! \brief  Set a 16 bit value to specified gfx memory dword
2527     //!
2528     //! \param  [in] cmdBuffer
2529     //!         command buffer
2530     //! \param  [in] presStoreBuffer
2531     //!         buffer to modify
2532     //! \param  [in] offset
2533     //!         member offset in the buffer
2534     //! \param  [in] value
2535     //!         value to set
2536     //! \param  [in] bSecond
2537     //!         second or first word in dword
2538     //!
2539     //! \return MOS_STATUS
2540     //!         MOS_STATUS_SUCCESS if success, else fail reason
2541     //!
2542     MOS_STATUS SetBufferWithIMMValueU16(
2543         PMOS_COMMAND_BUFFER cmdBuffer,
2544         PMOS_RESOURCE       presStoreBuffer,
2545         uint32_t            offset,
2546         uint32_t            value,
2547         bool                bSecond);
2548 
2549     bool          m_enableFakeHrdSize   = false;
2550     int32_t       m_fakeIFrameHrdSize   = 0;
2551     int32_t       m_fakePBFrameHrdSize  = 0;
2552 #endif
2553 };
2554 
PutBit(BSBuffer * bsbuffer,uint32_t code)2555 static void PutBit(BSBuffer *bsbuffer, uint32_t code)
2556 {
2557     if (code & 1)
2558     {
2559         *(bsbuffer->pCurrent) = (*(bsbuffer->pCurrent) | (uint8_t)(0x01 << (7 - bsbuffer->BitOffset)));
2560     }
2561 
2562     bsbuffer->BitOffset++;
2563     if (bsbuffer->BitOffset == 8)
2564     {
2565         bsbuffer->BitOffset = 0;
2566         bsbuffer->pCurrent++;
2567         *(bsbuffer->pCurrent) = 0;
2568     }
2569 }
2570 
PutBitsSub(BSBuffer * bsbuffer,uint32_t code,uint32_t length)2571 static void PutBitsSub(BSBuffer *bsbuffer, uint32_t code, uint32_t length)
2572 {
2573     uint8_t *byte = bsbuffer->pCurrent;
2574 
2575     // make sure that the number of bits given is <= 24
2576     CODECHAL_ENCODE_ASSERT(length <= 24);
2577 
2578     code <<= (32 - length);
2579 
2580     // shift field so that the given code begins at the current bit
2581     // offset in the most significant byte of the 32-bit word
2582     length += bsbuffer->BitOffset;
2583     code >>= bsbuffer->BitOffset;
2584 
2585     // write bytes back into memory, big-endian
2586     byte[0] = (uint8_t)((code >> 24) | byte[0]);
2587     byte[1] = (uint8_t)(code >> 16);
2588     if (length > 16)
2589     {
2590         byte[2] = (uint8_t)(code >> 8);
2591         byte[3] = (uint8_t)code;
2592     }
2593     else
2594     {
2595         byte[2] = 0;
2596     }
2597 
2598     // update bitstream pointer and bit offset
2599     bsbuffer->pCurrent += (length >> 3);
2600     bsbuffer->BitOffset = (length & 7);
2601 }
2602 
PutBits(BSBuffer * bsbuffer,uint32_t code,uint32_t length)2603 static void PutBits(BSBuffer *bsbuffer, uint32_t code, uint32_t length)
2604 {
2605     uint32_t code1, code2;
2606 
2607     // temp solution, only support up to 32 bits based on current usage
2608     CODECHAL_ENCODE_ASSERT(length <= 32);
2609 
2610     if (length >= 24)
2611     {
2612         code1 = code & 0xFFFF;
2613         code2 = code >> 16;
2614 
2615         // high bits go first
2616         PutBitsSub(bsbuffer, code2, length - 16);
2617         PutBitsSub(bsbuffer, code1, 16);
2618     }
2619     else
2620     {
2621         PutBitsSub(bsbuffer, code, length);
2622     }
2623 }
2624 
2625 #endif  // __CODECHAL_ENCODER_BASE_H__
2626