Fix the filling of MFC batchbuffer for software path
[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
34 #include "intel_batchbuffer.h"
35 #include "i965_defines.h"
36 #include "i965_structs.h"
37 #include "i965_drv_video.h"
38 #include "i965_encoder.h"
39 #include "i965_encoder_utils.h"
40 #include "gen6_mfc.h"
41 #include "gen6_vme.h"
42
43 #define CMD_LEN_IN_OWORD        4
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
362     if (batch == NULL)
363         batch = encoder_context->base.batch;
364
365     if (slice_type == SLICE_TYPE_I)
366         bit_rate_control_target = 0;
367     else
368         bit_rate_control_target = 1;
369
370     if (slice_type == SLICE_TYPE_P) {
371         weighted_pred_idc = pic_param->pic_fields.bits.weighted_pred_flag;
372     } else if (slice_type == SLICE_TYPE_B) {
373         weighted_pred_idc = pic_param->pic_fields.bits.weighted_bipred_idc;
374     }
375
376     maxQpN = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpNegModifier;
377     maxQpP = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpPosModifier;
378
379     for (i = 0; i < 6; i++)
380         correct[i] = mfc_context->bit_rate_control_context[bit_rate_control_target].Correct[i];
381
382     grow = mfc_context->bit_rate_control_context[bit_rate_control_target].GrowInit + 
383         (mfc_context->bit_rate_control_context[bit_rate_control_target].GrowResistance << 4);
384     shrink = mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkInit + 
385         (mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkResistance << 4);
386
387     BEGIN_BCS_BATCH(batch, 11);;
388
389     OUT_BCS_BATCH(batch, MFX_AVC_SLICE_STATE | (11 - 2) );
390     OUT_BCS_BATCH(batch, slice_type);                   /*Slice Type: I:P:B Slice*/
391
392     if (slice_type == SLICE_TYPE_I) {
393         OUT_BCS_BATCH(batch, 0);                        /*no reference frames and pred_weight_table*/
394     } else {
395         OUT_BCS_BATCH(batch, 0x00010000);       /*1 reference frame*/
396     }
397
398     OUT_BCS_BATCH(batch, 
399                   (weighted_pred_idc << 30) |
400                   (slice_param->direct_spatial_mv_pred_flag<<29) |             /*Direct Prediction Type*/
401                   (slice_param->disable_deblocking_filter_idc << 27) |
402                   (slice_param->cabac_init_idc << 24) |
403                   (qp<<16) |                    /*Slice Quantization Parameter*/
404                   ((slice_param->slice_beta_offset_div2 & 0xf) << 8) |
405                   ((slice_param->slice_alpha_c0_offset_div2 & 0xf) << 0));
406     OUT_BCS_BATCH(batch,
407                   (beginy << 24) |                      /*First MB X&Y , the begin postion of current slice*/
408                   (beginx << 16) |
409                   slice_param->macroblock_address );
410     OUT_BCS_BATCH(batch, (nexty << 16) | nextx);                       /*Next slice first MB X&Y*/
411     OUT_BCS_BATCH(batch, 
412                   (rate_control_enable << 31) |         /*in CBR mode RateControlCounterEnable = enable*/
413                   (1 << 30) |           /*ResetRateControlCounter*/
414                   (0 << 28) |           /*RC Triggle Mode = Always Rate Control*/
415                   (4 << 24) |     /*RC Stable Tolerance, middle level*/
416                   (rate_control_enable << 23) |     /*RC Panic Enable*/                 
417                   (0 << 22) |     /*QP mode, don't modfiy CBP*/
418                   (0 << 21) |     /*MB Type Direct Conversion Enabled*/ 
419                   (0 << 20) |     /*MB Type Skip Conversion Enabled*/ 
420                   (last_slice << 19) |     /*IsLastSlice*/
421                   (0 << 18) |   /*BitstreamOutputFlag Compressed BitStream Output Disable Flag 0:enable 1:disable*/
422                   (1 << 17) |       /*HeaderPresentFlag*/       
423                   (1 << 16) |       /*SliceData PresentFlag*/
424                   (1 << 15) |       /*TailPresentFlag*/
425                   (1 << 13) |       /*RBSP NAL TYPE*/   
426                   (0 << 12) );    /*CabacZeroWordInsertionEnable*/
427     OUT_BCS_BATCH(batch, mfc_context->mfc_indirect_pak_bse_object.offset);
428     OUT_BCS_BATCH(batch,
429                   (maxQpN << 24) |     /*Target QP - 24 is lowest QP*/ 
430                   (maxQpP << 16) |     /*Target QP + 20 is highest QP*/
431                   (shrink << 8)  |
432                   (grow << 0));   
433     OUT_BCS_BATCH(batch,
434                   (correct[5] << 20) |
435                   (correct[4] << 16) |
436                   (correct[3] << 12) |
437                   (correct[2] << 8) |
438                   (correct[1] << 4) |
439                   (correct[0] << 0));
440     OUT_BCS_BATCH(batch, 0);
441
442     ADVANCE_BCS_BATCH(batch);
443 }
444
445 static void gen6_mfc_avc_qm_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
446 {
447     struct intel_batchbuffer *batch = encoder_context->base.batch;
448     int i;
449
450     BEGIN_BCS_BATCH(batch, 58);
451
452     OUT_BCS_BATCH(batch, MFX_AVC_QM_STATE | 56);
453     OUT_BCS_BATCH(batch, 0xFF ) ; 
454     for( i = 0; i < 56; i++) {
455         OUT_BCS_BATCH(batch, 0x10101010); 
456     }   
457
458     ADVANCE_BCS_BATCH(batch);
459 }
460
461 static void gen6_mfc_avc_fqm_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
462 {
463     struct intel_batchbuffer *batch = encoder_context->base.batch;
464     int i;
465
466     BEGIN_BCS_BATCH(batch, 113);
467     OUT_BCS_BATCH(batch, MFC_AVC_FQM_STATE | (113 - 2));
468
469     for(i = 0; i < 112;i++) {
470         OUT_BCS_BATCH(batch, 0x10001000);
471     }   
472
473     ADVANCE_BCS_BATCH(batch);   
474 }
475
476 static void
477 gen6_mfc_avc_ref_idx_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
478 {
479     struct intel_batchbuffer *batch = encoder_context->base.batch;
480     int i;
481
482     BEGIN_BCS_BATCH(batch, 10);
483     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
484     OUT_BCS_BATCH(batch, 0);                  //Select L0
485     OUT_BCS_BATCH(batch, 0x80808020);         //Only 1 reference
486     for(i = 0; i < 7; i++) {
487         OUT_BCS_BATCH(batch, 0x80808080);
488     }   
489     ADVANCE_BCS_BATCH(batch);
490
491     BEGIN_BCS_BATCH(batch, 10);
492     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
493     OUT_BCS_BATCH(batch, 1);                  //Select L1
494     OUT_BCS_BATCH(batch, 0x80808022);         //Only 1 reference
495     for(i = 0; i < 7; i++) {
496         OUT_BCS_BATCH(batch, 0x80808080);
497     }   
498     ADVANCE_BCS_BATCH(batch);
499 }
500         
501 static void
502 gen6_mfc_avc_insert_object(VADriverContextP ctx, struct intel_encoder_context *encoder_context,
503                            unsigned int *insert_data, int lenght_in_dws, int data_bits_in_last_dw,
504                            int skip_emul_byte_count, int is_last_header, int is_end_of_slice, int emulation_flag,
505                            struct intel_batchbuffer *batch)
506 {
507     if (batch == NULL)
508         batch = encoder_context->base.batch;
509
510     BEGIN_BCS_BATCH(batch, lenght_in_dws + 2);
511
512     OUT_BCS_BATCH(batch, MFC_AVC_INSERT_OBJECT | (lenght_in_dws + 2 - 2));
513
514     OUT_BCS_BATCH(batch,
515                   (0 << 16) |   /* always start at offset 0 */
516                   (data_bits_in_last_dw << 8) |
517                   (skip_emul_byte_count << 4) |
518                   (!!emulation_flag << 3) |
519                   ((!!is_last_header) << 2) |
520                   ((!!is_end_of_slice) << 1) |
521                   (0 << 0));    /* FIXME: ??? */
522
523     intel_batchbuffer_data(batch, insert_data, lenght_in_dws * 4);
524     ADVANCE_BCS_BATCH(batch);
525 }
526
527 static void gen6_mfc_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
528 {
529     struct i965_driver_data *i965 = i965_driver_data(ctx);
530     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
531     dri_bo *bo;
532     int i;
533
534     /*Encode common setup for MFC*/
535     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
536     mfc_context->post_deblocking_output.bo = NULL;
537
538     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
539     mfc_context->pre_deblocking_output.bo = NULL;
540
541     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
542     mfc_context->uncompressed_picture_source.bo = NULL;
543
544     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
545     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
546
547     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
548         if ( mfc_context->direct_mv_buffers[i].bo != NULL);
549         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
550         mfc_context->direct_mv_buffers[i].bo = NULL;
551     }
552
553     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
554         if (mfc_context->reference_surfaces[i].bo != NULL)
555             dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
556         mfc_context->reference_surfaces[i].bo = NULL;  
557     }
558
559     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
560     bo = dri_bo_alloc(i965->intel.bufmgr,
561                       "Buffer",
562                       128 * 64,
563                       64);
564     assert(bo);
565     mfc_context->intra_row_store_scratch_buffer.bo = bo;
566
567     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
568     bo = dri_bo_alloc(i965->intel.bufmgr,
569                       "Buffer",
570                       128*128*16,
571                       64);
572     assert(bo);
573     mfc_context->macroblock_status_buffer.bo = bo;
574
575     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
576     bo = dri_bo_alloc(i965->intel.bufmgr,
577                       "Buffer",
578                       49152,  /* 6 * 128 * 64 */
579                       64);
580     assert(bo);
581     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = bo;
582
583     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
584     bo = dri_bo_alloc(i965->intel.bufmgr,
585                       "Buffer",
586                       12288, /* 1.5 * 128 * 64 */
587                       0x1000);
588     assert(bo);
589     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = bo;
590
591     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
592     mfc_context->mfc_batchbuffer_surface.bo = NULL;
593
594     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
595     mfc_context->aux_batchbuffer_surface.bo = NULL;
596
597     if (mfc_context->aux_batchbuffer)
598         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
599
600     mfc_context->aux_batchbuffer = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD);
601     mfc_context->aux_batchbuffer_surface.bo = mfc_context->aux_batchbuffer->buffer;
602     dri_bo_reference(mfc_context->aux_batchbuffer_surface.bo);
603     mfc_context->aux_batchbuffer_surface.pitch = 16;
604     mfc_context->aux_batchbuffer_surface.num_blocks = mfc_context->aux_batchbuffer->size / 16;
605     mfc_context->aux_batchbuffer_surface.size_block = 16;
606
607     i965_gpe_context_init(ctx, &mfc_context->gpe_context);
608 }
609
610 static void gen6_mfc_avc_pipeline_header_programing(VADriverContextP ctx,
611                                                     struct encode_state *encode_state,
612                                                     struct intel_encoder_context *encoder_context,
613                                                     struct intel_batchbuffer *slice_batch)
614 {
615     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
616     static int count = 0;
617     unsigned int rate_control_mode = encoder_context->rate_control_mode;
618
619     if (encode_state->packed_header_data[VAEncPackedHeaderH264_SPS]) {
620         VAEncPackedHeaderParameterBuffer *param = NULL;
621         unsigned int *header_data = (unsigned int *)encode_state->packed_header_data[VAEncPackedHeaderH264_SPS]->buffer;
622         unsigned int length_in_bits;
623
624         assert(encode_state->packed_header_param[VAEncPackedHeaderH264_SPS]);
625         param = (VAEncPackedHeaderParameterBuffer *)encode_state->packed_header_param[VAEncPackedHeaderH264_SPS]->buffer;
626         length_in_bits = param->bit_length;
627
628         mfc_context->insert_object(ctx,
629                                    encoder_context,
630                                    header_data,
631                                    ALIGN(length_in_bits, 32) >> 5,
632                                    length_in_bits & 0x1f,
633                                    5,   /* FIXME: check it */
634                                    0,
635                                    0,
636                                    !param->has_emulation_bytes,
637                                    slice_batch);
638     }
639
640     if (encode_state->packed_header_data[VAEncPackedHeaderH264_PPS]) {
641         VAEncPackedHeaderParameterBuffer *param = NULL;
642         unsigned int *header_data = (unsigned int *)encode_state->packed_header_data[VAEncPackedHeaderH264_PPS]->buffer;
643         unsigned int length_in_bits;
644
645         assert(encode_state->packed_header_param[VAEncPackedHeaderH264_PPS]);
646         param = (VAEncPackedHeaderParameterBuffer *)encode_state->packed_header_param[VAEncPackedHeaderH264_PPS]->buffer;
647         length_in_bits = param->bit_length;
648
649         mfc_context->insert_object(ctx,
650                                    encoder_context,
651                                    header_data,
652                                    ALIGN(length_in_bits, 32) >> 5,
653                                    length_in_bits & 0x1f,
654                                    5, /* FIXME: check it */
655                                    0,
656                                    0,
657                                    !param->has_emulation_bytes,
658                                    slice_batch);
659     }
660     
661     if ( (rate_control_mode == VA_RC_CBR) && encode_state->packed_header_data[VAEncPackedHeaderH264_SPS]) {       // this is frist AU
662         struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
663
664         unsigned char *sei_data = NULL;
665         int length_in_bits = build_avc_sei_buffering_period(mfc_context->vui_hrd.i_initial_cpb_removal_delay_length, 
666                                                             mfc_context->vui_hrd.i_initial_cpb_removal_delay, 0, &sei_data);
667         mfc_context->insert_object(ctx,
668                                    encoder_context,
669                                    (unsigned int *)sei_data,
670                                    ALIGN(length_in_bits, 32) >> 5,
671                                    length_in_bits & 0x1f,
672                                    4,   
673                                    0,   
674                                    0,   
675                                    1,
676                                    slice_batch);  
677         free(sei_data);
678     }    
679
680     // SEI pic_timing header
681     if (rate_control_mode == VA_RC_CBR) {   
682         struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
683         unsigned char *sei_data = NULL;
684         int length_in_bits = build_avc_sei_pic_timing( mfc_context->vui_hrd.i_cpb_removal_delay_length,
685                                                        mfc_context->vui_hrd.i_cpb_removal_delay * mfc_context->vui_hrd.i_frame_number,
686                                                        mfc_context->vui_hrd.i_dpb_output_delay_length,
687                                                        0, &sei_data);
688         mfc_context->insert_object(ctx,
689                                    encoder_context,
690                                    (unsigned int *)sei_data,
691                                    ALIGN(length_in_bits, 32) >> 5,
692                                    length_in_bits & 0x1f,
693                                    4,   
694                                    0,   
695                                    0,   
696                                    1,
697                                    slice_batch);  
698         free(sei_data);
699     }  
700     
701     count++;
702 }
703
704 static void gen6_mfc_avc_pipeline_picture_programing( VADriverContextP ctx,
705                                       struct encode_state *encode_state,
706                                       struct intel_encoder_context *encoder_context)
707 {
708     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
709
710     mfc_context->pipe_mode_select(ctx, MFX_FORMAT_AVC, encoder_context);
711     mfc_context->set_surface_state(ctx, encoder_context);
712     mfc_context->ind_obj_base_addr_state(ctx, encoder_context);
713     gen6_mfc_pipe_buf_addr_state(ctx, encoder_context);
714     gen6_mfc_bsp_buf_base_addr_state(ctx, encoder_context);
715     mfc_context->avc_img_state(ctx, encode_state, encoder_context);
716     mfc_context->avc_qm_state(ctx, encoder_context);
717     mfc_context->avc_fqm_state(ctx, encoder_context);
718     gen6_mfc_avc_directmode_state(ctx, encoder_context); 
719     gen6_mfc_avc_ref_idx_state(ctx, encoder_context);
720 }
721
722 static void 
723 gen6_mfc_free_avc_surface(void **data)
724 {
725     struct gen6_mfc_avc_surface_aux *avc_surface = *data;
726
727     if (!avc_surface)
728         return;
729
730     dri_bo_unreference(avc_surface->dmv_top);
731     avc_surface->dmv_top = NULL;
732     dri_bo_unreference(avc_surface->dmv_bottom);
733     avc_surface->dmv_bottom = NULL;
734
735     free(avc_surface);
736     *data = NULL;
737 }
738
739 static void
740 gen6_mfc_bit_rate_control_context_init(struct encode_state *encode_state, 
741                                        struct gen6_mfc_context *mfc_context)
742 {
743     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
744     
745     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
746     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
747     float fps =  pSequenceParameter->time_scale * 0.5 / pSequenceParameter->num_units_in_tick ;
748     int inter_mb_size = pSequenceParameter->bits_per_second * 1.0 / (fps+4.0) / width_in_mbs / height_in_mbs;
749     int intra_mb_size = inter_mb_size * 5.0;
750     int i;
751     
752     mfc_context->bit_rate_control_context[0].target_mb_size = intra_mb_size;
753     mfc_context->bit_rate_control_context[0].target_frame_size = intra_mb_size * width_in_mbs * height_in_mbs;
754     mfc_context->bit_rate_control_context[1].target_mb_size = inter_mb_size;
755     mfc_context->bit_rate_control_context[1].target_frame_size = inter_mb_size * width_in_mbs * height_in_mbs;
756
757     for(i = 0 ; i < 2; i++) {
758         mfc_context->bit_rate_control_context[i].QpPrimeY = 26;
759         mfc_context->bit_rate_control_context[i].MaxQpNegModifier = 6;
760         mfc_context->bit_rate_control_context[i].MaxQpPosModifier = 6;
761         mfc_context->bit_rate_control_context[i].GrowInit = 6;
762         mfc_context->bit_rate_control_context[i].GrowResistance = 4;
763         mfc_context->bit_rate_control_context[i].ShrinkInit = 6;
764         mfc_context->bit_rate_control_context[i].ShrinkResistance = 4;
765         
766         mfc_context->bit_rate_control_context[i].Correct[0] = 8;
767         mfc_context->bit_rate_control_context[i].Correct[1] = 4;
768         mfc_context->bit_rate_control_context[i].Correct[2] = 2;
769         mfc_context->bit_rate_control_context[i].Correct[3] = 2;
770         mfc_context->bit_rate_control_context[i].Correct[4] = 4;
771         mfc_context->bit_rate_control_context[i].Correct[5] = 8;
772     }
773     
774     mfc_context->bit_rate_control_context[0].TargetSizeInWord = (intra_mb_size + 16)/ 16;
775     mfc_context->bit_rate_control_context[1].TargetSizeInWord = (inter_mb_size + 16)/ 16;
776
777     mfc_context->bit_rate_control_context[0].MaxSizeInWord = mfc_context->bit_rate_control_context[0].TargetSizeInWord * 1.5;
778     mfc_context->bit_rate_control_context[1].MaxSizeInWord = mfc_context->bit_rate_control_context[1].TargetSizeInWord * 1.5;
779 }
780
781 static int gen6_mfc_bit_rate_control_context_update(struct encode_state *encode_state, 
782                                                     struct gen6_mfc_context *mfc_context,
783                                                     int current_frame_size)
784 {
785     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[0]->buffer; 
786     int control_index = 1 - (pSliceParameter->slice_type == SLICE_TYPE_I);
787     int oldQp = mfc_context->bit_rate_control_context[control_index].QpPrimeY;
788
789     /*
790       printf("conrol_index = %d, start_qp = %d, result = %d, target = %d\n", control_index, 
791       mfc_context->bit_rate_control_context[control_index].QpPrimeY, current_frame_size,
792       mfc_context->bit_rate_control_context[control_index].target_frame_size );
793     */
794
795     if ( current_frame_size > mfc_context->bit_rate_control_context[control_index].target_frame_size * 4.0 ) {
796         mfc_context->bit_rate_control_context[control_index].QpPrimeY += 4;
797     } else if ( current_frame_size > mfc_context->bit_rate_control_context[control_index].target_frame_size * 2.0 ) {
798         mfc_context->bit_rate_control_context[control_index].QpPrimeY += 3;
799     } else if ( current_frame_size > mfc_context->bit_rate_control_context[control_index].target_frame_size * 1.50 ) {
800         mfc_context->bit_rate_control_context[control_index].QpPrimeY += 2;
801     } else if ( current_frame_size > mfc_context->bit_rate_control_context[control_index].target_frame_size * 1.20 ) {
802         mfc_context->bit_rate_control_context[control_index].QpPrimeY ++;
803     } else if (current_frame_size < mfc_context->bit_rate_control_context[control_index].target_frame_size * 0.30 )  {
804         mfc_context->bit_rate_control_context[control_index].QpPrimeY -= 3;
805     } else if (current_frame_size < mfc_context->bit_rate_control_context[control_index].target_frame_size * 0.50 )  {
806         mfc_context->bit_rate_control_context[control_index].QpPrimeY -= 2;
807     } else if (current_frame_size < mfc_context->bit_rate_control_context[control_index].target_frame_size * 0.80 )  {
808         mfc_context->bit_rate_control_context[control_index].QpPrimeY --;
809     }
810     
811     if ( mfc_context->bit_rate_control_context[control_index].QpPrimeY > 51)
812         mfc_context->bit_rate_control_context[control_index].QpPrimeY = 51;
813     if ( mfc_context->bit_rate_control_context[control_index].QpPrimeY < 1)
814         mfc_context->bit_rate_control_context[control_index].QpPrimeY = 1;
815  
816     if ( mfc_context->bit_rate_control_context[control_index].QpPrimeY != oldQp)
817         return 0;
818
819     return 1;
820 }
821
822 static void 
823 gen6_mfc_hrd_context_init(struct encode_state *encode_state,
824                           struct intel_encoder_context *encoder_context)
825 {
826     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
827     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
828     unsigned int rate_control_mode = encoder_context->rate_control_mode;
829     int target_bit_rate = pSequenceParameter->bits_per_second;
830     
831     // current we only support CBR mode.
832     if (rate_control_mode == VA_RC_CBR) {
833         mfc_context->vui_hrd.i_bit_rate_value = target_bit_rate >> 10;
834         mfc_context->vui_hrd.i_cpb_size_value = (target_bit_rate * 8) >> 10;
835         mfc_context->vui_hrd.i_initial_cpb_removal_delay = mfc_context->vui_hrd.i_cpb_size_value * 0.5 * 1024 / target_bit_rate * 90000;
836         mfc_context->vui_hrd.i_cpb_removal_delay = 2;
837         mfc_context->vui_hrd.i_frame_number = 0;
838
839         mfc_context->vui_hrd.i_initial_cpb_removal_delay_length = 24; 
840         mfc_context->vui_hrd.i_cpb_removal_delay_length = 24;
841         mfc_context->vui_hrd.i_dpb_output_delay_length = 24;
842     }
843
844 }
845
846 static void 
847 gen6_mfc_hrd_context_update(struct encode_state *encode_state, 
848                           struct gen6_mfc_context *mfc_context) 
849 {
850     mfc_context->vui_hrd.i_frame_number++;
851 }
852
853 static VAStatus gen6_mfc_avc_prepare(VADriverContextP ctx, 
854                                      struct encode_state *encode_state,
855                                      struct intel_encoder_context *encoder_context)
856 {
857     struct i965_driver_data *i965 = i965_driver_data(ctx);
858     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
859     struct object_surface *obj_surface; 
860     struct object_buffer *obj_buffer;
861     struct gen6_mfc_avc_surface_aux* gen6_avc_surface;
862     dri_bo *bo;
863     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
864     unsigned int rate_control_mode = encoder_context->rate_control_mode;
865     VAStatus vaStatus = VA_STATUS_SUCCESS;
866     int i, j, enable_avc_ildb = 0;
867     VAEncSliceParameterBufferH264 *slice_param;
868
869     for (j = 0; j < encode_state->num_slice_params_ext && enable_avc_ildb == 0; j++) {
870         assert(encode_state->slice_params_ext && encode_state->slice_params_ext[j]->buffer);
871         slice_param = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[j]->buffer;
872
873         for (i = 0; i < encode_state->slice_params_ext[j]->num_elements; i++) {
874             assert((slice_param->slice_type == SLICE_TYPE_I) ||
875                    (slice_param->slice_type == SLICE_TYPE_SI) ||
876                    (slice_param->slice_type == SLICE_TYPE_P) ||
877                    (slice_param->slice_type == SLICE_TYPE_SP) ||
878                    (slice_param->slice_type == SLICE_TYPE_B));
879
880             if (slice_param->disable_deblocking_filter_idc != 1) {
881                 enable_avc_ildb = 1;
882                 break;
883             }
884
885             slice_param++;
886         }
887     }
888
889     /*Setup all the input&output object*/
890
891     /* Setup current frame and current direct mv buffer*/
892     obj_surface = SURFACE(pPicParameter->CurrPic.picture_id);
893     assert(obj_surface);
894     i965_check_alloc_surface_bo(ctx, obj_surface, 1, VA_FOURCC('N','V','1','2'), SUBSAMPLE_YUV420);
895
896     if ( obj_surface->private_data == NULL) {
897         gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
898         gen6_avc_surface->dmv_top = 
899             dri_bo_alloc(i965->intel.bufmgr,
900                          "Buffer",
901                          68*8192, 
902                          64);
903         gen6_avc_surface->dmv_bottom = 
904             dri_bo_alloc(i965->intel.bufmgr,
905                          "Buffer",
906                          68*8192, 
907                          64);
908         assert(gen6_avc_surface->dmv_top);
909         assert(gen6_avc_surface->dmv_bottom);
910         obj_surface->private_data = (void *)gen6_avc_surface;
911         obj_surface->free_private_data = (void *)gen6_mfc_free_avc_surface; 
912     }
913     gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
914     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 2].bo = gen6_avc_surface->dmv_top;
915     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 1].bo = gen6_avc_surface->dmv_bottom;
916     dri_bo_reference(gen6_avc_surface->dmv_top);
917     dri_bo_reference(gen6_avc_surface->dmv_bottom);
918
919     if (enable_avc_ildb) {
920         mfc_context->post_deblocking_output.bo = obj_surface->bo;
921         dri_bo_reference(mfc_context->post_deblocking_output.bo);
922     } else {
923         mfc_context->pre_deblocking_output.bo = obj_surface->bo;
924         dri_bo_reference(mfc_context->pre_deblocking_output.bo);
925     }
926
927     mfc_context->surface_state.width = obj_surface->orig_width;
928     mfc_context->surface_state.height = obj_surface->orig_height;
929     mfc_context->surface_state.w_pitch = obj_surface->width;
930     mfc_context->surface_state.h_pitch = obj_surface->height;
931     
932     /* Setup reference frames and direct mv buffers*/
933     for(i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++) {
934         if ( pPicParameter->ReferenceFrames[i].picture_id != VA_INVALID_ID ) { 
935             obj_surface = SURFACE(pPicParameter->ReferenceFrames[i].picture_id);
936             assert(obj_surface);
937             if (obj_surface->bo != NULL) {
938                 mfc_context->reference_surfaces[i].bo = obj_surface->bo;
939                 dri_bo_reference(obj_surface->bo);
940             }
941             /* Check DMV buffer */
942             if ( obj_surface->private_data == NULL) {
943                 
944                 gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
945                 gen6_avc_surface->dmv_top = 
946                     dri_bo_alloc(i965->intel.bufmgr,
947                                  "Buffer",
948                                  68*8192, 
949                                  64);
950                 gen6_avc_surface->dmv_bottom = 
951                     dri_bo_alloc(i965->intel.bufmgr,
952                                  "Buffer",
953                                  68*8192, 
954                                  64);
955                 assert(gen6_avc_surface->dmv_top);
956                 assert(gen6_avc_surface->dmv_bottom);
957                 obj_surface->private_data = gen6_avc_surface;
958                 obj_surface->free_private_data = gen6_mfc_free_avc_surface; 
959             }
960     
961             gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
962             /* Setup DMV buffer */
963             mfc_context->direct_mv_buffers[i*2].bo = gen6_avc_surface->dmv_top;
964             mfc_context->direct_mv_buffers[i*2+1].bo = gen6_avc_surface->dmv_bottom; 
965             dri_bo_reference(gen6_avc_surface->dmv_top);
966             dri_bo_reference(gen6_avc_surface->dmv_bottom);
967         } else {
968             break;
969         }
970     }
971         
972     obj_surface = SURFACE(encoder_context->input_yuv_surface);
973     assert(obj_surface && obj_surface->bo);
974     mfc_context->uncompressed_picture_source.bo = obj_surface->bo;
975     dri_bo_reference(mfc_context->uncompressed_picture_source.bo);
976
977     obj_buffer = BUFFER (pPicParameter->coded_buf); /* FIXME: fix this later */
978     bo = obj_buffer->buffer_store->bo;
979     assert(bo);
980     mfc_context->mfc_indirect_pak_bse_object.bo = bo;
981     mfc_context->mfc_indirect_pak_bse_object.offset = ALIGN(sizeof(VACodedBufferSegment), 64);
982     mfc_context->mfc_indirect_pak_bse_object.end_offset = ALIGN (obj_buffer->size_element - 0x1000, 0x1000);
983     dri_bo_reference(mfc_context->mfc_indirect_pak_bse_object.bo);
984
985     /*Programing bit rate control */
986     if ( mfc_context->bit_rate_control_context[0].MaxSizeInWord == 0 )
987         gen6_mfc_bit_rate_control_context_init(encode_state, mfc_context);
988
989     /*Programing HRD control */
990     if ( (rate_control_mode == VA_RC_CBR) && (mfc_context->vui_hrd.i_cpb_size_value == 0) )
991         gen6_mfc_hrd_context_init(encode_state, encoder_context);
992
993     return vaStatus;
994 }
995
996 static VAStatus gen6_mfc_run(VADriverContextP ctx, 
997                              struct encode_state *encode_state,
998                              struct intel_encoder_context *encoder_context)
999 {
1000     struct intel_batchbuffer *batch = encoder_context->base.batch;
1001
1002     intel_batchbuffer_flush(batch);             //run the pipeline
1003
1004     return VA_STATUS_SUCCESS;
1005 }
1006
1007 static VAStatus
1008 gen6_mfc_stop(VADriverContextP ctx, 
1009               struct encode_state *encode_state,
1010               struct intel_encoder_context *encoder_context,
1011               int *encoded_bits_size)
1012 {
1013     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1014     unsigned int *status_mem;
1015     unsigned int buffer_size_bits = 0;
1016     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1017     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1018     int i;
1019
1020     dri_bo_map(mfc_context->macroblock_status_buffer.bo, 1);
1021     status_mem = (unsigned int *)mfc_context->macroblock_status_buffer.bo->virtual;
1022     //Detecting encoder buffer size and bit rate control result
1023     for(i = 0; i < width_in_mbs * height_in_mbs; i++) {
1024         unsigned short current_mb = status_mem[1] >> 16;
1025         buffer_size_bits += current_mb;
1026         status_mem += 4;
1027     }    
1028     dri_bo_unmap(mfc_context->macroblock_status_buffer.bo);
1029
1030     *encoded_bits_size = buffer_size_bits;
1031     if ( buffer_size_bits == 0) {       // FIXME: we can't get info in IVB.
1032          struct i965_driver_data *i965 = i965_driver_data(ctx);
1033          struct object_buffer *obj_buffer;
1034          VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1035          obj_buffer = BUFFER (pPicParameter->coded_buf);
1036          dri_bo_map(obj_buffer->buffer_store->bo, 1);
1037          unsigned char *coded_mem = (unsigned char *)(obj_buffer->buffer_store->bo->virtual) + ALIGN(sizeof(VACodedBufferSegment), 64); 
1038          for(i = 0; i < obj_buffer->size_element - ALIGN(sizeof(VACodedBufferSegment), 64) - 3 - 0x1000; i++) {
1039                if (!coded_mem[i] &&
1040                     !coded_mem[i + 1] &&
1041                     !coded_mem[i + 2] &&
1042                     !coded_mem[i + 3] &&
1043                     !coded_mem[i + 4])
1044                     break;      
1045          }
1046          dri_bo_unmap(obj_buffer->buffer_store->bo);
1047          *encoded_bits_size = i*8;
1048     }
1049
1050     return VA_STATUS_SUCCESS;
1051 }
1052
1053 #if __SOFTWARE__
1054
1055 static int
1056 gen6_mfc_avc_pak_object_intra(VADriverContextP ctx, int x, int y, int end_mb, int qp,unsigned int *msg,
1057                               struct intel_encoder_context *encoder_context,
1058                               unsigned char target_mb_size, unsigned char max_mb_size,
1059                               struct intel_batchbuffer *batch)
1060 {
1061     int len_in_dwords = 11;
1062
1063     if (batch == NULL)
1064         batch = encoder_context->base.batch;
1065
1066     BEGIN_BCS_BATCH(batch, len_in_dwords);
1067
1068     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1069     OUT_BCS_BATCH(batch, 0);
1070     OUT_BCS_BATCH(batch, 0);
1071     OUT_BCS_BATCH(batch, 
1072                   (0 << 24) |           /* PackedMvNum, Debug*/
1073                   (0 << 20) |           /* No motion vector */
1074                   (1 << 19) |           /* CbpDcY */
1075                   (1 << 18) |           /* CbpDcU */
1076                   (1 << 17) |           /* CbpDcV */
1077                   (msg[0] & 0xFFFF) );
1078
1079     OUT_BCS_BATCH(batch, (0xFFFF << 16) | (y << 8) | x);                /* Code Block Pattern for Y*/
1080     OUT_BCS_BATCH(batch, 0x000F000F);                                                   /* Code Block Pattern */                
1081     OUT_BCS_BATCH(batch, (0 << 27) | (end_mb << 26) | qp);      /* Last MB */
1082
1083     /*Stuff for Intra MB*/
1084     OUT_BCS_BATCH(batch, msg[1]);                       /* We using Intra16x16 no 4x4 predmode*/        
1085     OUT_BCS_BATCH(batch, msg[2]);       
1086     OUT_BCS_BATCH(batch, msg[3]&0xFC);          
1087     
1088     /*MaxSizeInWord and TargetSzieInWord*/
1089     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1090                   (target_mb_size << 16) );
1091
1092     ADVANCE_BCS_BATCH(batch);
1093
1094     return len_in_dwords;
1095 }
1096
1097 static int
1098 gen6_mfc_avc_pak_object_inter(VADriverContextP ctx, int x, int y, int end_mb, int qp,
1099                               unsigned int *msg, unsigned int offset,
1100                               struct intel_encoder_context *encoder_context,
1101                               unsigned char target_mb_size,unsigned char max_mb_size, int slice_type,
1102                               struct intel_batchbuffer *batch)
1103 {
1104     int len_in_dwords = 11;
1105
1106     if (batch == NULL)
1107         batch = encoder_context->base.batch;
1108
1109     BEGIN_BCS_BATCH(batch, len_in_dwords);
1110
1111     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1112
1113     OUT_BCS_BATCH(batch, msg[2]);         /* 32 MV*/
1114     OUT_BCS_BATCH(batch, offset);
1115
1116     OUT_BCS_BATCH(batch, msg[0]);
1117
1118     OUT_BCS_BATCH(batch, (0xFFFF<<16) | (y << 8) | x);        /* Code Block Pattern for Y*/
1119     OUT_BCS_BATCH(batch, 0x000F000F);                         /* Code Block Pattern */  
1120 #if 0 
1121     if ( slice_type == SLICE_TYPE_B) {
1122         OUT_BCS_BATCH(batch, (0xF<<28) | (end_mb << 26) | qp);  /* Last MB */
1123     } else {
1124         OUT_BCS_BATCH(batch, (end_mb << 26) | qp);      /* Last MB */
1125     }
1126 #else
1127     OUT_BCS_BATCH(batch, (end_mb << 26) | qp);  /* Last MB */
1128 #endif
1129
1130
1131     /*Stuff for Inter MB*/
1132     OUT_BCS_BATCH(batch, msg[1]);        
1133     OUT_BCS_BATCH(batch, 0x0);    
1134     OUT_BCS_BATCH(batch, 0x0);        
1135
1136     /*MaxSizeInWord and TargetSzieInWord*/
1137     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1138                   (target_mb_size << 16) );
1139
1140     ADVANCE_BCS_BATCH(batch);
1141
1142     return len_in_dwords;
1143 }
1144
1145 static void 
1146 gen6_mfc_avc_pipeline_slice_programing(VADriverContextP ctx,
1147                                        struct encode_state *encode_state,
1148                                        struct intel_encoder_context *encoder_context,
1149                                        int slice_index,
1150                                        struct intel_batchbuffer *slice_batch)
1151 {
1152     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1153     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1154     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1155     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1156     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1157     unsigned int *msg = NULL, offset = 0;
1158     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
1159     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1160     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1161     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1162     int i,x,y;
1163     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1164     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1165     unsigned char *slice_header = NULL;
1166     int slice_header_length_in_bits = 0;
1167     unsigned int tail_data[] = { 0x0, 0x0 };
1168
1169     gen6_mfc_avc_slice_state(ctx, 
1170                              pPicParameter,
1171                              pSliceParameter,
1172                              encode_state, encoder_context,
1173                              (rate_control_mode == VA_RC_CBR), qp, slice_batch);
1174
1175     if ( slice_index == 0) 
1176         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1177
1178     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1179
1180     // slice hander
1181     mfc_context->insert_object(ctx, encoder_context,
1182                                (unsigned int *)slice_header, ALIGN(slice_header_length_in_bits, 32) >> 5, slice_header_length_in_bits & 0x1f,
1183                                5,  /* first 5 bytes are start code + nal unit type */
1184                                1, 0, 1, slice_batch);
1185
1186     if ( rate_control_mode == VA_RC_CBR) {
1187         qp = mfc_context->bit_rate_control_context[1-is_intra].QpPrimeY;
1188     }
1189
1190     dri_bo_map(vme_context->vme_output.bo , 1);
1191     msg = (unsigned int *)vme_context->vme_output.bo->virtual;
1192
1193     if (is_intra) {
1194         msg += pSliceParameter->macroblock_address * INTRA_VME_OUTPUT_IN_DWS;
1195     } else {
1196         msg += pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_DWS;
1197         msg += 32; /* the first 32 DWs are MVs */
1198         offset = pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_BYTES;
1199     }
1200    
1201     for (i = pSliceParameter->macroblock_address; 
1202          i < pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks; i++) {
1203         int last_mb = (i == (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks - 1) );
1204         x = i % width_in_mbs;
1205         y = i / width_in_mbs;
1206
1207         if (is_intra) {
1208             assert(msg);
1209             gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
1210             msg += INTRA_VME_OUTPUT_IN_DWS;
1211         } else {
1212             gen6_mfc_avc_pak_object_inter(ctx, x, y, last_mb, qp, msg, offset, encoder_context, 0, 0, pSliceParameter->slice_type, slice_batch);
1213             msg += INTER_VME_OUTPUT_IN_DWS;
1214             offset += INTER_VME_OUTPUT_IN_BYTES;
1215         }
1216     }
1217    
1218     dri_bo_unmap(vme_context->vme_output.bo);
1219
1220     if ( last_slice ) {    
1221         mfc_context->insert_object(ctx, encoder_context,
1222                                    tail_data, 2, 8,
1223                                    2, 1, 1, 0, slice_batch);
1224     } else {
1225         mfc_context->insert_object(ctx, encoder_context,
1226                                    tail_data, 1, 8,
1227                                    1, 1, 1, 0, slice_batch);
1228     }
1229
1230     free(slice_header);
1231
1232 }
1233
1234 static dri_bo *
1235 gen6_mfc_avc_software_batchbuffer(VADriverContextP ctx,
1236                                   struct encode_state *encode_state,
1237                                   struct intel_encoder_context *encoder_context)
1238 {
1239     struct i965_driver_data *i965 = i965_driver_data(ctx);
1240     struct intel_batchbuffer *batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD);
1241     dri_bo *batch_bo = batch->buffer;
1242     int i;
1243
1244     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1245         gen6_mfc_avc_pipeline_slice_programing(ctx, encode_state, encoder_context, i, batch);
1246     }
1247
1248     intel_batchbuffer_align(batch, 8);
1249     
1250     BEGIN_BCS_BATCH(batch, 2);
1251     OUT_BCS_BATCH(batch, 0);
1252     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_END);
1253     ADVANCE_BCS_BATCH(batch);
1254
1255     dri_bo_reference(batch_bo);
1256     intel_batchbuffer_free(batch);
1257
1258     return batch_bo;
1259 }
1260
1261 #else
1262
1263 static void
1264 gen6_mfc_batchbuffer_surfaces_input(VADriverContextP ctx,
1265                                     struct encode_state *encode_state,
1266                                     struct intel_encoder_context *encoder_context)
1267
1268 {
1269     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1270     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1271
1272     assert(vme_context->vme_output.bo);
1273     mfc_context->buffer_suface_setup(ctx,
1274                                      &mfc_context->gpe_context,
1275                                      &vme_context->vme_output,
1276                                      BINDING_TABLE_OFFSET(BIND_IDX_VME_OUTPUT),
1277                                      SURFACE_STATE_OFFSET(BIND_IDX_VME_OUTPUT));
1278     assert(mfc_context->aux_batchbuffer_surface.bo);
1279     mfc_context->buffer_suface_setup(ctx,
1280                                      &mfc_context->gpe_context,
1281                                      &mfc_context->aux_batchbuffer_surface,
1282                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_SLICE_HEADER),
1283                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_SLICE_HEADER));
1284 }
1285
1286 static void
1287 gen6_mfc_batchbuffer_surfaces_output(VADriverContextP ctx,
1288                                      struct encode_state *encode_state,
1289                                      struct intel_encoder_context *encoder_context)
1290
1291 {
1292     struct i965_driver_data *i965 = i965_driver_data(ctx);
1293     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1294     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1295     int width_in_mbs = pSequenceParameter->picture_width_in_mbs;
1296     int height_in_mbs = pSequenceParameter->picture_height_in_mbs;
1297     mfc_context->mfc_batchbuffer_surface.num_blocks = width_in_mbs * height_in_mbs + encode_state->num_slice_params_ext * 8 + 1;
1298     mfc_context->mfc_batchbuffer_surface.size_block = 16 * CMD_LEN_IN_OWORD; /* 3 OWORDs */
1299     mfc_context->mfc_batchbuffer_surface.pitch = 16;
1300     mfc_context->mfc_batchbuffer_surface.bo = dri_bo_alloc(i965->intel.bufmgr, 
1301                                                            "MFC batchbuffer",
1302                                                            mfc_context->mfc_batchbuffer_surface.num_blocks * mfc_context->mfc_batchbuffer_surface.size_block,
1303                                                            0x1000);
1304     mfc_context->buffer_suface_setup(ctx,
1305                                      &mfc_context->gpe_context,
1306                                      &mfc_context->mfc_batchbuffer_surface,
1307                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_BATCHBUFFER),
1308                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_BATCHBUFFER));
1309 }
1310
1311 static void
1312 gen6_mfc_batchbuffer_surfaces_setup(VADriverContextP ctx, 
1313                                     struct encode_state *encode_state,
1314                                     struct intel_encoder_context *encoder_context)
1315 {
1316     gen6_mfc_batchbuffer_surfaces_input(ctx, encode_state, encoder_context);
1317     gen6_mfc_batchbuffer_surfaces_output(ctx, encode_state, encoder_context);
1318 }
1319
1320 static void
1321 gen6_mfc_batchbuffer_idrt_setup(VADriverContextP ctx, 
1322                                 struct encode_state *encode_state,
1323                                 struct intel_encoder_context *encoder_context)
1324 {
1325     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1326     struct gen6_interface_descriptor_data *desc;   
1327     int i;
1328     dri_bo *bo;
1329
1330     bo = mfc_context->gpe_context.idrt.bo;
1331     dri_bo_map(bo, 1);
1332     assert(bo->virtual);
1333     desc = bo->virtual;
1334
1335     for (i = 0; i < mfc_context->gpe_context.num_kernels; i++) {
1336         struct i965_kernel *kernel;
1337
1338         kernel = &mfc_context->gpe_context.kernels[i];
1339         assert(sizeof(*desc) == 32);
1340
1341         /*Setup the descritor table*/
1342         memset(desc, 0, sizeof(*desc));
1343         desc->desc0.kernel_start_pointer = (kernel->bo->offset >> 6);
1344         desc->desc2.sampler_count = 0;
1345         desc->desc2.sampler_state_pointer = 0;
1346         desc->desc3.binding_table_entry_count = 2;
1347         desc->desc3.binding_table_pointer = (BINDING_TABLE_OFFSET(0) >> 5);
1348         desc->desc4.constant_urb_entry_read_offset = 0;
1349         desc->desc4.constant_urb_entry_read_length = 4;
1350                 
1351         /*kernel start*/
1352         dri_bo_emit_reloc(bo,   
1353                           I915_GEM_DOMAIN_INSTRUCTION, 0,
1354                           0,
1355                           i * sizeof(*desc) + offsetof(struct gen6_interface_descriptor_data, desc0),
1356                           kernel->bo);
1357         desc++;
1358     }
1359
1360     dri_bo_unmap(bo);
1361 }
1362
1363 static void
1364 gen6_mfc_batchbuffer_constant_setup(VADriverContextP ctx, 
1365                                     struct encode_state *encode_state,
1366                                     struct intel_encoder_context *encoder_context)
1367 {
1368     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1369     
1370     (void)mfc_context;
1371 }
1372
1373 static void
1374 gen6_mfc_batchbuffer_emit_object_command(struct intel_batchbuffer *batch,
1375                                          int index,
1376                                          int head_offset,
1377                                          int batchbuffer_offset,
1378                                          int head_size,
1379                                          int tail_size,
1380                                          int number_mb_cmds,
1381                                          int first_object,
1382                                          int last_object,
1383                                          int last_slice,
1384                                          int mb_x,
1385                                          int mb_y,
1386                                          int width_in_mbs,
1387                                          int qp)
1388 {
1389     BEGIN_BATCH(batch, 12);
1390     
1391     OUT_BATCH(batch, CMD_MEDIA_OBJECT | (12 - 2));
1392     OUT_BATCH(batch, index);
1393     OUT_BATCH(batch, 0);
1394     OUT_BATCH(batch, 0);
1395     OUT_BATCH(batch, 0);
1396     OUT_BATCH(batch, 0);
1397    
1398     /*inline data */
1399     OUT_BATCH(batch, head_offset);
1400     OUT_BATCH(batch, batchbuffer_offset);
1401     OUT_BATCH(batch, 
1402               head_size << 16 |
1403               tail_size);
1404     OUT_BATCH(batch,
1405               number_mb_cmds << 16 |
1406               first_object << 2 |
1407               last_object << 1 |
1408               last_slice);
1409     OUT_BATCH(batch,
1410               mb_y << 8 |
1411               mb_x);
1412     OUT_BATCH(batch,
1413               qp << 16 |
1414               width_in_mbs);
1415
1416     ADVANCE_BATCH(batch);
1417 }
1418
1419 static void
1420 gen6_mfc_avc_batchbuffer_slice_command(VADriverContextP ctx,
1421                                        struct intel_encoder_context *encoder_context,
1422                                        VAEncSliceParameterBufferH264 *slice_param,
1423                                        int head_offset,
1424                                        unsigned short head_size,
1425                                        unsigned short tail_size,
1426                                        int batchbuffer_offset,
1427                                        int qp,
1428                                        int last_slice)
1429 {
1430     struct intel_batchbuffer *batch = encoder_context->base.batch;
1431     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1432     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1433     int total_mbs = slice_param->num_macroblocks;
1434     int number_mb_cmds = 128;
1435     int starting_mb = 0;
1436     int last_object = 0;
1437     int first_object = 1;
1438     int i;
1439     int mb_x, mb_y;
1440     int index = (slice_param->slice_type == SLICE_TYPE_I) ? MFC_BATCHBUFFER_AVC_INTRA : MFC_BATCHBUFFER_AVC_INTER;
1441
1442     for (i = 0; i < total_mbs / number_mb_cmds; i++) {
1443         last_object = (total_mbs - starting_mb) == number_mb_cmds;
1444         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1445         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1446         assert(mb_x <= 255 && mb_y <= 255);
1447
1448         starting_mb += number_mb_cmds;
1449
1450         gen6_mfc_batchbuffer_emit_object_command(batch,
1451                                                  index,
1452                                                  head_offset,
1453                                                  batchbuffer_offset,
1454                                                  head_size,
1455                                                  tail_size,
1456                                                  number_mb_cmds,
1457                                                  first_object,
1458                                                  last_object,
1459                                                  last_slice,
1460                                                  mb_x,
1461                                                  mb_y,
1462                                                  width_in_mbs,
1463                                                  qp);
1464
1465         if (first_object) {
1466             head_offset += head_size;
1467             batchbuffer_offset += head_size;
1468         }
1469
1470         if (last_object) {
1471             head_offset += tail_size;
1472             batchbuffer_offset += tail_size;
1473         }
1474
1475         batchbuffer_offset += number_mb_cmds * CMD_LEN_IN_OWORD;
1476
1477         first_object = 0;
1478     }
1479
1480     if (!last_object) {
1481         last_object = 1;
1482         number_mb_cmds = total_mbs % number_mb_cmds;
1483         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1484         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1485         assert(mb_x <= 255 && mb_y <= 255);
1486         starting_mb += number_mb_cmds;
1487
1488         gen6_mfc_batchbuffer_emit_object_command(batch,
1489                                                  index,
1490                                                  head_offset,
1491                                                  batchbuffer_offset,
1492                                                  head_size,
1493                                                  tail_size,
1494                                                  number_mb_cmds,
1495                                                  first_object,
1496                                                  last_object,
1497                                                  last_slice,
1498                                                  mb_x,
1499                                                  mb_y,
1500                                                  width_in_mbs,
1501                                                  qp);
1502     }
1503 }
1504                           
1505 /*
1506  * return size in Owords (16bytes)
1507  */         
1508 static int
1509 gen6_mfc_avc_batchbuffer_slice(VADriverContextP ctx,
1510                                struct encode_state *encode_state,
1511                                struct intel_encoder_context *encoder_context,
1512                                int slice_index,
1513                                int batchbuffer_offset)
1514 {
1515     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1516     struct intel_batchbuffer *slice_batch = mfc_context->aux_batchbuffer;
1517     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1518     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1519     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1520     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
1521     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1522     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1523     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1524     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1525     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1526     unsigned char *slice_header = NULL;
1527     int slice_header_length_in_bits = 0;
1528     unsigned int tail_data[] = { 0x0, 0x0 };
1529     long head_offset;
1530     int old_used = intel_batchbuffer_used_size(slice_batch), used;
1531     unsigned short head_size, tail_size;
1532
1533     head_offset = old_used / 16;
1534     gen6_mfc_avc_slice_state(ctx,
1535                              pPicParameter,
1536                              pSliceParameter,
1537                              encode_state,
1538                              encoder_context,
1539                              (rate_control_mode == VA_RC_CBR),
1540                              qp,
1541                              slice_batch);
1542
1543     if (slice_index == 0)
1544         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1545
1546     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1547
1548     // slice hander
1549     mfc_context->insert_object(ctx,
1550                                encoder_context,
1551                                (unsigned int *)slice_header,
1552                                ALIGN(slice_header_length_in_bits, 32) >> 5,
1553                                slice_header_length_in_bits & 0x1f,
1554                                5,  /* first 5 bytes are start code + nal unit type */
1555                                1,
1556                                0,
1557                                1,
1558                                slice_batch);
1559     free(slice_header);
1560
1561     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1562     used = intel_batchbuffer_used_size(slice_batch);
1563     head_size = (used - old_used) / 16;
1564     old_used = used;
1565
1566     if (rate_control_mode == VA_RC_CBR) {
1567         qp = mfc_context->bit_rate_control_context[1 - is_intra].QpPrimeY;
1568     }
1569
1570     /* tail */
1571     if (last_slice) {    
1572         mfc_context->insert_object(ctx,
1573                                    encoder_context,
1574                                    tail_data,
1575                                    2,
1576                                    8,
1577                                    2,
1578                                    1,
1579                                    1,
1580                                    0,
1581                                    slice_batch);
1582     } else {
1583         mfc_context->insert_object(ctx,
1584                                    encoder_context,
1585                                    tail_data,
1586                                    1,
1587                                    8,
1588                                    1,
1589                                    1,
1590                                    1,
1591                                    0,
1592                                    slice_batch);
1593     }
1594
1595     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1596     used = intel_batchbuffer_used_size(slice_batch);
1597     tail_size = (used - old_used) / 16;
1598
1599    
1600     gen6_mfc_avc_batchbuffer_slice_command(ctx,
1601                                            encoder_context,
1602                                            pSliceParameter,
1603                                            head_offset,
1604                                            head_size,
1605                                            tail_size,
1606                                            batchbuffer_offset,
1607                                            qp,
1608                                            last_slice);
1609
1610     return head_size + tail_size + pSliceParameter->num_macroblocks * CMD_LEN_IN_OWORD;
1611 }
1612
1613 static void
1614 gen6_mfc_avc_batchbuffer_pipeline(VADriverContextP ctx,
1615                                   struct encode_state *encode_state,
1616                                   struct intel_encoder_context *encoder_context)
1617 {
1618     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1619     struct intel_batchbuffer *batch = encoder_context->base.batch;
1620     int i, size, offset = 0;
1621     intel_batchbuffer_start_atomic(batch, 0x4000); 
1622     gen6_gpe_pipeline_setup(ctx, &mfc_context->gpe_context, batch);
1623
1624     for ( i = 0; i < encode_state->num_slice_params_ext; i++) {
1625         size = gen6_mfc_avc_batchbuffer_slice(ctx, encode_state, encoder_context, i, offset);
1626         offset += size;
1627     }
1628
1629     intel_batchbuffer_end_atomic(batch);
1630     intel_batchbuffer_flush(batch);
1631 }
1632
1633 static void
1634 gen6_mfc_build_avc_batchbuffer(VADriverContextP ctx, 
1635                                struct encode_state *encode_state,
1636                                struct intel_encoder_context *encoder_context)
1637 {
1638     gen6_mfc_batchbuffer_surfaces_setup(ctx, encode_state, encoder_context);
1639     gen6_mfc_batchbuffer_idrt_setup(ctx, encode_state, encoder_context);
1640     gen6_mfc_batchbuffer_constant_setup(ctx, encode_state, encoder_context);
1641     gen6_mfc_avc_batchbuffer_pipeline(ctx, encode_state, encoder_context);
1642 }
1643
1644 static dri_bo *
1645 gen6_mfc_avc_hardware_batchbuffer(VADriverContextP ctx,
1646                                   struct encode_state *encode_state,
1647                                   struct intel_encoder_context *encoder_context)
1648 {
1649     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1650
1651     gen6_mfc_build_avc_batchbuffer(ctx, encode_state, encoder_context);
1652     dri_bo_reference(mfc_context->mfc_batchbuffer_surface.bo);
1653
1654     return mfc_context->mfc_batchbuffer_surface.bo;
1655 }
1656
1657 #endif
1658
1659 int interlace_check(VADriverContextP ctx,
1660                    struct encode_state *encode_state,
1661                    struct intel_encoder_context *encoder_context) {
1662     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1663     VAEncSliceParameterBufferH264 *pSliceParameter;
1664     int i;
1665     int mbCount = 0;
1666     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1667     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1668   
1669     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1670         pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[i]->buffer; 
1671         mbCount += pSliceParameter->num_macroblocks; 
1672     }
1673     
1674     if ( mbCount == ( width_in_mbs * height_in_mbs ) )
1675         return 0;
1676
1677     return 1;
1678 }
1679
1680
1681 static void
1682 gen6_mfc_avc_pipeline_programing(VADriverContextP ctx,
1683                                  struct encode_state *encode_state,
1684                                  struct intel_encoder_context *encoder_context)
1685 {
1686     struct intel_batchbuffer *batch = encoder_context->base.batch;
1687     dri_bo *slice_batch_bo;
1688
1689     if ( interlace_check(ctx, encode_state, encoder_context) ) {
1690         fprintf(stderr, "Current VA driver don't support interlace mode!\n");
1691         assert(0);
1692         return; 
1693     }
1694
1695 #if __SOFTWARE__
1696     slice_batch_bo = gen6_mfc_avc_software_batchbuffer(ctx, encode_state, encoder_context);
1697 #else
1698     slice_batch_bo = gen6_mfc_avc_hardware_batchbuffer(ctx, encode_state, encoder_context);
1699 #endif
1700
1701     // begin programing
1702     intel_batchbuffer_start_atomic_bcs(batch, 0x4000); 
1703     intel_batchbuffer_emit_mi_flush(batch);
1704     
1705     // picture level programing
1706     gen6_mfc_avc_pipeline_picture_programing(ctx, encode_state, encoder_context);
1707
1708     BEGIN_BCS_BATCH(batch, 2);
1709     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_START | (1 << 8));
1710     OUT_BCS_RELOC(batch,
1711                   slice_batch_bo,
1712                   I915_GEM_DOMAIN_COMMAND, 0, 
1713                   0);
1714     ADVANCE_BCS_BATCH(batch);
1715
1716     // end programing
1717     intel_batchbuffer_end_atomic(batch);
1718
1719     dri_bo_unreference(slice_batch_bo);
1720 }
1721
1722 static VAStatus
1723 gen6_mfc_avc_encode_picture(VADriverContextP ctx, 
1724                             struct encode_state *encode_state,
1725                             struct intel_encoder_context *encoder_context)
1726 {
1727     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1728     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1729     int MAX_CBR_INTERATE = 4;
1730     int current_frame_bits_size;
1731     int i;
1732  
1733     for(i = 0; i < MAX_CBR_INTERATE; i++) {
1734         gen6_mfc_init(ctx, encoder_context);
1735         gen6_mfc_avc_prepare(ctx, encode_state, encoder_context);
1736         /*Programing bcs pipeline*/
1737         gen6_mfc_avc_pipeline_programing(ctx, encode_state, encoder_context);   //filling the pipeline
1738         gen6_mfc_run(ctx, encode_state, encoder_context);
1739         if ( rate_control_mode == VA_RC_CBR) {
1740             gen6_mfc_stop(ctx, encode_state, encoder_context, &current_frame_bits_size);
1741             //gen6_mfc_hrd_context_check(encode_state, mfc_context);
1742             if ( gen6_mfc_bit_rate_control_context_update( encode_state, mfc_context, current_frame_bits_size) ) {
1743                 gen6_mfc_hrd_context_update(encode_state, mfc_context);
1744                 break;
1745             }
1746         } else {
1747             break;
1748         }
1749     }
1750
1751     return VA_STATUS_SUCCESS;
1752 }
1753
1754 VAStatus
1755 gen6_mfc_pipeline(VADriverContextP ctx,
1756                   VAProfile profile,
1757                   struct encode_state *encode_state,
1758                   struct intel_encoder_context *encoder_context)
1759 {
1760     VAStatus vaStatus;
1761
1762     switch (profile) {
1763     case VAProfileH264Baseline:
1764     case VAProfileH264Main:
1765     case VAProfileH264High:
1766         vaStatus = gen6_mfc_avc_encode_picture(ctx, encode_state, encoder_context);
1767         break;
1768
1769         /* FIXME: add for other profile */
1770     default:
1771         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1772         break;
1773     }
1774
1775     return vaStatus;
1776 }
1777
1778 void
1779 gen6_mfc_context_destroy(void *context)
1780 {
1781     struct gen6_mfc_context *mfc_context = context;
1782     int i;
1783
1784     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
1785     mfc_context->post_deblocking_output.bo = NULL;
1786
1787     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
1788     mfc_context->pre_deblocking_output.bo = NULL;
1789
1790     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
1791     mfc_context->uncompressed_picture_source.bo = NULL;
1792
1793     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
1794     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
1795
1796     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
1797         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
1798         mfc_context->direct_mv_buffers[i].bo = NULL;
1799     }
1800
1801     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
1802     mfc_context->intra_row_store_scratch_buffer.bo = NULL;
1803
1804     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
1805     mfc_context->macroblock_status_buffer.bo = NULL;
1806
1807     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
1808     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = NULL;
1809
1810     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
1811     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = NULL;
1812
1813
1814     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
1815         dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
1816         mfc_context->reference_surfaces[i].bo = NULL;  
1817     }
1818
1819     i965_gpe_context_destroy(&mfc_context->gpe_context);
1820
1821     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
1822     mfc_context->mfc_batchbuffer_surface.bo = NULL;
1823
1824     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
1825     mfc_context->aux_batchbuffer_surface.bo = NULL;
1826
1827     if (mfc_context->aux_batchbuffer)
1828         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
1829
1830     mfc_context->aux_batchbuffer = NULL;
1831
1832     free(mfc_context);
1833 }
1834
1835 Bool gen6_mfc_context_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
1836 {
1837     struct gen6_mfc_context *mfc_context = calloc(1, sizeof(struct gen6_mfc_context));
1838
1839     mfc_context->gpe_context.surface_state_binding_table.length = (SURFACE_STATE_PADDED_SIZE + sizeof(unsigned int)) * MAX_MEDIA_SURFACES_GEN6;
1840
1841     mfc_context->gpe_context.idrt.max_entries = MAX_GPE_KERNELS;
1842     mfc_context->gpe_context.idrt.entry_size = sizeof(struct gen6_interface_descriptor_data);
1843
1844     mfc_context->gpe_context.curbe.length = 32 * 4;
1845
1846     mfc_context->gpe_context.vfe_state.max_num_threads = 60 - 1;
1847     mfc_context->gpe_context.vfe_state.num_urb_entries = 16;
1848     mfc_context->gpe_context.vfe_state.gpgpu_mode = 0;
1849     mfc_context->gpe_context.vfe_state.urb_entry_size = 59 - 1;
1850     mfc_context->gpe_context.vfe_state.curbe_allocation_size = 37 - 1;
1851
1852     i965_gpe_load_kernels(ctx,
1853                           &mfc_context->gpe_context,
1854                           gen6_mfc_kernels,
1855                           NUM_MFC_KERNEL);
1856
1857     mfc_context->pipe_mode_select = gen6_mfc_pipe_mode_select;
1858     mfc_context->set_surface_state = gen6_mfc_surface_state;
1859     mfc_context->ind_obj_base_addr_state = gen6_mfc_ind_obj_base_addr_state;
1860     mfc_context->avc_img_state = gen6_mfc_avc_img_state;
1861     mfc_context->avc_qm_state = gen6_mfc_avc_qm_state;
1862     mfc_context->avc_fqm_state = gen6_mfc_avc_fqm_state;
1863     mfc_context->insert_object = gen6_mfc_avc_insert_object;
1864     mfc_context->buffer_suface_setup = i965_gpe_buffer_suface_setup;
1865
1866     encoder_context->mfc_context = mfc_context;
1867     encoder_context->mfc_context_destroy = gen6_mfc_context_destroy;
1868     encoder_context->mfc_pipeline = gen6_mfc_pipeline;
1869
1870     return True;
1871 }