silence compiler warning
[platform/upstream/libva-intel-driver.git] / src / gen6_mfc.c
1 /*
2  * Copyright © 2010-2011 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
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sub license, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial portions
14  * of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
19  * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
20  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *    Zhou Chang <chang.zhou@intel.com>
26  *
27  */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <assert.h>
33 #include <math.h>
34
35 #include "intel_batchbuffer.h"
36 #include "i965_defines.h"
37 #include "i965_structs.h"
38 #include "i965_drv_video.h"
39 #include "i965_encoder.h"
40 #include "i965_encoder_utils.h"
41 #include "gen6_mfc.h"
42 #include "gen6_vme.h"
43
44 #define CMD_LEN_IN_OWORD        4
45
46 #define BRC_CLIP(x, min, max) \
47 { \
48     x = ((x > (max)) ? (max) : ((x < (min)) ? (min) : x)); \
49 }
50
51 #define BRC_P_B_QP_DIFF 4
52 #define BRC_I_P_QP_DIFF 2
53 #define BRC_I_B_QP_DIFF (BRC_I_P_QP_DIFF + BRC_P_B_QP_DIFF)
54
55 #define BRC_PWEIGHT 0.6  /* weight if P slice with comparison to I slice */
56 #define BRC_BWEIGHT 0.25 /* weight if B slice with comparison to I slice */
57
58 #define BRC_QP_MAX_CHANGE 5 /* maximum qp modification */
59 #define BRC_CY 0.1 /* weight for */
60 #define BRC_CX_UNDERFLOW 5.
61 #define BRC_CX_OVERFLOW -4.
62
63 #define BRC_PI_0_5 1.5707963267948966192313216916398
64
65 typedef enum _gen6_brc_status
66 {
67     BRC_NO_HRD_VIOLATION = 0,
68     BRC_UNDERFLOW = 1,
69     BRC_OVERFLOW = 2,
70     BRC_UNDERFLOW_WITH_MAX_QP = 3,
71     BRC_OVERFLOW_WITH_MIN_QP = 4,
72 } gen6_brc_status;
73
74 static const uint32_t gen6_mfc_batchbuffer_avc_intra[][4] = {
75 #include "shaders/utils/mfc_batchbuffer_avc_intra.g6b"
76 };
77
78 static const uint32_t gen6_mfc_batchbuffer_avc_inter[][4] = {
79 #include "shaders/utils/mfc_batchbuffer_avc_inter.g6b"
80 };
81
82 static struct i965_kernel gen6_mfc_kernels[] = {
83     {
84         "MFC AVC INTRA BATCHBUFFER ",
85         MFC_BATCHBUFFER_AVC_INTRA,
86         gen6_mfc_batchbuffer_avc_intra,
87         sizeof(gen6_mfc_batchbuffer_avc_intra),
88         NULL
89     },
90
91     {
92         "MFC AVC INTER BATCHBUFFER ",
93         MFC_BATCHBUFFER_AVC_INTER,
94         gen6_mfc_batchbuffer_avc_inter,
95         sizeof(gen6_mfc_batchbuffer_avc_inter),
96         NULL
97     },
98 };
99
100 static void
101 gen6_mfc_pipe_mode_select(VADriverContextP ctx,
102                           int standard_select,
103                           struct intel_encoder_context *encoder_context)
104 {
105     struct intel_batchbuffer *batch = encoder_context->base.batch;
106     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
107
108     assert(standard_select == MFX_FORMAT_AVC);
109
110     BEGIN_BCS_BATCH(batch, 4);
111
112     OUT_BCS_BATCH(batch, MFX_PIPE_MODE_SELECT | (4 - 2));
113     OUT_BCS_BATCH(batch,
114                   (1 << 10) | /* disable Stream-Out , advanced QP/bitrate control need enable it*/
115                   ((!!mfc_context->post_deblocking_output.bo) << 9)  | /* Post Deblocking Output */
116                   ((!!mfc_context->pre_deblocking_output.bo) << 8)  | /* Pre Deblocking Output */
117                   (0 << 7)  | /* disable TLB prefectch */
118                   (0 << 5)  | /* not in stitch mode */
119                   (1 << 4)  | /* encoding mode */
120                   (2 << 0));  /* Standard Select: AVC */
121     OUT_BCS_BATCH(batch,
122                   (0 << 20) | /* round flag in PB slice */
123                   (0 << 19) | /* round flag in Intra8x8 */
124                   (0 << 7)  | /* expand NOA bus flag */
125                   (1 << 6)  | /* must be 1 */
126                   (0 << 5)  | /* disable clock gating for NOA */
127                   (0 << 4)  | /* terminate if AVC motion and POC table error occurs */
128                   (0 << 3)  | /* terminate if AVC mbdata error occurs */
129                   (0 << 2)  | /* terminate if AVC CABAC/CAVLC decode error occurs */
130                   (0 << 1)  | /* AVC long field motion vector */
131                   (0 << 0));  /* always calculate AVC ILDB boundary strength */
132     OUT_BCS_BATCH(batch, 0);
133
134     ADVANCE_BCS_BATCH(batch);
135 }
136
137 static void
138 gen6_mfc_surface_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
139 {
140     struct intel_batchbuffer *batch = encoder_context->base.batch;
141     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
142
143     BEGIN_BCS_BATCH(batch, 6);
144
145     OUT_BCS_BATCH(batch, MFX_SURFACE_STATE | (6 - 2));
146     OUT_BCS_BATCH(batch, 0);
147     OUT_BCS_BATCH(batch,
148                   ((mfc_context->surface_state.height - 1) << 19) |
149                   ((mfc_context->surface_state.width - 1) << 6));
150     OUT_BCS_BATCH(batch,
151                   (MFX_SURFACE_PLANAR_420_8 << 28) | /* 420 planar YUV surface */
152                   (1 << 27) | /* must be 1 for interleave U/V, hardware requirement */
153                   (0 << 22) | /* surface object control state, FIXME??? */
154                   ((mfc_context->surface_state.w_pitch - 1) << 3) | /* pitch */
155                   (0 << 2)  | /* must be 0 for interleave U/V */
156                   (1 << 1)  | /* must be y-tiled */
157                   (I965_TILEWALK_YMAJOR << 0));                         /* tile walk, TILEWALK_YMAJOR */
158     OUT_BCS_BATCH(batch,
159                   (0 << 16) |                                                           /* must be 0 for interleave U/V */
160                   (mfc_context->surface_state.h_pitch));                /* y offset for U(cb) */
161     OUT_BCS_BATCH(batch, 0);
162     ADVANCE_BCS_BATCH(batch);
163 }
164
165 static void
166 gen6_mfc_pipe_buf_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
167 {
168     struct intel_batchbuffer *batch = encoder_context->base.batch;
169     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
170     int i;
171
172     BEGIN_BCS_BATCH(batch, 24);
173
174     OUT_BCS_BATCH(batch, MFX_PIPE_BUF_ADDR_STATE | (24 - 2));
175
176     if (mfc_context->pre_deblocking_output.bo)
177         OUT_BCS_RELOC(batch, mfc_context->pre_deblocking_output.bo,
178                       I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
179                       0);
180     else
181         OUT_BCS_BATCH(batch, 0);                                                                                        /* pre output addr   */
182
183     if (mfc_context->post_deblocking_output.bo)
184         OUT_BCS_RELOC(batch, mfc_context->post_deblocking_output.bo,
185                       I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
186                       0);                                                                                       /* post output addr  */ 
187     else
188         OUT_BCS_BATCH(batch, 0);
189
190     OUT_BCS_RELOC(batch, mfc_context->uncompressed_picture_source.bo,
191                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
192                   0);                                                                                   /* uncompressed data */
193     OUT_BCS_RELOC(batch, mfc_context->macroblock_status_buffer.bo,
194                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
195                   0);                                                                                   /* StreamOut data*/
196     OUT_BCS_RELOC(batch, mfc_context->intra_row_store_scratch_buffer.bo,
197                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
198                   0);   
199     OUT_BCS_RELOC(batch, mfc_context->deblocking_filter_row_store_scratch_buffer.bo,
200                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
201                   0);
202     /* 7..22 Reference pictures*/
203     for (i = 0; i < ARRAY_ELEMS(mfc_context->reference_surfaces); i++) {
204         if ( mfc_context->reference_surfaces[i].bo != NULL) {
205             OUT_BCS_RELOC(batch, mfc_context->reference_surfaces[i].bo,
206                           I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
207                           0);                   
208         } else {
209             OUT_BCS_BATCH(batch, 0);
210         }
211     }
212     OUT_BCS_RELOC(batch, mfc_context->macroblock_status_buffer.bo,
213                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
214                   0);                                                                                   /* Macroblock status buffer*/
215
216     ADVANCE_BCS_BATCH(batch);
217 }
218
219 static void
220 gen6_mfc_ind_obj_base_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
221 {
222     struct intel_batchbuffer *batch = encoder_context->base.batch;
223     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
224     struct gen6_vme_context *vme_context = encoder_context->vme_context;
225
226     BEGIN_BCS_BATCH(batch, 11);
227
228     OUT_BCS_BATCH(batch, MFX_IND_OBJ_BASE_ADDR_STATE | (11 - 2));
229     OUT_BCS_BATCH(batch, 0);
230     OUT_BCS_BATCH(batch, 0);
231     /* MFX Indirect MV Object Base Address */
232     OUT_BCS_RELOC(batch, vme_context->vme_output.bo, I915_GEM_DOMAIN_INSTRUCTION, 0, 0);
233     OUT_BCS_BATCH(batch, 0);    
234     OUT_BCS_BATCH(batch, 0);
235     OUT_BCS_BATCH(batch, 0);
236     OUT_BCS_BATCH(batch, 0);
237     OUT_BCS_BATCH(batch, 0);
238     /*MFC Indirect PAK-BSE Object Base Address for Encoder*/    
239     OUT_BCS_RELOC(batch,
240                   mfc_context->mfc_indirect_pak_bse_object.bo,
241                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
242                   0);
243     OUT_BCS_RELOC(batch,
244                   mfc_context->mfc_indirect_pak_bse_object.bo,
245                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
246                   mfc_context->mfc_indirect_pak_bse_object.end_offset);
247
248     ADVANCE_BCS_BATCH(batch);
249 }
250
251 static void
252 gen6_mfc_bsp_buf_base_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
253 {
254     struct intel_batchbuffer *batch = encoder_context->base.batch;
255     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
256
257     BEGIN_BCS_BATCH(batch, 4);
258
259     OUT_BCS_BATCH(batch, MFX_BSP_BUF_BASE_ADDR_STATE | (4 - 2));
260     OUT_BCS_RELOC(batch, mfc_context->bsd_mpc_row_store_scratch_buffer.bo,
261                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
262                   0);
263     OUT_BCS_BATCH(batch, 0);
264     OUT_BCS_BATCH(batch, 0);
265
266     ADVANCE_BCS_BATCH(batch);
267 }
268
269 static void
270 gen6_mfc_avc_img_state(VADriverContextP ctx,struct encode_state *encode_state,
271                        struct intel_encoder_context *encoder_context)
272 {
273     struct intel_batchbuffer *batch = encoder_context->base.batch;
274     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
275     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
276     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
277     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
278     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
279
280     BEGIN_BCS_BATCH(batch, 13);
281     OUT_BCS_BATCH(batch, MFX_AVC_IMG_STATE | (13 - 2));
282     OUT_BCS_BATCH(batch, 
283                   ((width_in_mbs * height_in_mbs) & 0xFFFF));
284     OUT_BCS_BATCH(batch, 
285                   (height_in_mbs << 16) | 
286                   (width_in_mbs << 0));
287     OUT_BCS_BATCH(batch, 
288                   (0 << 24) |     /*Second Chroma QP Offset*/
289                   (0 << 16) |     /*Chroma QP Offset*/
290                   (0 << 14) |   /*Max-bit conformance Intra flag*/
291                   (0 << 13) |   /*Max Macroblock size conformance Inter flag*/
292                   (1 << 12) |   /*Should always be written as "1" */
293                   (0 << 10) |   /*QM Preset FLag */
294                   (0 << 8)  |   /*Image Structure*/
295                   (0 << 0) );   /*Current Decoed Image Frame Store ID, reserved in Encode mode*/
296     OUT_BCS_BATCH(batch,
297                   (400 << 16) |   /*Mininum Frame size*/        
298                   (0 << 15) |   /*Disable reading of Macroblock Status Buffer*/
299                   (0 << 14) |   /*Load BitStream Pointer only once, 1 slic 1 frame*/
300                   (0 << 13) |   /*CABAC 0 word insertion test enable*/
301                   (1 << 12) |   /*MVUnpackedEnable,compliant to DXVA*/
302                   (1 << 10) |   /*Chroma Format IDC, 4:2:0*/
303                   (pPicParameter->pic_fields.bits.entropy_coding_mode_flag << 7)  |   /*0:CAVLC encoding mode,1:CABAC*/
304                   (0 << 6)  |   /*Only valid for VLD decoding mode*/
305                   (0 << 5)  |   /*Constrained Intra Predition Flag, from PPS*/
306                   (pSequenceParameter->seq_fields.bits.direct_8x8_inference_flag << 4)  |   /*Direct 8x8 inference flag*/
307                   (pPicParameter->pic_fields.bits.transform_8x8_mode_flag << 3)  |   /*8x8 or 4x4 IDCT Transform Mode Flag*/
308                   (1 << 2)  |   /*Frame MB only flag*/
309                   (0 << 1)  |   /*MBAFF mode is in active*/
310                   (0 << 0) );   /*Field picture flag*/
311     OUT_BCS_BATCH(batch, 
312                   (1<<16)   |   /*Frame Size Rate Control Flag*/  
313                   (1<<12)   |   
314                   (1<<9)    |   /*MB level Rate Control Enabling Flag*/
315                   (1 << 3)  |   /*FrameBitRateMinReportMask*/
316                   (1 << 2)  |   /*FrameBitRateMaxReportMask*/
317                   (1 << 1)  |   /*InterMBMaxSizeReportMask*/
318                   (1 << 0) );   /*IntraMBMaxSizeReportMask*/
319     OUT_BCS_BATCH(batch,                        /*Inter and Intra Conformance Max size limit*/
320                   (0x0600 << 16) |              /*InterMbMaxSz 192 Byte*/
321                   (0x0800) );                   /*IntraMbMaxSz 256 Byte*/
322     OUT_BCS_BATCH(batch, 0x00000000);   /*Reserved : MBZReserved*/
323     OUT_BCS_BATCH(batch, 0x01020304);   /*Slice QP Delta for bitrate control*/                  
324     OUT_BCS_BATCH(batch, 0xFEFDFCFB);           
325     OUT_BCS_BATCH(batch, 0x80601004);   /*MAX = 128KB, MIN = 64KB*/
326     OUT_BCS_BATCH(batch, 0x00800001);   
327     OUT_BCS_BATCH(batch, 0);
328
329     ADVANCE_BCS_BATCH(batch);
330 }
331
332 static void
333 gen6_mfc_avc_directmode_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
334 {
335     struct intel_batchbuffer *batch = encoder_context->base.batch;
336     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
337
338     int i;
339
340     BEGIN_BCS_BATCH(batch, 69);
341
342     OUT_BCS_BATCH(batch, MFX_AVC_DIRECTMODE_STATE | (69 - 2));
343
344     /* Reference frames and Current frames */
345     for(i = 0; i < NUM_MFC_DMV_BUFFERS; i++) {
346         if ( mfc_context->direct_mv_buffers[i].bo != NULL) { 
347             OUT_BCS_RELOC(batch, mfc_context->direct_mv_buffers[i].bo,
348                           I915_GEM_DOMAIN_INSTRUCTION, 0,
349                           0);
350         } else {
351             OUT_BCS_BATCH(batch, 0);
352         }
353     }
354
355     /* POL list */
356     for(i = 0; i < 32; i++) {
357         OUT_BCS_BATCH(batch, i/2);
358     }
359     OUT_BCS_BATCH(batch, 0);
360     OUT_BCS_BATCH(batch, 0);
361
362     ADVANCE_BCS_BATCH(batch);
363 }
364
365 static void
366 gen6_mfc_avc_slice_state(VADriverContextP ctx,
367                          VAEncPictureParameterBufferH264 *pic_param,
368                          VAEncSliceParameterBufferH264 *slice_param,
369                          struct encode_state *encode_state,
370                          struct intel_encoder_context *encoder_context,
371                          int rate_control_enable,
372                          int qp,
373                          struct intel_batchbuffer *batch)
374 {
375     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
376     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
377     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
378     int beginmb = slice_param->macroblock_address;
379     int endmb = beginmb + slice_param->num_macroblocks;
380     int beginx = beginmb % width_in_mbs;
381     int beginy = beginmb / width_in_mbs;
382     int nextx =  endmb % width_in_mbs;
383     int nexty = endmb / width_in_mbs;
384     int slice_type = slice_param->slice_type;
385     int last_slice = (endmb == (width_in_mbs * height_in_mbs));
386     int bit_rate_control_target, maxQpN, maxQpP;
387     unsigned char correct[6], grow, shrink;
388     int i;
389     int weighted_pred_idc = 0;
390     unsigned int luma_log2_weight_denom = slice_param->luma_log2_weight_denom;
391     unsigned int chroma_log2_weight_denom = slice_param->chroma_log2_weight_denom;
392
393     if (batch == NULL)
394         batch = encoder_context->base.batch;
395
396     bit_rate_control_target = slice_type;
397     if (slice_type == SLICE_TYPE_SP)
398         bit_rate_control_target = SLICE_TYPE_P;
399     else if (slice_type == SLICE_TYPE_SI)
400         bit_rate_control_target = SLICE_TYPE_I;
401
402     if (slice_type == SLICE_TYPE_P) {
403         weighted_pred_idc = pic_param->pic_fields.bits.weighted_pred_flag;
404     } else if (slice_type == SLICE_TYPE_B) {
405         weighted_pred_idc = pic_param->pic_fields.bits.weighted_bipred_idc;
406
407         if (weighted_pred_idc == 2) {
408             /* 8.4.3 - Derivation process for prediction weights (8-279) */
409             luma_log2_weight_denom = 5;
410             chroma_log2_weight_denom = 5;
411         }
412     }
413
414     maxQpN = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpNegModifier;
415     maxQpP = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpPosModifier;
416
417     for (i = 0; i < 6; i++)
418         correct[i] = mfc_context->bit_rate_control_context[bit_rate_control_target].Correct[i];
419
420     grow = mfc_context->bit_rate_control_context[bit_rate_control_target].GrowInit + 
421         (mfc_context->bit_rate_control_context[bit_rate_control_target].GrowResistance << 4);
422     shrink = mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkInit + 
423         (mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkResistance << 4);
424
425     BEGIN_BCS_BATCH(batch, 11);;
426
427     OUT_BCS_BATCH(batch, MFX_AVC_SLICE_STATE | (11 - 2) );
428     OUT_BCS_BATCH(batch, slice_type);                   /*Slice Type: I:P:B Slice*/
429
430     if (slice_type == SLICE_TYPE_I) {
431         OUT_BCS_BATCH(batch, 0);                        /*no reference frames and pred_weight_table*/
432     } else {
433         OUT_BCS_BATCH(batch,
434                       (1 << 16) |                       /*1 reference frame*/
435                       (chroma_log2_weight_denom << 8) |
436                       (luma_log2_weight_denom << 0));
437     }
438
439     OUT_BCS_BATCH(batch, 
440                   (weighted_pred_idc << 30) |
441                   (slice_param->direct_spatial_mv_pred_flag<<29) |             /*Direct Prediction Type*/
442                   (slice_param->disable_deblocking_filter_idc << 27) |
443                   (slice_param->cabac_init_idc << 24) |
444                   (qp<<16) |                    /*Slice Quantization Parameter*/
445                   ((slice_param->slice_beta_offset_div2 & 0xf) << 8) |
446                   ((slice_param->slice_alpha_c0_offset_div2 & 0xf) << 0));
447     OUT_BCS_BATCH(batch,
448                   (beginy << 24) |                      /*First MB X&Y , the begin postion of current slice*/
449                   (beginx << 16) |
450                   slice_param->macroblock_address );
451     OUT_BCS_BATCH(batch, (nexty << 16) | nextx);                       /*Next slice first MB X&Y*/
452     OUT_BCS_BATCH(batch, 
453                   (0/*rate_control_enable*/ << 31) |            /*in CBR mode RateControlCounterEnable = enable*/
454                   (1 << 30) |           /*ResetRateControlCounter*/
455                   (0 << 28) |           /*RC Triggle Mode = Always Rate Control*/
456                   (4 << 24) |     /*RC Stable Tolerance, middle level*/
457                   (0/*rate_control_enable*/ << 23) |     /*RC Panic Enable*/                 
458                   (0 << 22) |     /*QP mode, don't modfiy CBP*/
459                   (0 << 21) |     /*MB Type Direct Conversion Enabled*/ 
460                   (0 << 20) |     /*MB Type Skip Conversion Enabled*/ 
461                   (last_slice << 19) |     /*IsLastSlice*/
462                   (0 << 18) |   /*BitstreamOutputFlag Compressed BitStream Output Disable Flag 0:enable 1:disable*/
463                   (1 << 17) |       /*HeaderPresentFlag*/       
464                   (1 << 16) |       /*SliceData PresentFlag*/
465                   (1 << 15) |       /*TailPresentFlag*/
466                   (1 << 13) |       /*RBSP NAL TYPE*/   
467                   (0 << 12) );    /*CabacZeroWordInsertionEnable*/
468     OUT_BCS_BATCH(batch, mfc_context->mfc_indirect_pak_bse_object.offset);
469     OUT_BCS_BATCH(batch,
470                   (maxQpN << 24) |     /*Target QP - 24 is lowest QP*/ 
471                   (maxQpP << 16) |     /*Target QP + 20 is highest QP*/
472                   (shrink << 8)  |
473                   (grow << 0));   
474     OUT_BCS_BATCH(batch,
475                   (correct[5] << 20) |
476                   (correct[4] << 16) |
477                   (correct[3] << 12) |
478                   (correct[2] << 8) |
479                   (correct[1] << 4) |
480                   (correct[0] << 0));
481     OUT_BCS_BATCH(batch, 0);
482
483     ADVANCE_BCS_BATCH(batch);
484 }
485
486 static void gen6_mfc_avc_qm_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
487 {
488     struct intel_batchbuffer *batch = encoder_context->base.batch;
489     int i;
490
491     BEGIN_BCS_BATCH(batch, 58);
492
493     OUT_BCS_BATCH(batch, MFX_AVC_QM_STATE | 56);
494     OUT_BCS_BATCH(batch, 0xFF ) ; 
495     for( i = 0; i < 56; i++) {
496         OUT_BCS_BATCH(batch, 0x10101010); 
497     }   
498
499     ADVANCE_BCS_BATCH(batch);
500 }
501
502 static void gen6_mfc_avc_fqm_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
503 {
504     struct intel_batchbuffer *batch = encoder_context->base.batch;
505     int i;
506
507     BEGIN_BCS_BATCH(batch, 113);
508     OUT_BCS_BATCH(batch, MFC_AVC_FQM_STATE | (113 - 2));
509
510     for(i = 0; i < 112;i++) {
511         OUT_BCS_BATCH(batch, 0x10001000);
512     }   
513
514     ADVANCE_BCS_BATCH(batch);   
515 }
516
517 static void
518 gen6_mfc_avc_ref_idx_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
519 {
520     struct intel_batchbuffer *batch = encoder_context->base.batch;
521     int i;
522
523     BEGIN_BCS_BATCH(batch, 10);
524     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
525     OUT_BCS_BATCH(batch, 0);                  //Select L0
526     OUT_BCS_BATCH(batch, 0x80808020);         //Only 1 reference
527     for(i = 0; i < 7; i++) {
528         OUT_BCS_BATCH(batch, 0x80808080);
529     }   
530     ADVANCE_BCS_BATCH(batch);
531
532     BEGIN_BCS_BATCH(batch, 10);
533     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
534     OUT_BCS_BATCH(batch, 1);                  //Select L1
535     OUT_BCS_BATCH(batch, 0x80808022);         //Only 1 reference
536     for(i = 0; i < 7; i++) {
537         OUT_BCS_BATCH(batch, 0x80808080);
538     }   
539     ADVANCE_BCS_BATCH(batch);
540 }
541         
542 static void
543 gen6_mfc_avc_insert_object(VADriverContextP ctx, struct intel_encoder_context *encoder_context,
544                            unsigned int *insert_data, int lenght_in_dws, int data_bits_in_last_dw,
545                            int skip_emul_byte_count, int is_last_header, int is_end_of_slice, int emulation_flag,
546                            struct intel_batchbuffer *batch)
547 {
548     if (batch == NULL)
549         batch = encoder_context->base.batch;
550
551     BEGIN_BCS_BATCH(batch, lenght_in_dws + 2);
552
553     OUT_BCS_BATCH(batch, MFC_AVC_INSERT_OBJECT | (lenght_in_dws + 2 - 2));
554
555     OUT_BCS_BATCH(batch,
556                   (0 << 16) |   /* always start at offset 0 */
557                   (data_bits_in_last_dw << 8) |
558                   (skip_emul_byte_count << 4) |
559                   (!!emulation_flag << 3) |
560                   ((!!is_last_header) << 2) |
561                   ((!!is_end_of_slice) << 1) |
562                   (0 << 0));    /* FIXME: ??? */
563
564     intel_batchbuffer_data(batch, insert_data, lenght_in_dws * 4);
565     ADVANCE_BCS_BATCH(batch);
566 }
567
568 static void gen6_mfc_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
569 {
570     struct i965_driver_data *i965 = i965_driver_data(ctx);
571     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
572     dri_bo *bo;
573     int i;
574
575     /*Encode common setup for MFC*/
576     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
577     mfc_context->post_deblocking_output.bo = NULL;
578
579     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
580     mfc_context->pre_deblocking_output.bo = NULL;
581
582     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
583     mfc_context->uncompressed_picture_source.bo = NULL;
584
585     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
586     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
587
588     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
589         if ( mfc_context->direct_mv_buffers[i].bo != NULL);
590         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
591         mfc_context->direct_mv_buffers[i].bo = NULL;
592     }
593
594     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
595         if (mfc_context->reference_surfaces[i].bo != NULL)
596             dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
597         mfc_context->reference_surfaces[i].bo = NULL;  
598     }
599
600     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
601     bo = dri_bo_alloc(i965->intel.bufmgr,
602                       "Buffer",
603                       128 * 64,
604                       64);
605     assert(bo);
606     mfc_context->intra_row_store_scratch_buffer.bo = bo;
607
608     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
609     bo = dri_bo_alloc(i965->intel.bufmgr,
610                       "Buffer",
611                       128*128*16,
612                       64);
613     assert(bo);
614     mfc_context->macroblock_status_buffer.bo = bo;
615
616     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
617     bo = dri_bo_alloc(i965->intel.bufmgr,
618                       "Buffer",
619                       49152,  /* 6 * 128 * 64 */
620                       64);
621     assert(bo);
622     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = bo;
623
624     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
625     bo = dri_bo_alloc(i965->intel.bufmgr,
626                       "Buffer",
627                       12288, /* 1.5 * 128 * 64 */
628                       0x1000);
629     assert(bo);
630     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = bo;
631
632     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
633     mfc_context->mfc_batchbuffer_surface.bo = NULL;
634
635     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
636     mfc_context->aux_batchbuffer_surface.bo = NULL;
637
638     if (mfc_context->aux_batchbuffer)
639         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
640
641     mfc_context->aux_batchbuffer = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD);
642     mfc_context->aux_batchbuffer_surface.bo = mfc_context->aux_batchbuffer->buffer;
643     dri_bo_reference(mfc_context->aux_batchbuffer_surface.bo);
644     mfc_context->aux_batchbuffer_surface.pitch = 16;
645     mfc_context->aux_batchbuffer_surface.num_blocks = mfc_context->aux_batchbuffer->size / 16;
646     mfc_context->aux_batchbuffer_surface.size_block = 16;
647
648     i965_gpe_context_init(ctx, &mfc_context->gpe_context);
649 }
650
651 static void gen6_mfc_avc_pipeline_header_programing(VADriverContextP ctx,
652                                                     struct encode_state *encode_state,
653                                                     struct intel_encoder_context *encoder_context,
654                                                     struct intel_batchbuffer *slice_batch)
655 {
656     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
657     int idx = va_enc_packed_type_to_idx(VAEncPackedHeaderH264_SPS);
658
659     if (encode_state->packed_header_data[idx]) {
660         VAEncPackedHeaderParameterBuffer *param = NULL;
661         unsigned int *header_data = (unsigned int *)encode_state->packed_header_data[idx]->buffer;
662         unsigned int length_in_bits;
663
664         assert(encode_state->packed_header_param[idx]);
665         param = (VAEncPackedHeaderParameterBuffer *)encode_state->packed_header_param[idx]->buffer;
666         length_in_bits = param->bit_length;
667
668         mfc_context->insert_object(ctx,
669                                    encoder_context,
670                                    header_data,
671                                    ALIGN(length_in_bits, 32) >> 5,
672                                    length_in_bits & 0x1f,
673                                    5,   /* FIXME: check it */
674                                    0,
675                                    0,
676                                    !param->has_emulation_bytes,
677                                    slice_batch);
678     }
679
680     idx = va_enc_packed_type_to_idx(VAEncPackedHeaderH264_PPS);
681
682     if (encode_state->packed_header_data[idx]) {
683         VAEncPackedHeaderParameterBuffer *param = NULL;
684         unsigned int *header_data = (unsigned int *)encode_state->packed_header_data[idx]->buffer;
685         unsigned int length_in_bits;
686
687         assert(encode_state->packed_header_param[idx]);
688         param = (VAEncPackedHeaderParameterBuffer *)encode_state->packed_header_param[idx]->buffer;
689         length_in_bits = param->bit_length;
690
691         mfc_context->insert_object(ctx,
692                                    encoder_context,
693                                    header_data,
694                                    ALIGN(length_in_bits, 32) >> 5,
695                                    length_in_bits & 0x1f,
696                                    5, /* FIXME: check it */
697                                    0,
698                                    0,
699                                    !param->has_emulation_bytes,
700                                    slice_batch);
701     }
702     
703     idx = va_enc_packed_type_to_idx(VAEncPackedHeaderH264_SEI);
704
705     if (encode_state->packed_header_data[idx]) {
706         VAEncPackedHeaderParameterBuffer *param = NULL;
707         unsigned int *header_data = (unsigned int *)encode_state->packed_header_data[idx]->buffer;
708         unsigned int length_in_bits;
709
710         assert(encode_state->packed_header_param[idx]);
711         param = (VAEncPackedHeaderParameterBuffer *)encode_state->packed_header_param[idx]->buffer;
712         length_in_bits = param->bit_length;
713
714         mfc_context->insert_object(ctx,
715                                    encoder_context,
716                                    header_data,
717                                    ALIGN(length_in_bits, 32) >> 5,
718                                    length_in_bits & 0x1f,
719                                    5, /* FIXME: check it */
720                                    0,
721                                    0,
722                                    !param->has_emulation_bytes,
723                                    slice_batch);
724     }
725 }
726
727 static void gen6_mfc_avc_pipeline_picture_programing( VADriverContextP ctx,
728                                       struct encode_state *encode_state,
729                                       struct intel_encoder_context *encoder_context)
730 {
731     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
732
733     mfc_context->pipe_mode_select(ctx, MFX_FORMAT_AVC, encoder_context);
734     mfc_context->set_surface_state(ctx, encoder_context);
735     mfc_context->ind_obj_base_addr_state(ctx, encoder_context);
736     gen6_mfc_pipe_buf_addr_state(ctx, encoder_context);
737     gen6_mfc_bsp_buf_base_addr_state(ctx, encoder_context);
738     mfc_context->avc_img_state(ctx, encode_state, encoder_context);
739     mfc_context->avc_qm_state(ctx, encoder_context);
740     mfc_context->avc_fqm_state(ctx, encoder_context);
741     gen6_mfc_avc_directmode_state(ctx, encoder_context); 
742     gen6_mfc_avc_ref_idx_state(ctx, encoder_context);
743 }
744
745 static void 
746 gen6_mfc_free_avc_surface(void **data)
747 {
748     struct gen6_mfc_avc_surface_aux *avc_surface = *data;
749
750     if (!avc_surface)
751         return;
752
753     dri_bo_unreference(avc_surface->dmv_top);
754     avc_surface->dmv_top = NULL;
755     dri_bo_unreference(avc_surface->dmv_bottom);
756     avc_surface->dmv_bottom = NULL;
757
758     free(avc_surface);
759     *data = NULL;
760 }
761
762 static void
763 gen6_mfc_bit_rate_control_context_init(struct encode_state *encode_state, 
764                                        struct gen6_mfc_context *mfc_context)
765 {
766     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
767     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
768     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
769     float fps =  pSequenceParameter->time_scale * 0.5 / pSequenceParameter->num_units_in_tick ;
770     int inter_mb_size = pSequenceParameter->bits_per_second * 1.0 / (fps+4.0) / width_in_mbs / height_in_mbs;
771     int intra_mb_size = inter_mb_size * 5.0;
772     int i;
773
774     mfc_context->bit_rate_control_context[SLICE_TYPE_I].target_mb_size = intra_mb_size;
775     mfc_context->bit_rate_control_context[SLICE_TYPE_I].target_frame_size = intra_mb_size * width_in_mbs * height_in_mbs;
776     mfc_context->bit_rate_control_context[SLICE_TYPE_P].target_mb_size = inter_mb_size;
777     mfc_context->bit_rate_control_context[SLICE_TYPE_P].target_frame_size = inter_mb_size * width_in_mbs * height_in_mbs;
778     mfc_context->bit_rate_control_context[SLICE_TYPE_B].target_mb_size = inter_mb_size;
779     mfc_context->bit_rate_control_context[SLICE_TYPE_B].target_frame_size = inter_mb_size * width_in_mbs * height_in_mbs;
780
781     for(i = 0 ; i < 3; i++) {
782         mfc_context->bit_rate_control_context[i].QpPrimeY = 26;
783         mfc_context->bit_rate_control_context[i].MaxQpNegModifier = 6;
784         mfc_context->bit_rate_control_context[i].MaxQpPosModifier = 6;
785         mfc_context->bit_rate_control_context[i].GrowInit = 6;
786         mfc_context->bit_rate_control_context[i].GrowResistance = 4;
787         mfc_context->bit_rate_control_context[i].ShrinkInit = 6;
788         mfc_context->bit_rate_control_context[i].ShrinkResistance = 4;
789         
790         mfc_context->bit_rate_control_context[i].Correct[0] = 8;
791         mfc_context->bit_rate_control_context[i].Correct[1] = 4;
792         mfc_context->bit_rate_control_context[i].Correct[2] = 2;
793         mfc_context->bit_rate_control_context[i].Correct[3] = 2;
794         mfc_context->bit_rate_control_context[i].Correct[4] = 4;
795         mfc_context->bit_rate_control_context[i].Correct[5] = 8;
796     }
797     
798     mfc_context->bit_rate_control_context[SLICE_TYPE_I].TargetSizeInWord = (intra_mb_size + 16)/ 16;
799     mfc_context->bit_rate_control_context[SLICE_TYPE_P].TargetSizeInWord = (inter_mb_size + 16)/ 16;
800     mfc_context->bit_rate_control_context[SLICE_TYPE_B].TargetSizeInWord = (inter_mb_size + 16)/ 16;
801
802     mfc_context->bit_rate_control_context[SLICE_TYPE_I].MaxSizeInWord = mfc_context->bit_rate_control_context[SLICE_TYPE_I].TargetSizeInWord * 1.5;
803     mfc_context->bit_rate_control_context[SLICE_TYPE_P].MaxSizeInWord = mfc_context->bit_rate_control_context[SLICE_TYPE_P].TargetSizeInWord * 1.5;
804     mfc_context->bit_rate_control_context[SLICE_TYPE_B].MaxSizeInWord = mfc_context->bit_rate_control_context[SLICE_TYPE_B].TargetSizeInWord * 1.5;
805 }
806
807 static void
808 gen6_mfc_brc_init(struct encode_state *encode_state,
809                   struct intel_encoder_context* encoder_context)
810 {
811     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
812     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
813     VAEncMiscParameterBuffer* pMiscParamHRD = (VAEncMiscParameterBuffer*)encode_state->misc_param[VAEncMiscParameterTypeHRD]->buffer;
814     VAEncMiscParameterHRD* pParameterHRD = (VAEncMiscParameterHRD*)pMiscParamHRD->data;
815     double bitrate = pSequenceParameter->bits_per_second;
816     double framerate = (double)pSequenceParameter->time_scale /(2 * (double)pSequenceParameter->num_units_in_tick);
817     int inum = 1, pnum = 0, bnum = 0; /* Gop structure: number of I, P, B frames in the Gop. */
818     int intra_period = pSequenceParameter->intra_period;
819     int ip_period = pSequenceParameter->ip_period;
820     double qp1_size = 0.1 * 8 * 3 * (pSequenceParameter->picture_width_in_mbs<<4) * (pSequenceParameter->picture_height_in_mbs<<4)/2;
821     double qp51_size = 0.001 * 8 * 3 * (pSequenceParameter->picture_width_in_mbs<<4) * (pSequenceParameter->picture_height_in_mbs<<4)/2;
822     double bpf;
823
824     if (pSequenceParameter->ip_period) {
825         pnum = (intra_period + ip_period - 1)/ip_period - 1;
826         bnum = intra_period - inum - pnum;
827     }
828
829     mfc_context->brc.mode = encoder_context->rate_control_mode;
830
831     mfc_context->brc.target_frame_size[SLICE_TYPE_I] = (int)((double)((bitrate * intra_period)/framerate) /
832                                                              (double)(inum + BRC_PWEIGHT * pnum + BRC_BWEIGHT * bnum));
833     mfc_context->brc.target_frame_size[SLICE_TYPE_P] = BRC_PWEIGHT * mfc_context->brc.target_frame_size[SLICE_TYPE_I];
834     mfc_context->brc.target_frame_size[SLICE_TYPE_B] = BRC_BWEIGHT * mfc_context->brc.target_frame_size[SLICE_TYPE_I];
835
836     mfc_context->brc.gop_nums[SLICE_TYPE_I] = inum;
837     mfc_context->brc.gop_nums[SLICE_TYPE_P] = pnum;
838     mfc_context->brc.gop_nums[SLICE_TYPE_B] = bnum;
839
840     bpf = mfc_context->brc.bits_per_frame = bitrate/framerate;
841
842     mfc_context->hrd.buffer_size = (double)pParameterHRD->buffer_size;
843     mfc_context->hrd.current_buffer_fullness =
844         (double)(pParameterHRD->initial_buffer_fullness < mfc_context->hrd.buffer_size)?
845             pParameterHRD->initial_buffer_fullness: mfc_context->hrd.buffer_size/2.;
846     mfc_context->hrd.target_buffer_fullness = (double)mfc_context->hrd.buffer_size/2.;
847     mfc_context->hrd.buffer_capacity = (double)mfc_context->hrd.buffer_size/qp1_size;
848     mfc_context->hrd.violation_noted = 0;
849
850     if ((bpf > qp51_size) && (bpf < qp1_size)) {
851         mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY = 51 - 50*(bpf - qp51_size)/(qp1_size - qp51_size);
852     }
853     else if (bpf >= qp1_size)
854         mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY = 1;
855     else if (bpf <= qp51_size)
856         mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY = 51;
857
858     mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY = mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY;
859     mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY = mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY;
860
861     BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY, 1, 51);
862     BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY, 1, 51);
863     BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY, 1, 51);
864 }
865
866 static int gen6_mfc_update_hrd(struct encode_state *encode_state,
867                                struct gen6_mfc_context *mfc_context,
868                                int frame_bits)
869 {
870     double prev_bf = mfc_context->hrd.current_buffer_fullness;
871
872     mfc_context->hrd.current_buffer_fullness -= frame_bits;
873
874     if (mfc_context->hrd.buffer_size > 0 && mfc_context->hrd.current_buffer_fullness <= 0.) {
875         mfc_context->hrd.current_buffer_fullness = prev_bf;
876         return BRC_UNDERFLOW;
877     }
878     
879     mfc_context->hrd.current_buffer_fullness += mfc_context->brc.bits_per_frame;
880     if (mfc_context->hrd.buffer_size > 0 && mfc_context->hrd.current_buffer_fullness > mfc_context->hrd.buffer_size) {
881         if (mfc_context->brc.mode == VA_RC_VBR)
882             mfc_context->hrd.current_buffer_fullness = mfc_context->hrd.buffer_size;
883         else {
884             mfc_context->hrd.current_buffer_fullness = prev_bf;
885             return BRC_OVERFLOW;
886         }
887     }
888     return BRC_NO_HRD_VIOLATION;
889 }
890
891 static int gen6_mfc_brc_postpack(struct encode_state *encode_state,
892                                  struct gen6_mfc_context *mfc_context,
893                                  int frame_bits)
894 {
895     gen6_brc_status sts = BRC_NO_HRD_VIOLATION;
896     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[0]->buffer; 
897     int slicetype = pSliceParameter->slice_type;
898     int qpi = mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY;
899     int qpp = mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY;
900     int qpb = mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY;
901     int qp; // quantizer of previously encoded slice of current type
902     int qpn; // predicted quantizer for next frame of current type in integer format
903     double qpf; // predicted quantizer for next frame of current type in float format
904     double delta_qp; // QP correction
905     int target_frame_size, frame_size_next;
906     /* Notes:
907      *  x - how far we are from HRD buffer borders
908      *  y - how far we are from target HRD buffer fullness
909      */
910     double x, y;
911     double frame_size_alpha;
912
913     if (slicetype == SLICE_TYPE_SP)
914         slicetype = SLICE_TYPE_P;
915     else if (slicetype == SLICE_TYPE_SI)
916         slicetype = SLICE_TYPE_I;
917
918     qp = mfc_context->bit_rate_control_context[slicetype].QpPrimeY;
919
920     target_frame_size = mfc_context->brc.target_frame_size[slicetype];
921     if (mfc_context->hrd.buffer_capacity < 5)
922         frame_size_alpha = 0;
923     else
924         frame_size_alpha = (double)mfc_context->brc.gop_nums[slicetype];
925     if (frame_size_alpha > 30) frame_size_alpha = 30;
926     frame_size_next = target_frame_size + (double)(target_frame_size - frame_bits) /
927                                           (double)(frame_size_alpha + 1.);
928
929     /* frame_size_next: avoiding negative number and too small value */
930     if ((double)frame_size_next < (double)(target_frame_size * 0.25))
931         frame_size_next = (int)((double)target_frame_size * 0.25);
932
933     qpf = (double)qp * target_frame_size / frame_size_next;
934     qpn = (int)(qpf + 0.5);
935
936     if (qpn == qp) {
937         /* setting qpn we round qpf making mistakes: now we are trying to compensate this */
938         mfc_context->brc.qpf_rounding_accumulator += qpf - qpn;
939         if (mfc_context->brc.qpf_rounding_accumulator > 1.0) {
940             qpn++;
941             mfc_context->brc.qpf_rounding_accumulator = 0.;
942         } else if (mfc_context->brc.qpf_rounding_accumulator < -1.0) {
943             qpn--;
944             mfc_context->brc.qpf_rounding_accumulator = 0.;
945         }
946     }
947     /* making sure that QP is not changing too fast */
948     if ((qpn - qp) > BRC_QP_MAX_CHANGE) qpn = qp + BRC_QP_MAX_CHANGE;
949     else if ((qpn - qp) < -BRC_QP_MAX_CHANGE) qpn = qp - BRC_QP_MAX_CHANGE;
950     /* making sure that with QP predictions we did do not leave QPs range */
951     BRC_CLIP(qpn, 1, 51);
952
953     /* checking wthether HRD compliance is still met */
954     sts = gen6_mfc_update_hrd(encode_state, mfc_context, frame_bits);
955
956     /* calculating QP delta as some function*/
957     x = mfc_context->hrd.target_buffer_fullness - mfc_context->hrd.current_buffer_fullness;
958     if (x > 0) {
959         x /= mfc_context->hrd.target_buffer_fullness;
960         y = mfc_context->hrd.current_buffer_fullness;
961     }
962     else {
963         x /= (mfc_context->hrd.buffer_size - mfc_context->hrd.target_buffer_fullness);
964         y = mfc_context->hrd.buffer_size - mfc_context->hrd.current_buffer_fullness;
965     }
966     if (y < 0.01) y = 0.01;
967     if (x > 1) x = 1;
968     else if (x < -1) x = -1;
969
970     delta_qp = BRC_QP_MAX_CHANGE*exp(-1/y)*sin(BRC_PI_0_5 * x);
971     qpn = (int)(qpn + delta_qp + 0.5);
972
973     /* making sure that with QP predictions we did do not leave QPs range */
974     BRC_CLIP(qpn, 1, 51);
975
976     if (sts == BRC_NO_HRD_VIOLATION) { // no HRD violation
977         /* correcting QPs of slices of other types */
978         if (slicetype == SLICE_TYPE_P) {
979             if (abs(qpn + BRC_P_B_QP_DIFF - qpb) > 2)
980                 mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY += (qpn + BRC_P_B_QP_DIFF - qpb) >> 1;
981             if (abs(qpn - BRC_I_P_QP_DIFF - qpi) > 2)
982                 mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY += (qpn - BRC_I_P_QP_DIFF - qpi) >> 1;
983         } else if (slicetype == SLICE_TYPE_I) {
984             if (abs(qpn + BRC_I_B_QP_DIFF - qpb) > 4)
985                 mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY += (qpn + BRC_I_B_QP_DIFF - qpb) >> 2;
986             if (abs(qpn + BRC_I_P_QP_DIFF - qpp) > 2)
987                 mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY += (qpn + BRC_I_P_QP_DIFF - qpp) >> 2;
988         } else { // SLICE_TYPE_B
989             if (abs(qpn - BRC_P_B_QP_DIFF - qpp) > 2)
990                 mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY += (qpn - BRC_P_B_QP_DIFF - qpp) >> 1;
991             if (abs(qpn - BRC_I_B_QP_DIFF - qpi) > 4)
992                 mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY += (qpn - BRC_I_B_QP_DIFF - qpi) >> 2;
993         }
994         BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_I].QpPrimeY, 1, 51);
995         BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_P].QpPrimeY, 1, 51);
996         BRC_CLIP(mfc_context->bit_rate_control_context[SLICE_TYPE_B].QpPrimeY, 1, 51);
997     } else if (sts == BRC_UNDERFLOW) { // underflow
998         if (qpn <= qp) qpn = qp + 1;
999         if (qpn > 51) {
1000             qpn = 51;
1001             sts = BRC_UNDERFLOW_WITH_MAX_QP; //underflow with maxQP
1002         }
1003     } else if (sts == BRC_OVERFLOW) {
1004         if (qpn >= qp) qpn = qp - 1;
1005         if (qpn < 1) { // < 0 (?) overflow with minQP
1006             qpn = 1;
1007             sts = BRC_OVERFLOW_WITH_MIN_QP; // bit stuffing to be done
1008         }
1009     }
1010
1011     mfc_context->bit_rate_control_context[slicetype].QpPrimeY = qpn;
1012
1013     return sts;
1014 }
1015
1016 static void 
1017 gen6_mfc_hrd_context_init(struct encode_state *encode_state,
1018                           struct intel_encoder_context *encoder_context)
1019 {
1020     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1021     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1022     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1023     int target_bit_rate = pSequenceParameter->bits_per_second;
1024     
1025     // current we only support CBR mode.
1026     if (rate_control_mode == VA_RC_CBR) {
1027         mfc_context->vui_hrd.i_bit_rate_value = target_bit_rate >> 10;
1028         mfc_context->vui_hrd.i_cpb_size_value = (target_bit_rate * 8) >> 10;
1029         mfc_context->vui_hrd.i_initial_cpb_removal_delay = mfc_context->vui_hrd.i_cpb_size_value * 0.5 * 1024 / target_bit_rate * 90000;
1030         mfc_context->vui_hrd.i_cpb_removal_delay = 2;
1031         mfc_context->vui_hrd.i_frame_number = 0;
1032
1033         mfc_context->vui_hrd.i_initial_cpb_removal_delay_length = 24; 
1034         mfc_context->vui_hrd.i_cpb_removal_delay_length = 24;
1035         mfc_context->vui_hrd.i_dpb_output_delay_length = 24;
1036     }
1037
1038 }
1039
1040 static void 
1041 gen6_mfc_hrd_context_update(struct encode_state *encode_state, 
1042                           struct gen6_mfc_context *mfc_context) 
1043 {
1044     mfc_context->vui_hrd.i_frame_number++;
1045 }
1046
1047 static VAStatus gen6_mfc_avc_prepare(VADriverContextP ctx, 
1048                                      struct encode_state *encode_state,
1049                                      struct intel_encoder_context *encoder_context)
1050 {
1051     struct i965_driver_data *i965 = i965_driver_data(ctx);
1052     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1053     struct object_surface *obj_surface; 
1054     struct object_buffer *obj_buffer;
1055     struct gen6_mfc_avc_surface_aux* gen6_avc_surface;
1056     dri_bo *bo;
1057     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1058     VAStatus vaStatus = VA_STATUS_SUCCESS;
1059     int i, j, enable_avc_ildb = 0;
1060     VAEncSliceParameterBufferH264 *slice_param;
1061     VACodedBufferSegment *coded_buffer_segment;
1062     unsigned char *flag = NULL;
1063
1064     for (j = 0; j < encode_state->num_slice_params_ext && enable_avc_ildb == 0; j++) {
1065         assert(encode_state->slice_params_ext && encode_state->slice_params_ext[j]->buffer);
1066         slice_param = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[j]->buffer;
1067
1068         for (i = 0; i < encode_state->slice_params_ext[j]->num_elements; i++) {
1069             assert((slice_param->slice_type == SLICE_TYPE_I) ||
1070                    (slice_param->slice_type == SLICE_TYPE_SI) ||
1071                    (slice_param->slice_type == SLICE_TYPE_P) ||
1072                    (slice_param->slice_type == SLICE_TYPE_SP) ||
1073                    (slice_param->slice_type == SLICE_TYPE_B));
1074
1075             if (slice_param->disable_deblocking_filter_idc != 1) {
1076                 enable_avc_ildb = 1;
1077                 break;
1078             }
1079
1080             slice_param++;
1081         }
1082     }
1083
1084     /*Setup all the input&output object*/
1085
1086     /* Setup current frame and current direct mv buffer*/
1087     obj_surface = SURFACE(pPicParameter->CurrPic.picture_id);
1088     assert(obj_surface);
1089     i965_check_alloc_surface_bo(ctx, obj_surface, 1, VA_FOURCC('N','V','1','2'), SUBSAMPLE_YUV420);
1090
1091     if ( obj_surface->private_data == NULL) {
1092         gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
1093         gen6_avc_surface->dmv_top = 
1094             dri_bo_alloc(i965->intel.bufmgr,
1095                          "Buffer",
1096                          68*8192, 
1097                          64);
1098         gen6_avc_surface->dmv_bottom = 
1099             dri_bo_alloc(i965->intel.bufmgr,
1100                          "Buffer",
1101                          68*8192, 
1102                          64);
1103         assert(gen6_avc_surface->dmv_top);
1104         assert(gen6_avc_surface->dmv_bottom);
1105         obj_surface->private_data = (void *)gen6_avc_surface;
1106         obj_surface->free_private_data = (void *)gen6_mfc_free_avc_surface; 
1107     }
1108     gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
1109     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 2].bo = gen6_avc_surface->dmv_top;
1110     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 1].bo = gen6_avc_surface->dmv_bottom;
1111     dri_bo_reference(gen6_avc_surface->dmv_top);
1112     dri_bo_reference(gen6_avc_surface->dmv_bottom);
1113
1114     if (enable_avc_ildb) {
1115         mfc_context->post_deblocking_output.bo = obj_surface->bo;
1116         dri_bo_reference(mfc_context->post_deblocking_output.bo);
1117     } else {
1118         mfc_context->pre_deblocking_output.bo = obj_surface->bo;
1119         dri_bo_reference(mfc_context->pre_deblocking_output.bo);
1120     }
1121
1122     mfc_context->surface_state.width = obj_surface->orig_width;
1123     mfc_context->surface_state.height = obj_surface->orig_height;
1124     mfc_context->surface_state.w_pitch = obj_surface->width;
1125     mfc_context->surface_state.h_pitch = obj_surface->height;
1126     
1127     /* Setup reference frames and direct mv buffers*/
1128     for(i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++) {
1129         if ( pPicParameter->ReferenceFrames[i].picture_id != VA_INVALID_ID ) { 
1130             obj_surface = SURFACE(pPicParameter->ReferenceFrames[i].picture_id);
1131             assert(obj_surface);
1132             if (obj_surface->bo != NULL) {
1133                 mfc_context->reference_surfaces[i].bo = obj_surface->bo;
1134                 dri_bo_reference(obj_surface->bo);
1135             }
1136             /* Check DMV buffer */
1137             if ( obj_surface->private_data == NULL) {
1138                 
1139                 gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
1140                 gen6_avc_surface->dmv_top = 
1141                     dri_bo_alloc(i965->intel.bufmgr,
1142                                  "Buffer",
1143                                  68*8192, 
1144                                  64);
1145                 gen6_avc_surface->dmv_bottom = 
1146                     dri_bo_alloc(i965->intel.bufmgr,
1147                                  "Buffer",
1148                                  68*8192, 
1149                                  64);
1150                 assert(gen6_avc_surface->dmv_top);
1151                 assert(gen6_avc_surface->dmv_bottom);
1152                 obj_surface->private_data = gen6_avc_surface;
1153                 obj_surface->free_private_data = gen6_mfc_free_avc_surface; 
1154             }
1155     
1156             gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
1157             /* Setup DMV buffer */
1158             mfc_context->direct_mv_buffers[i*2].bo = gen6_avc_surface->dmv_top;
1159             mfc_context->direct_mv_buffers[i*2+1].bo = gen6_avc_surface->dmv_bottom; 
1160             dri_bo_reference(gen6_avc_surface->dmv_top);
1161             dri_bo_reference(gen6_avc_surface->dmv_bottom);
1162         } else {
1163             break;
1164         }
1165     }
1166         
1167     obj_surface = SURFACE(encoder_context->input_yuv_surface);
1168     assert(obj_surface && obj_surface->bo);
1169     mfc_context->uncompressed_picture_source.bo = obj_surface->bo;
1170     dri_bo_reference(mfc_context->uncompressed_picture_source.bo);
1171
1172     obj_buffer = BUFFER (pPicParameter->coded_buf); /* FIXME: fix this later */
1173     bo = obj_buffer->buffer_store->bo;
1174     assert(bo);
1175     mfc_context->mfc_indirect_pak_bse_object.bo = bo;
1176     mfc_context->mfc_indirect_pak_bse_object.offset = I965_CODEDBUFFER_SIZE;
1177     mfc_context->mfc_indirect_pak_bse_object.end_offset = ALIGN(obj_buffer->size_element - 0x1000, 0x1000);
1178     dri_bo_reference(mfc_context->mfc_indirect_pak_bse_object.bo);
1179     
1180     dri_bo_map(bo, 1);
1181     coded_buffer_segment = (VACodedBufferSegment *)bo->virtual;
1182     flag = (unsigned char *)(coded_buffer_segment + 1);
1183     *flag = 0;
1184     dri_bo_unmap(bo);
1185
1186     return vaStatus;
1187 }
1188
1189 static VAStatus gen6_mfc_run(VADriverContextP ctx, 
1190                              struct encode_state *encode_state,
1191                              struct intel_encoder_context *encoder_context)
1192 {
1193     struct intel_batchbuffer *batch = encoder_context->base.batch;
1194
1195     intel_batchbuffer_flush(batch);             //run the pipeline
1196
1197     return VA_STATUS_SUCCESS;
1198 }
1199
1200 extern VAStatus 
1201 i965_MapBuffer(VADriverContextP ctx, 
1202                VABufferID buf_id,       /* in */
1203                void **pbuf);            /* out */
1204 extern VAStatus
1205 i965_UnmapBuffer(VADriverContextP ctx,
1206                  VABufferID buf_id);
1207
1208 static VAStatus
1209 gen6_mfc_stop(VADriverContextP ctx, 
1210               struct encode_state *encode_state,
1211               struct intel_encoder_context *encoder_context,
1212               int *encoded_bits_size)
1213 {
1214     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1215     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1216     VACodedBufferSegment *coded_buffer_segment;
1217     
1218     vaStatus = i965_MapBuffer(ctx, pPicParameter->coded_buf, (void **)&coded_buffer_segment);
1219     assert(vaStatus == VA_STATUS_SUCCESS);
1220     *encoded_bits_size = coded_buffer_segment->size * 8;
1221     i965_UnmapBuffer(ctx, pPicParameter->coded_buf);
1222
1223     return VA_STATUS_SUCCESS;
1224 }
1225
1226 #if __SOFTWARE__
1227
1228 static int
1229 gen6_mfc_avc_pak_object_intra(VADriverContextP ctx, int x, int y, int end_mb, int qp,unsigned int *msg,
1230                               struct intel_encoder_context *encoder_context,
1231                               unsigned char target_mb_size, unsigned char max_mb_size,
1232                               struct intel_batchbuffer *batch)
1233 {
1234     int len_in_dwords = 11;
1235
1236     if (batch == NULL)
1237         batch = encoder_context->base.batch;
1238
1239     BEGIN_BCS_BATCH(batch, len_in_dwords);
1240
1241     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1242     OUT_BCS_BATCH(batch, 0);
1243     OUT_BCS_BATCH(batch, 0);
1244     OUT_BCS_BATCH(batch, 
1245                   (0 << 24) |           /* PackedMvNum, Debug*/
1246                   (0 << 20) |           /* No motion vector */
1247                   (1 << 19) |           /* CbpDcY */
1248                   (1 << 18) |           /* CbpDcU */
1249                   (1 << 17) |           /* CbpDcV */
1250                   (msg[0] & 0xFFFF) );
1251
1252     OUT_BCS_BATCH(batch, (0xFFFF << 16) | (y << 8) | x);                /* Code Block Pattern for Y*/
1253     OUT_BCS_BATCH(batch, 0x000F000F);                                                   /* Code Block Pattern */                
1254     OUT_BCS_BATCH(batch, (0 << 27) | (end_mb << 26) | qp);      /* Last MB */
1255
1256     /*Stuff for Intra MB*/
1257     OUT_BCS_BATCH(batch, msg[1]);                       /* We using Intra16x16 no 4x4 predmode*/        
1258     OUT_BCS_BATCH(batch, msg[2]);       
1259     OUT_BCS_BATCH(batch, msg[3]&0xFC);          
1260     
1261     /*MaxSizeInWord and TargetSzieInWord*/
1262     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1263                   (target_mb_size << 16) );
1264
1265     ADVANCE_BCS_BATCH(batch);
1266
1267     return len_in_dwords;
1268 }
1269
1270 static int
1271 gen6_mfc_avc_pak_object_inter(VADriverContextP ctx, int x, int y, int end_mb, int qp,
1272                               unsigned int *msg, unsigned int offset,
1273                               struct intel_encoder_context *encoder_context,
1274                               unsigned char target_mb_size,unsigned char max_mb_size, int slice_type,
1275                               struct intel_batchbuffer *batch)
1276 {
1277     int len_in_dwords = 11;
1278
1279     if (batch == NULL)
1280         batch = encoder_context->base.batch;
1281
1282     BEGIN_BCS_BATCH(batch, len_in_dwords);
1283
1284     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1285
1286     OUT_BCS_BATCH(batch, msg[2]);         /* 32 MV*/
1287     OUT_BCS_BATCH(batch, offset);
1288
1289     OUT_BCS_BATCH(batch, msg[0]);
1290
1291     OUT_BCS_BATCH(batch, (0xFFFF<<16) | (y << 8) | x);        /* Code Block Pattern for Y*/
1292     OUT_BCS_BATCH(batch, 0x000F000F);                         /* Code Block Pattern */  
1293 #if 0 
1294     if ( slice_type == SLICE_TYPE_B) {
1295         OUT_BCS_BATCH(batch, (0xF<<28) | (end_mb << 26) | qp);  /* Last MB */
1296     } else {
1297         OUT_BCS_BATCH(batch, (end_mb << 26) | qp);      /* Last MB */
1298     }
1299 #else
1300     OUT_BCS_BATCH(batch, (end_mb << 26) | qp);  /* Last MB */
1301 #endif
1302
1303
1304     /*Stuff for Inter MB*/
1305     OUT_BCS_BATCH(batch, msg[1]);        
1306     OUT_BCS_BATCH(batch, 0x0);    
1307     OUT_BCS_BATCH(batch, 0x0);        
1308
1309     /*MaxSizeInWord and TargetSzieInWord*/
1310     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1311                   (target_mb_size << 16) );
1312
1313     ADVANCE_BCS_BATCH(batch);
1314
1315     return len_in_dwords;
1316 }
1317
1318 static void 
1319 gen6_mfc_avc_pipeline_slice_programing(VADriverContextP ctx,
1320                                        struct encode_state *encode_state,
1321                                        struct intel_encoder_context *encoder_context,
1322                                        int slice_index,
1323                                        struct intel_batchbuffer *slice_batch)
1324 {
1325     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1326     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1327     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1328     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1329     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1330     unsigned int *msg = NULL, offset = 0;
1331     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
1332     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1333     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1334     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1335     int i,x,y;
1336     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1337     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1338     unsigned char *slice_header = NULL;
1339     int slice_header_length_in_bits = 0;
1340     unsigned int tail_data[] = { 0x0, 0x0 };
1341     int slice_type = pSliceParameter->slice_type;
1342
1343
1344     if (rate_control_mode == VA_RC_CBR) {
1345         qp = mfc_context->bit_rate_control_context[slice_type].QpPrimeY;
1346         pSliceParameter->slice_qp_delta = qp - pPicParameter->pic_init_qp;
1347     }
1348
1349     /* only support for 8-bit pixel bit-depth */
1350     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
1351     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
1352     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
1353     assert(qp >= 0 && qp < 52);
1354
1355     gen6_mfc_avc_slice_state(ctx, 
1356                              pPicParameter,
1357                              pSliceParameter,
1358                              encode_state, encoder_context,
1359                              (rate_control_mode == VA_RC_CBR), qp, slice_batch);
1360
1361     if ( slice_index == 0) 
1362         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1363
1364     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1365
1366     // slice hander
1367     mfc_context->insert_object(ctx, encoder_context,
1368                                (unsigned int *)slice_header, ALIGN(slice_header_length_in_bits, 32) >> 5, slice_header_length_in_bits & 0x1f,
1369                                5,  /* first 5 bytes are start code + nal unit type */
1370                                1, 0, 1, slice_batch);
1371
1372     dri_bo_map(vme_context->vme_output.bo , 1);
1373     msg = (unsigned int *)vme_context->vme_output.bo->virtual;
1374
1375     if (is_intra) {
1376         msg += pSliceParameter->macroblock_address * INTRA_VME_OUTPUT_IN_DWS;
1377     } else {
1378         msg += pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_DWS;
1379         msg += 32; /* the first 32 DWs are MVs */
1380         offset = pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_BYTES;
1381     }
1382    
1383     for (i = pSliceParameter->macroblock_address; 
1384          i < pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks; i++) {
1385         int last_mb = (i == (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks - 1) );
1386         x = i % width_in_mbs;
1387         y = i / width_in_mbs;
1388
1389         if (is_intra) {
1390             assert(msg);
1391             gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
1392             msg += INTRA_VME_OUTPUT_IN_DWS;
1393         } else {
1394             if (msg[0] & INTRA_MB_FLAG_MASK) {
1395                 gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
1396             } else {
1397                 gen6_mfc_avc_pak_object_inter(ctx, x, y, last_mb, qp, msg, offset, encoder_context, 0, 0, pSliceParameter->slice_type, slice_batch);
1398             }
1399
1400             msg += INTER_VME_OUTPUT_IN_DWS;
1401             offset += INTER_VME_OUTPUT_IN_BYTES;
1402         }
1403     }
1404    
1405     dri_bo_unmap(vme_context->vme_output.bo);
1406
1407     if ( last_slice ) {    
1408         mfc_context->insert_object(ctx, encoder_context,
1409                                    tail_data, 2, 8,
1410                                    2, 1, 1, 0, slice_batch);
1411     } else {
1412         mfc_context->insert_object(ctx, encoder_context,
1413                                    tail_data, 1, 8,
1414                                    1, 1, 1, 0, slice_batch);
1415     }
1416
1417     free(slice_header);
1418
1419 }
1420
1421 static dri_bo *
1422 gen6_mfc_avc_software_batchbuffer(VADriverContextP ctx,
1423                                   struct encode_state *encode_state,
1424                                   struct intel_encoder_context *encoder_context)
1425 {
1426     struct i965_driver_data *i965 = i965_driver_data(ctx);
1427     struct intel_batchbuffer *batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD);
1428     dri_bo *batch_bo = batch->buffer;
1429     int i;
1430
1431     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1432         gen6_mfc_avc_pipeline_slice_programing(ctx, encode_state, encoder_context, i, batch);
1433     }
1434
1435     intel_batchbuffer_align(batch, 8);
1436     
1437     BEGIN_BCS_BATCH(batch, 2);
1438     OUT_BCS_BATCH(batch, 0);
1439     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_END);
1440     ADVANCE_BCS_BATCH(batch);
1441
1442     dri_bo_reference(batch_bo);
1443     intel_batchbuffer_free(batch);
1444
1445     return batch_bo;
1446 }
1447
1448 #else
1449
1450 static void
1451 gen6_mfc_batchbuffer_surfaces_input(VADriverContextP ctx,
1452                                     struct encode_state *encode_state,
1453                                     struct intel_encoder_context *encoder_context)
1454
1455 {
1456     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1457     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1458
1459     assert(vme_context->vme_output.bo);
1460     mfc_context->buffer_suface_setup(ctx,
1461                                      &mfc_context->gpe_context,
1462                                      &vme_context->vme_output,
1463                                      BINDING_TABLE_OFFSET(BIND_IDX_VME_OUTPUT),
1464                                      SURFACE_STATE_OFFSET(BIND_IDX_VME_OUTPUT));
1465     assert(mfc_context->aux_batchbuffer_surface.bo);
1466     mfc_context->buffer_suface_setup(ctx,
1467                                      &mfc_context->gpe_context,
1468                                      &mfc_context->aux_batchbuffer_surface,
1469                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_SLICE_HEADER),
1470                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_SLICE_HEADER));
1471 }
1472
1473 static void
1474 gen6_mfc_batchbuffer_surfaces_output(VADriverContextP ctx,
1475                                      struct encode_state *encode_state,
1476                                      struct intel_encoder_context *encoder_context)
1477
1478 {
1479     struct i965_driver_data *i965 = i965_driver_data(ctx);
1480     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1481     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1482     int width_in_mbs = pSequenceParameter->picture_width_in_mbs;
1483     int height_in_mbs = pSequenceParameter->picture_height_in_mbs;
1484     mfc_context->mfc_batchbuffer_surface.num_blocks = width_in_mbs * height_in_mbs + encode_state->num_slice_params_ext * 8 + 1;
1485     mfc_context->mfc_batchbuffer_surface.size_block = 16 * CMD_LEN_IN_OWORD; /* 3 OWORDs */
1486     mfc_context->mfc_batchbuffer_surface.pitch = 16;
1487     mfc_context->mfc_batchbuffer_surface.bo = dri_bo_alloc(i965->intel.bufmgr, 
1488                                                            "MFC batchbuffer",
1489                                                            mfc_context->mfc_batchbuffer_surface.num_blocks * mfc_context->mfc_batchbuffer_surface.size_block,
1490                                                            0x1000);
1491     mfc_context->buffer_suface_setup(ctx,
1492                                      &mfc_context->gpe_context,
1493                                      &mfc_context->mfc_batchbuffer_surface,
1494                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_BATCHBUFFER),
1495                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_BATCHBUFFER));
1496 }
1497
1498 static void
1499 gen6_mfc_batchbuffer_surfaces_setup(VADriverContextP ctx, 
1500                                     struct encode_state *encode_state,
1501                                     struct intel_encoder_context *encoder_context)
1502 {
1503     gen6_mfc_batchbuffer_surfaces_input(ctx, encode_state, encoder_context);
1504     gen6_mfc_batchbuffer_surfaces_output(ctx, encode_state, encoder_context);
1505 }
1506
1507 static void
1508 gen6_mfc_batchbuffer_idrt_setup(VADriverContextP ctx, 
1509                                 struct encode_state *encode_state,
1510                                 struct intel_encoder_context *encoder_context)
1511 {
1512     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1513     struct gen6_interface_descriptor_data *desc;   
1514     int i;
1515     dri_bo *bo;
1516
1517     bo = mfc_context->gpe_context.idrt.bo;
1518     dri_bo_map(bo, 1);
1519     assert(bo->virtual);
1520     desc = bo->virtual;
1521
1522     for (i = 0; i < mfc_context->gpe_context.num_kernels; i++) {
1523         struct i965_kernel *kernel;
1524
1525         kernel = &mfc_context->gpe_context.kernels[i];
1526         assert(sizeof(*desc) == 32);
1527
1528         /*Setup the descritor table*/
1529         memset(desc, 0, sizeof(*desc));
1530         desc->desc0.kernel_start_pointer = (kernel->bo->offset >> 6);
1531         desc->desc2.sampler_count = 0;
1532         desc->desc2.sampler_state_pointer = 0;
1533         desc->desc3.binding_table_entry_count = 2;
1534         desc->desc3.binding_table_pointer = (BINDING_TABLE_OFFSET(0) >> 5);
1535         desc->desc4.constant_urb_entry_read_offset = 0;
1536         desc->desc4.constant_urb_entry_read_length = 4;
1537                 
1538         /*kernel start*/
1539         dri_bo_emit_reloc(bo,   
1540                           I915_GEM_DOMAIN_INSTRUCTION, 0,
1541                           0,
1542                           i * sizeof(*desc) + offsetof(struct gen6_interface_descriptor_data, desc0),
1543                           kernel->bo);
1544         desc++;
1545     }
1546
1547     dri_bo_unmap(bo);
1548 }
1549
1550 static void
1551 gen6_mfc_batchbuffer_constant_setup(VADriverContextP ctx, 
1552                                     struct encode_state *encode_state,
1553                                     struct intel_encoder_context *encoder_context)
1554 {
1555     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1556     
1557     (void)mfc_context;
1558 }
1559
1560 static void
1561 gen6_mfc_batchbuffer_emit_object_command(struct intel_batchbuffer *batch,
1562                                          int index,
1563                                          int head_offset,
1564                                          int batchbuffer_offset,
1565                                          int head_size,
1566                                          int tail_size,
1567                                          int number_mb_cmds,
1568                                          int first_object,
1569                                          int last_object,
1570                                          int last_slice,
1571                                          int mb_x,
1572                                          int mb_y,
1573                                          int width_in_mbs,
1574                                          int qp)
1575 {
1576     BEGIN_BATCH(batch, 12);
1577     
1578     OUT_BATCH(batch, CMD_MEDIA_OBJECT | (12 - 2));
1579     OUT_BATCH(batch, index);
1580     OUT_BATCH(batch, 0);
1581     OUT_BATCH(batch, 0);
1582     OUT_BATCH(batch, 0);
1583     OUT_BATCH(batch, 0);
1584    
1585     /*inline data */
1586     OUT_BATCH(batch, head_offset);
1587     OUT_BATCH(batch, batchbuffer_offset);
1588     OUT_BATCH(batch, 
1589               head_size << 16 |
1590               tail_size);
1591     OUT_BATCH(batch,
1592               number_mb_cmds << 16 |
1593               first_object << 2 |
1594               last_object << 1 |
1595               last_slice);
1596     OUT_BATCH(batch,
1597               mb_y << 8 |
1598               mb_x);
1599     OUT_BATCH(batch,
1600               qp << 16 |
1601               width_in_mbs);
1602
1603     ADVANCE_BATCH(batch);
1604 }
1605
1606 static void
1607 gen6_mfc_avc_batchbuffer_slice_command(VADriverContextP ctx,
1608                                        struct intel_encoder_context *encoder_context,
1609                                        VAEncSliceParameterBufferH264 *slice_param,
1610                                        int head_offset,
1611                                        unsigned short head_size,
1612                                        unsigned short tail_size,
1613                                        int batchbuffer_offset,
1614                                        int qp,
1615                                        int last_slice)
1616 {
1617     struct intel_batchbuffer *batch = encoder_context->base.batch;
1618     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1619     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1620     int total_mbs = slice_param->num_macroblocks;
1621     int number_mb_cmds = 128;
1622     int starting_mb = 0;
1623     int last_object = 0;
1624     int first_object = 1;
1625     int i;
1626     int mb_x, mb_y;
1627     int index = (slice_param->slice_type == SLICE_TYPE_I) ? MFC_BATCHBUFFER_AVC_INTRA : MFC_BATCHBUFFER_AVC_INTER;
1628
1629     for (i = 0; i < total_mbs / number_mb_cmds; i++) {
1630         last_object = (total_mbs - starting_mb) == number_mb_cmds;
1631         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1632         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1633         assert(mb_x <= 255 && mb_y <= 255);
1634
1635         starting_mb += number_mb_cmds;
1636
1637         gen6_mfc_batchbuffer_emit_object_command(batch,
1638                                                  index,
1639                                                  head_offset,
1640                                                  batchbuffer_offset,
1641                                                  head_size,
1642                                                  tail_size,
1643                                                  number_mb_cmds,
1644                                                  first_object,
1645                                                  last_object,
1646                                                  last_slice,
1647                                                  mb_x,
1648                                                  mb_y,
1649                                                  width_in_mbs,
1650                                                  qp);
1651
1652         if (first_object) {
1653             head_offset += head_size;
1654             batchbuffer_offset += head_size;
1655         }
1656
1657         if (last_object) {
1658             head_offset += tail_size;
1659             batchbuffer_offset += tail_size;
1660         }
1661
1662         batchbuffer_offset += number_mb_cmds * CMD_LEN_IN_OWORD;
1663
1664         first_object = 0;
1665     }
1666
1667     if (!last_object) {
1668         last_object = 1;
1669         number_mb_cmds = total_mbs % number_mb_cmds;
1670         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1671         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1672         assert(mb_x <= 255 && mb_y <= 255);
1673         starting_mb += number_mb_cmds;
1674
1675         gen6_mfc_batchbuffer_emit_object_command(batch,
1676                                                  index,
1677                                                  head_offset,
1678                                                  batchbuffer_offset,
1679                                                  head_size,
1680                                                  tail_size,
1681                                                  number_mb_cmds,
1682                                                  first_object,
1683                                                  last_object,
1684                                                  last_slice,
1685                                                  mb_x,
1686                                                  mb_y,
1687                                                  width_in_mbs,
1688                                                  qp);
1689     }
1690 }
1691                           
1692 /*
1693  * return size in Owords (16bytes)
1694  */         
1695 static int
1696 gen6_mfc_avc_batchbuffer_slice(VADriverContextP ctx,
1697                                struct encode_state *encode_state,
1698                                struct intel_encoder_context *encoder_context,
1699                                int slice_index,
1700                                int batchbuffer_offset)
1701 {
1702     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1703     struct intel_batchbuffer *slice_batch = mfc_context->aux_batchbuffer;
1704     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1705     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1706     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1707     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1708     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1709     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1710     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1711     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1712     unsigned char *slice_header = NULL;
1713     int slice_header_length_in_bits = 0;
1714     unsigned int tail_data[] = { 0x0, 0x0 };
1715     long head_offset;
1716     int old_used = intel_batchbuffer_used_size(slice_batch), used;
1717     unsigned short head_size, tail_size;
1718     int slice_type = pSliceParameter->slice_type;
1719
1720     if (rate_control_mode == VA_RC_CBR) {
1721         qp = mfc_context->bit_rate_control_context[slice_type].QpPrimeY;
1722         pSliceParameter->slice_qp_delta = qp - pPicParameter->pic_init_qp;
1723     }
1724
1725     /* only support for 8-bit pixel bit-depth */
1726     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
1727     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
1728     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
1729     assert(qp >= 0 && qp < 52);
1730
1731     head_offset = old_used / 16;
1732     gen6_mfc_avc_slice_state(ctx,
1733                              pPicParameter,
1734                              pSliceParameter,
1735                              encode_state,
1736                              encoder_context,
1737                              (rate_control_mode == VA_RC_CBR),
1738                              qp,
1739                              slice_batch);
1740
1741     if (slice_index == 0)
1742         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1743
1744     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1745
1746     // slice hander
1747     mfc_context->insert_object(ctx,
1748                                encoder_context,
1749                                (unsigned int *)slice_header,
1750                                ALIGN(slice_header_length_in_bits, 32) >> 5,
1751                                slice_header_length_in_bits & 0x1f,
1752                                5,  /* first 5 bytes are start code + nal unit type */
1753                                1,
1754                                0,
1755                                1,
1756                                slice_batch);
1757     free(slice_header);
1758
1759     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1760     used = intel_batchbuffer_used_size(slice_batch);
1761     head_size = (used - old_used) / 16;
1762     old_used = used;
1763
1764     /* tail */
1765     if (last_slice) {    
1766         mfc_context->insert_object(ctx,
1767                                    encoder_context,
1768                                    tail_data,
1769                                    2,
1770                                    8,
1771                                    2,
1772                                    1,
1773                                    1,
1774                                    0,
1775                                    slice_batch);
1776     } else {
1777         mfc_context->insert_object(ctx,
1778                                    encoder_context,
1779                                    tail_data,
1780                                    1,
1781                                    8,
1782                                    1,
1783                                    1,
1784                                    1,
1785                                    0,
1786                                    slice_batch);
1787     }
1788
1789     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1790     used = intel_batchbuffer_used_size(slice_batch);
1791     tail_size = (used - old_used) / 16;
1792
1793    
1794     gen6_mfc_avc_batchbuffer_slice_command(ctx,
1795                                            encoder_context,
1796                                            pSliceParameter,
1797                                            head_offset,
1798                                            head_size,
1799                                            tail_size,
1800                                            batchbuffer_offset,
1801                                            qp,
1802                                            last_slice);
1803
1804     return head_size + tail_size + pSliceParameter->num_macroblocks * CMD_LEN_IN_OWORD;
1805 }
1806
1807 static void
1808 gen6_mfc_avc_batchbuffer_pipeline(VADriverContextP ctx,
1809                                   struct encode_state *encode_state,
1810                                   struct intel_encoder_context *encoder_context)
1811 {
1812     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1813     struct intel_batchbuffer *batch = encoder_context->base.batch;
1814     int i, size, offset = 0;
1815     intel_batchbuffer_start_atomic(batch, 0x4000); 
1816     gen6_gpe_pipeline_setup(ctx, &mfc_context->gpe_context, batch);
1817
1818     for ( i = 0; i < encode_state->num_slice_params_ext; i++) {
1819         size = gen6_mfc_avc_batchbuffer_slice(ctx, encode_state, encoder_context, i, offset);
1820         offset += size;
1821     }
1822
1823     intel_batchbuffer_end_atomic(batch);
1824     intel_batchbuffer_flush(batch);
1825 }
1826
1827 static void
1828 gen6_mfc_build_avc_batchbuffer(VADriverContextP ctx, 
1829                                struct encode_state *encode_state,
1830                                struct intel_encoder_context *encoder_context)
1831 {
1832     gen6_mfc_batchbuffer_surfaces_setup(ctx, encode_state, encoder_context);
1833     gen6_mfc_batchbuffer_idrt_setup(ctx, encode_state, encoder_context);
1834     gen6_mfc_batchbuffer_constant_setup(ctx, encode_state, encoder_context);
1835     gen6_mfc_avc_batchbuffer_pipeline(ctx, encode_state, encoder_context);
1836 }
1837
1838 static dri_bo *
1839 gen6_mfc_avc_hardware_batchbuffer(VADriverContextP ctx,
1840                                   struct encode_state *encode_state,
1841                                   struct intel_encoder_context *encoder_context)
1842 {
1843     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1844
1845     gen6_mfc_build_avc_batchbuffer(ctx, encode_state, encoder_context);
1846     dri_bo_reference(mfc_context->mfc_batchbuffer_surface.bo);
1847
1848     return mfc_context->mfc_batchbuffer_surface.bo;
1849 }
1850
1851 #endif
1852
1853 int interlace_check(VADriverContextP ctx,
1854                    struct encode_state *encode_state,
1855                    struct intel_encoder_context *encoder_context) {
1856     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1857     VAEncSliceParameterBufferH264 *pSliceParameter;
1858     int i;
1859     int mbCount = 0;
1860     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1861     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1862   
1863     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1864         pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[i]->buffer; 
1865         mbCount += pSliceParameter->num_macroblocks; 
1866     }
1867     
1868     if ( mbCount == ( width_in_mbs * height_in_mbs ) )
1869         return 0;
1870
1871     return 1;
1872 }
1873
1874
1875 static void
1876 gen6_mfc_avc_pipeline_programing(VADriverContextP ctx,
1877                                  struct encode_state *encode_state,
1878                                  struct intel_encoder_context *encoder_context)
1879 {
1880     struct intel_batchbuffer *batch = encoder_context->base.batch;
1881     dri_bo *slice_batch_bo;
1882
1883     if ( interlace_check(ctx, encode_state, encoder_context) ) {
1884         fprintf(stderr, "Current VA driver don't support interlace mode!\n");
1885         assert(0);
1886         return; 
1887     }
1888
1889 #if __SOFTWARE__
1890     slice_batch_bo = gen6_mfc_avc_software_batchbuffer(ctx, encode_state, encoder_context);
1891 #else
1892     slice_batch_bo = gen6_mfc_avc_hardware_batchbuffer(ctx, encode_state, encoder_context);
1893 #endif
1894
1895     // begin programing
1896     intel_batchbuffer_start_atomic_bcs(batch, 0x4000); 
1897     intel_batchbuffer_emit_mi_flush(batch);
1898     
1899     // picture level programing
1900     gen6_mfc_avc_pipeline_picture_programing(ctx, encode_state, encoder_context);
1901
1902     BEGIN_BCS_BATCH(batch, 2);
1903     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_START | (1 << 8));
1904     OUT_BCS_RELOC(batch,
1905                   slice_batch_bo,
1906                   I915_GEM_DOMAIN_COMMAND, 0, 
1907                   0);
1908     ADVANCE_BCS_BATCH(batch);
1909
1910     // end programing
1911     intel_batchbuffer_end_atomic(batch);
1912
1913     dri_bo_unreference(slice_batch_bo);
1914 }
1915
1916 static VAStatus
1917 gen6_mfc_avc_encode_picture(VADriverContextP ctx, 
1918                             struct encode_state *encode_state,
1919                             struct intel_encoder_context *encoder_context)
1920 {
1921     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1922     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1923     int current_frame_bits_size;
1924     int sts;
1925  
1926     for (;;) {
1927         gen6_mfc_init(ctx, encoder_context);
1928         gen6_mfc_avc_prepare(ctx, encode_state, encoder_context);
1929         /*Programing bcs pipeline*/
1930         gen6_mfc_avc_pipeline_programing(ctx, encode_state, encoder_context);   //filling the pipeline
1931         gen6_mfc_run(ctx, encode_state, encoder_context);
1932         if (rate_control_mode == VA_RC_CBR /*|| rate_control_mode == VA_RC_VBR*/) {
1933             gen6_mfc_stop(ctx, encode_state, encoder_context, &current_frame_bits_size);
1934             sts = gen6_mfc_brc_postpack(encode_state, mfc_context, current_frame_bits_size);
1935             if (sts == BRC_NO_HRD_VIOLATION) {
1936                 gen6_mfc_hrd_context_update(encode_state, mfc_context);
1937                 break;
1938             }
1939             else if (sts == BRC_OVERFLOW_WITH_MIN_QP || sts == BRC_UNDERFLOW_WITH_MAX_QP) {
1940                 if (!mfc_context->hrd.violation_noted) {
1941                     fprintf(stderr, "Unrepairable %s!\n", (sts == BRC_OVERFLOW_WITH_MIN_QP)? "overflow": "underflow");
1942                     mfc_context->hrd.violation_noted = 1;
1943                 }
1944                 return VA_STATUS_SUCCESS;
1945             }
1946         } else {
1947             break;
1948         }
1949     }
1950
1951     return VA_STATUS_SUCCESS;
1952 }
1953
1954 VAStatus
1955 gen6_mfc_pipeline(VADriverContextP ctx,
1956                   VAProfile profile,
1957                   struct encode_state *encode_state,
1958                   struct intel_encoder_context *encoder_context)
1959 {
1960     VAStatus vaStatus;
1961
1962     switch (profile) {
1963     case VAProfileH264Baseline:
1964     case VAProfileH264Main:
1965     case VAProfileH264High:
1966         vaStatus = gen6_mfc_avc_encode_picture(ctx, encode_state, encoder_context);
1967         break;
1968
1969         /* FIXME: add for other profile */
1970     default:
1971         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1972         break;
1973     }
1974
1975     return vaStatus;
1976 }
1977
1978 void
1979 gen6_mfc_context_destroy(void *context)
1980 {
1981     struct gen6_mfc_context *mfc_context = context;
1982     int i;
1983
1984     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
1985     mfc_context->post_deblocking_output.bo = NULL;
1986
1987     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
1988     mfc_context->pre_deblocking_output.bo = NULL;
1989
1990     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
1991     mfc_context->uncompressed_picture_source.bo = NULL;
1992
1993     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
1994     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
1995
1996     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
1997         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
1998         mfc_context->direct_mv_buffers[i].bo = NULL;
1999     }
2000
2001     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
2002     mfc_context->intra_row_store_scratch_buffer.bo = NULL;
2003
2004     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
2005     mfc_context->macroblock_status_buffer.bo = NULL;
2006
2007     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
2008     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = NULL;
2009
2010     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
2011     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = NULL;
2012
2013
2014     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
2015         dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
2016         mfc_context->reference_surfaces[i].bo = NULL;  
2017     }
2018
2019     i965_gpe_context_destroy(&mfc_context->gpe_context);
2020
2021     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
2022     mfc_context->mfc_batchbuffer_surface.bo = NULL;
2023
2024     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
2025     mfc_context->aux_batchbuffer_surface.bo = NULL;
2026
2027     if (mfc_context->aux_batchbuffer)
2028         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
2029
2030     mfc_context->aux_batchbuffer = NULL;
2031
2032     free(mfc_context);
2033 }
2034
2035 void gen6_mfc_brc_prepare(struct encode_state *encode_state,
2036                           struct intel_encoder_context *encoder_context)
2037 {
2038     unsigned int rate_control_mode = encoder_context->rate_control_mode;
2039     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
2040
2041     if (rate_control_mode == VA_RC_CBR) {
2042         /*Programing bit rate control */
2043         if ( mfc_context->bit_rate_control_context[SLICE_TYPE_I].MaxSizeInWord == 0 ) {
2044             gen6_mfc_bit_rate_control_context_init(encode_state, mfc_context);
2045             gen6_mfc_brc_init(encode_state, encoder_context);
2046         }
2047
2048         /*Programing HRD control */
2049         if ( mfc_context->vui_hrd.i_cpb_size_value == 0 )
2050             gen6_mfc_hrd_context_init(encode_state, encoder_context);    
2051     }
2052 }
2053
2054 Bool gen6_mfc_context_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
2055 {
2056     struct gen6_mfc_context *mfc_context = calloc(1, sizeof(struct gen6_mfc_context));
2057
2058     mfc_context->gpe_context.surface_state_binding_table.length = (SURFACE_STATE_PADDED_SIZE + sizeof(unsigned int)) * MAX_MEDIA_SURFACES_GEN6;
2059
2060     mfc_context->gpe_context.idrt.max_entries = MAX_GPE_KERNELS;
2061     mfc_context->gpe_context.idrt.entry_size = sizeof(struct gen6_interface_descriptor_data);
2062
2063     mfc_context->gpe_context.curbe.length = 32 * 4;
2064
2065     mfc_context->gpe_context.vfe_state.max_num_threads = 60 - 1;
2066     mfc_context->gpe_context.vfe_state.num_urb_entries = 16;
2067     mfc_context->gpe_context.vfe_state.gpgpu_mode = 0;
2068     mfc_context->gpe_context.vfe_state.urb_entry_size = 59 - 1;
2069     mfc_context->gpe_context.vfe_state.curbe_allocation_size = 37 - 1;
2070
2071     i965_gpe_load_kernels(ctx,
2072                           &mfc_context->gpe_context,
2073                           gen6_mfc_kernels,
2074                           NUM_MFC_KERNEL);
2075
2076     mfc_context->pipe_mode_select = gen6_mfc_pipe_mode_select;
2077     mfc_context->set_surface_state = gen6_mfc_surface_state;
2078     mfc_context->ind_obj_base_addr_state = gen6_mfc_ind_obj_base_addr_state;
2079     mfc_context->avc_img_state = gen6_mfc_avc_img_state;
2080     mfc_context->avc_qm_state = gen6_mfc_avc_qm_state;
2081     mfc_context->avc_fqm_state = gen6_mfc_avc_fqm_state;
2082     mfc_context->insert_object = gen6_mfc_avc_insert_object;
2083     mfc_context->buffer_suface_setup = i965_gpe_buffer_suface_setup;
2084
2085     encoder_context->mfc_context = mfc_context;
2086     encoder_context->mfc_context_destroy = gen6_mfc_context_destroy;
2087     encoder_context->mfc_pipeline = gen6_mfc_pipeline;
2088     encoder_context->mfc_brc_prepare = gen6_mfc_brc_prepare;
2089
2090     return True;
2091 }