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