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