Fix coded buffer size calculating for CBR mode
[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     VACodedBufferSegment *coded_buffer_segment;
862     unsigned char *flag = NULL;
863
864     for (j = 0; j < encode_state->num_slice_params_ext && enable_avc_ildb == 0; j++) {
865         assert(encode_state->slice_params_ext && encode_state->slice_params_ext[j]->buffer);
866         slice_param = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[j]->buffer;
867
868         for (i = 0; i < encode_state->slice_params_ext[j]->num_elements; i++) {
869             assert((slice_param->slice_type == SLICE_TYPE_I) ||
870                    (slice_param->slice_type == SLICE_TYPE_SI) ||
871                    (slice_param->slice_type == SLICE_TYPE_P) ||
872                    (slice_param->slice_type == SLICE_TYPE_SP) ||
873                    (slice_param->slice_type == SLICE_TYPE_B));
874
875             if (slice_param->disable_deblocking_filter_idc != 1) {
876                 enable_avc_ildb = 1;
877                 break;
878             }
879
880             slice_param++;
881         }
882     }
883
884     /*Setup all the input&output object*/
885
886     /* Setup current frame and current direct mv buffer*/
887     obj_surface = SURFACE(pPicParameter->CurrPic.picture_id);
888     assert(obj_surface);
889     i965_check_alloc_surface_bo(ctx, obj_surface, 1, VA_FOURCC('N','V','1','2'), SUBSAMPLE_YUV420);
890
891     if ( obj_surface->private_data == NULL) {
892         gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
893         gen6_avc_surface->dmv_top = 
894             dri_bo_alloc(i965->intel.bufmgr,
895                          "Buffer",
896                          68*8192, 
897                          64);
898         gen6_avc_surface->dmv_bottom = 
899             dri_bo_alloc(i965->intel.bufmgr,
900                          "Buffer",
901                          68*8192, 
902                          64);
903         assert(gen6_avc_surface->dmv_top);
904         assert(gen6_avc_surface->dmv_bottom);
905         obj_surface->private_data = (void *)gen6_avc_surface;
906         obj_surface->free_private_data = (void *)gen6_mfc_free_avc_surface; 
907     }
908     gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
909     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 2].bo = gen6_avc_surface->dmv_top;
910     mfc_context->direct_mv_buffers[NUM_MFC_DMV_BUFFERS - 1].bo = gen6_avc_surface->dmv_bottom;
911     dri_bo_reference(gen6_avc_surface->dmv_top);
912     dri_bo_reference(gen6_avc_surface->dmv_bottom);
913
914     if (enable_avc_ildb) {
915         mfc_context->post_deblocking_output.bo = obj_surface->bo;
916         dri_bo_reference(mfc_context->post_deblocking_output.bo);
917     } else {
918         mfc_context->pre_deblocking_output.bo = obj_surface->bo;
919         dri_bo_reference(mfc_context->pre_deblocking_output.bo);
920     }
921
922     mfc_context->surface_state.width = obj_surface->orig_width;
923     mfc_context->surface_state.height = obj_surface->orig_height;
924     mfc_context->surface_state.w_pitch = obj_surface->width;
925     mfc_context->surface_state.h_pitch = obj_surface->height;
926     
927     /* Setup reference frames and direct mv buffers*/
928     for(i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++) {
929         if ( pPicParameter->ReferenceFrames[i].picture_id != VA_INVALID_ID ) { 
930             obj_surface = SURFACE(pPicParameter->ReferenceFrames[i].picture_id);
931             assert(obj_surface);
932             if (obj_surface->bo != NULL) {
933                 mfc_context->reference_surfaces[i].bo = obj_surface->bo;
934                 dri_bo_reference(obj_surface->bo);
935             }
936             /* Check DMV buffer */
937             if ( obj_surface->private_data == NULL) {
938                 
939                 gen6_avc_surface = calloc(sizeof(struct gen6_mfc_avc_surface_aux), 1);
940                 gen6_avc_surface->dmv_top = 
941                     dri_bo_alloc(i965->intel.bufmgr,
942                                  "Buffer",
943                                  68*8192, 
944                                  64);
945                 gen6_avc_surface->dmv_bottom = 
946                     dri_bo_alloc(i965->intel.bufmgr,
947                                  "Buffer",
948                                  68*8192, 
949                                  64);
950                 assert(gen6_avc_surface->dmv_top);
951                 assert(gen6_avc_surface->dmv_bottom);
952                 obj_surface->private_data = gen6_avc_surface;
953                 obj_surface->free_private_data = gen6_mfc_free_avc_surface; 
954             }
955     
956             gen6_avc_surface = (struct gen6_mfc_avc_surface_aux*) obj_surface->private_data;
957             /* Setup DMV buffer */
958             mfc_context->direct_mv_buffers[i*2].bo = gen6_avc_surface->dmv_top;
959             mfc_context->direct_mv_buffers[i*2+1].bo = gen6_avc_surface->dmv_bottom; 
960             dri_bo_reference(gen6_avc_surface->dmv_top);
961             dri_bo_reference(gen6_avc_surface->dmv_bottom);
962         } else {
963             break;
964         }
965     }
966         
967     obj_surface = SURFACE(encoder_context->input_yuv_surface);
968     assert(obj_surface && obj_surface->bo);
969     mfc_context->uncompressed_picture_source.bo = obj_surface->bo;
970     dri_bo_reference(mfc_context->uncompressed_picture_source.bo);
971
972     obj_buffer = BUFFER (pPicParameter->coded_buf); /* FIXME: fix this later */
973     bo = obj_buffer->buffer_store->bo;
974     assert(bo);
975     mfc_context->mfc_indirect_pak_bse_object.bo = bo;
976     mfc_context->mfc_indirect_pak_bse_object.offset = I965_CODEDBUFFER_SIZE;
977     mfc_context->mfc_indirect_pak_bse_object.end_offset = ALIGN(obj_buffer->size_element - 0x1000, 0x1000);
978     dri_bo_reference(mfc_context->mfc_indirect_pak_bse_object.bo);
979     
980     dri_bo_map(bo, 1);
981     coded_buffer_segment = (VACodedBufferSegment *)bo->virtual;
982     flag = (unsigned char *)(coded_buffer_segment + 1);
983     *flag = 0;
984     dri_bo_unmap(bo);
985
986     /*Programing bit rate control */
987     if ( mfc_context->bit_rate_control_context[0].MaxSizeInWord == 0 )
988         gen6_mfc_bit_rate_control_context_init(encode_state, mfc_context);
989
990     /*Programing HRD control */
991     if ( (rate_control_mode == VA_RC_CBR) && (mfc_context->vui_hrd.i_cpb_size_value == 0) )
992         gen6_mfc_hrd_context_init(encode_state, encoder_context);
993
994     return vaStatus;
995 }
996
997 static VAStatus gen6_mfc_run(VADriverContextP ctx, 
998                              struct encode_state *encode_state,
999                              struct intel_encoder_context *encoder_context)
1000 {
1001     struct intel_batchbuffer *batch = encoder_context->base.batch;
1002
1003     intel_batchbuffer_flush(batch);             //run the pipeline
1004
1005     return VA_STATUS_SUCCESS;
1006 }
1007
1008 extern VAStatus 
1009 i965_MapBuffer(VADriverContextP ctx, 
1010                VABufferID buf_id,       /* in */
1011                void **pbuf);            /* out */
1012 extern VAStatus
1013 i965_UnmapBuffer(VADriverContextP ctx,
1014                  VABufferID buf_id);
1015
1016 static VAStatus
1017 gen6_mfc_stop(VADriverContextP ctx, 
1018               struct encode_state *encode_state,
1019               struct intel_encoder_context *encoder_context,
1020               int *encoded_bits_size)
1021 {
1022     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1023     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1024     VACodedBufferSegment *coded_buffer_segment;
1025     
1026     vaStatus = i965_MapBuffer(ctx, pPicParameter->coded_buf, (void **)&coded_buffer_segment);
1027     assert(vaStatus == VA_STATUS_SUCCESS);
1028     *encoded_bits_size = coded_buffer_segment->size * 8;
1029     i965_UnmapBuffer(ctx, pPicParameter->coded_buf);
1030
1031     return VA_STATUS_SUCCESS;
1032 }
1033
1034 #if __SOFTWARE__
1035
1036 static int
1037 gen6_mfc_avc_pak_object_intra(VADriverContextP ctx, int x, int y, int end_mb, int qp,unsigned int *msg,
1038                               struct intel_encoder_context *encoder_context,
1039                               unsigned char target_mb_size, unsigned char max_mb_size,
1040                               struct intel_batchbuffer *batch)
1041 {
1042     int len_in_dwords = 11;
1043
1044     if (batch == NULL)
1045         batch = encoder_context->base.batch;
1046
1047     BEGIN_BCS_BATCH(batch, len_in_dwords);
1048
1049     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1050     OUT_BCS_BATCH(batch, 0);
1051     OUT_BCS_BATCH(batch, 0);
1052     OUT_BCS_BATCH(batch, 
1053                   (0 << 24) |           /* PackedMvNum, Debug*/
1054                   (0 << 20) |           /* No motion vector */
1055                   (1 << 19) |           /* CbpDcY */
1056                   (1 << 18) |           /* CbpDcU */
1057                   (1 << 17) |           /* CbpDcV */
1058                   (msg[0] & 0xFFFF) );
1059
1060     OUT_BCS_BATCH(batch, (0xFFFF << 16) | (y << 8) | x);                /* Code Block Pattern for Y*/
1061     OUT_BCS_BATCH(batch, 0x000F000F);                                                   /* Code Block Pattern */                
1062     OUT_BCS_BATCH(batch, (0 << 27) | (end_mb << 26) | qp);      /* Last MB */
1063
1064     /*Stuff for Intra MB*/
1065     OUT_BCS_BATCH(batch, msg[1]);                       /* We using Intra16x16 no 4x4 predmode*/        
1066     OUT_BCS_BATCH(batch, msg[2]);       
1067     OUT_BCS_BATCH(batch, msg[3]&0xFC);          
1068     
1069     /*MaxSizeInWord and TargetSzieInWord*/
1070     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1071                   (target_mb_size << 16) );
1072
1073     ADVANCE_BCS_BATCH(batch);
1074
1075     return len_in_dwords;
1076 }
1077
1078 static int
1079 gen6_mfc_avc_pak_object_inter(VADriverContextP ctx, int x, int y, int end_mb, int qp,
1080                               unsigned int *msg, unsigned int offset,
1081                               struct intel_encoder_context *encoder_context,
1082                               unsigned char target_mb_size,unsigned char max_mb_size, int slice_type,
1083                               struct intel_batchbuffer *batch)
1084 {
1085     int len_in_dwords = 11;
1086
1087     if (batch == NULL)
1088         batch = encoder_context->base.batch;
1089
1090     BEGIN_BCS_BATCH(batch, len_in_dwords);
1091
1092     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
1093
1094     OUT_BCS_BATCH(batch, msg[2]);         /* 32 MV*/
1095     OUT_BCS_BATCH(batch, offset);
1096
1097     OUT_BCS_BATCH(batch, msg[0]);
1098
1099     OUT_BCS_BATCH(batch, (0xFFFF<<16) | (y << 8) | x);        /* Code Block Pattern for Y*/
1100     OUT_BCS_BATCH(batch, 0x000F000F);                         /* Code Block Pattern */  
1101 #if 0 
1102     if ( slice_type == SLICE_TYPE_B) {
1103         OUT_BCS_BATCH(batch, (0xF<<28) | (end_mb << 26) | qp);  /* Last MB */
1104     } else {
1105         OUT_BCS_BATCH(batch, (end_mb << 26) | qp);      /* Last MB */
1106     }
1107 #else
1108     OUT_BCS_BATCH(batch, (end_mb << 26) | qp);  /* Last MB */
1109 #endif
1110
1111
1112     /*Stuff for Inter MB*/
1113     OUT_BCS_BATCH(batch, msg[1]);        
1114     OUT_BCS_BATCH(batch, 0x0);    
1115     OUT_BCS_BATCH(batch, 0x0);        
1116
1117     /*MaxSizeInWord and TargetSzieInWord*/
1118     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
1119                   (target_mb_size << 16) );
1120
1121     ADVANCE_BCS_BATCH(batch);
1122
1123     return len_in_dwords;
1124 }
1125
1126 static void 
1127 gen6_mfc_avc_pipeline_slice_programing(VADriverContextP ctx,
1128                                        struct encode_state *encode_state,
1129                                        struct intel_encoder_context *encoder_context,
1130                                        int slice_index,
1131                                        struct intel_batchbuffer *slice_batch)
1132 {
1133     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1134     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1135     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1136     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1137     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1138     unsigned int *msg = NULL, offset = 0;
1139     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
1140     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1141     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1142     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1143     int i,x,y;
1144     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1145     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1146     unsigned char *slice_header = NULL;
1147     int slice_header_length_in_bits = 0;
1148     unsigned int tail_data[] = { 0x0, 0x0 };
1149
1150     if (rate_control_mode == VA_RC_CBR) {
1151         qp = mfc_context->bit_rate_control_context[1 - is_intra].QpPrimeY;
1152         pSliceParameter->slice_qp_delta = qp - 26;
1153     }
1154
1155     /* only support for 8-bit pixel bit-depth */
1156     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
1157     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
1158     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
1159     assert(qp >= 0 && qp < 52);
1160
1161     gen6_mfc_avc_slice_state(ctx, 
1162                              pPicParameter,
1163                              pSliceParameter,
1164                              encode_state, encoder_context,
1165                              (rate_control_mode == VA_RC_CBR), qp, slice_batch);
1166
1167     if ( slice_index == 0) 
1168         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1169
1170     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1171
1172     // slice hander
1173     mfc_context->insert_object(ctx, encoder_context,
1174                                (unsigned int *)slice_header, ALIGN(slice_header_length_in_bits, 32) >> 5, slice_header_length_in_bits & 0x1f,
1175                                5,  /* first 5 bytes are start code + nal unit type */
1176                                1, 0, 1, slice_batch);
1177
1178     if ( rate_control_mode == VA_RC_CBR) {
1179         qp = mfc_context->bit_rate_control_context[1-is_intra].QpPrimeY;
1180     }
1181
1182     dri_bo_map(vme_context->vme_output.bo , 1);
1183     msg = (unsigned int *)vme_context->vme_output.bo->virtual;
1184
1185     if (is_intra) {
1186         msg += pSliceParameter->macroblock_address * INTRA_VME_OUTPUT_IN_DWS;
1187     } else {
1188         msg += pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_DWS;
1189         msg += 32; /* the first 32 DWs are MVs */
1190         offset = pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_BYTES;
1191     }
1192    
1193     for (i = pSliceParameter->macroblock_address; 
1194          i < pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks; i++) {
1195         int last_mb = (i == (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks - 1) );
1196         x = i % width_in_mbs;
1197         y = i / width_in_mbs;
1198
1199         if (is_intra) {
1200             assert(msg);
1201             gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
1202             msg += INTRA_VME_OUTPUT_IN_DWS;
1203         } else {
1204             if (msg[0] & INTRA_MB_FLAG_MASK) {
1205                 gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
1206             } else {
1207                 gen6_mfc_avc_pak_object_inter(ctx, x, y, last_mb, qp, msg, offset, encoder_context, 0, 0, pSliceParameter->slice_type, slice_batch);
1208             }
1209
1210             msg += INTER_VME_OUTPUT_IN_DWS;
1211             offset += INTER_VME_OUTPUT_IN_BYTES;
1212         }
1213     }
1214    
1215     dri_bo_unmap(vme_context->vme_output.bo);
1216
1217     if ( last_slice ) {    
1218         mfc_context->insert_object(ctx, encoder_context,
1219                                    tail_data, 2, 8,
1220                                    2, 1, 1, 0, slice_batch);
1221     } else {
1222         mfc_context->insert_object(ctx, encoder_context,
1223                                    tail_data, 1, 8,
1224                                    1, 1, 1, 0, slice_batch);
1225     }
1226
1227     free(slice_header);
1228
1229 }
1230
1231 static dri_bo *
1232 gen6_mfc_avc_software_batchbuffer(VADriverContextP ctx,
1233                                   struct encode_state *encode_state,
1234                                   struct intel_encoder_context *encoder_context)
1235 {
1236     struct i965_driver_data *i965 = i965_driver_data(ctx);
1237     struct intel_batchbuffer *batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD);
1238     dri_bo *batch_bo = batch->buffer;
1239     int i;
1240
1241     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1242         gen6_mfc_avc_pipeline_slice_programing(ctx, encode_state, encoder_context, i, batch);
1243     }
1244
1245     intel_batchbuffer_align(batch, 8);
1246     
1247     BEGIN_BCS_BATCH(batch, 2);
1248     OUT_BCS_BATCH(batch, 0);
1249     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_END);
1250     ADVANCE_BCS_BATCH(batch);
1251
1252     dri_bo_reference(batch_bo);
1253     intel_batchbuffer_free(batch);
1254
1255     return batch_bo;
1256 }
1257
1258 #else
1259
1260 static void
1261 gen6_mfc_batchbuffer_surfaces_input(VADriverContextP ctx,
1262                                     struct encode_state *encode_state,
1263                                     struct intel_encoder_context *encoder_context)
1264
1265 {
1266     struct gen6_vme_context *vme_context = encoder_context->vme_context;
1267     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1268
1269     assert(vme_context->vme_output.bo);
1270     mfc_context->buffer_suface_setup(ctx,
1271                                      &mfc_context->gpe_context,
1272                                      &vme_context->vme_output,
1273                                      BINDING_TABLE_OFFSET(BIND_IDX_VME_OUTPUT),
1274                                      SURFACE_STATE_OFFSET(BIND_IDX_VME_OUTPUT));
1275     assert(mfc_context->aux_batchbuffer_surface.bo);
1276     mfc_context->buffer_suface_setup(ctx,
1277                                      &mfc_context->gpe_context,
1278                                      &mfc_context->aux_batchbuffer_surface,
1279                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_SLICE_HEADER),
1280                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_SLICE_HEADER));
1281 }
1282
1283 static void
1284 gen6_mfc_batchbuffer_surfaces_output(VADriverContextP ctx,
1285                                      struct encode_state *encode_state,
1286                                      struct intel_encoder_context *encoder_context)
1287
1288 {
1289     struct i965_driver_data *i965 = i965_driver_data(ctx);
1290     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1291     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1292     int width_in_mbs = pSequenceParameter->picture_width_in_mbs;
1293     int height_in_mbs = pSequenceParameter->picture_height_in_mbs;
1294     mfc_context->mfc_batchbuffer_surface.num_blocks = width_in_mbs * height_in_mbs + encode_state->num_slice_params_ext * 8 + 1;
1295     mfc_context->mfc_batchbuffer_surface.size_block = 16 * CMD_LEN_IN_OWORD; /* 3 OWORDs */
1296     mfc_context->mfc_batchbuffer_surface.pitch = 16;
1297     mfc_context->mfc_batchbuffer_surface.bo = dri_bo_alloc(i965->intel.bufmgr, 
1298                                                            "MFC batchbuffer",
1299                                                            mfc_context->mfc_batchbuffer_surface.num_blocks * mfc_context->mfc_batchbuffer_surface.size_block,
1300                                                            0x1000);
1301     mfc_context->buffer_suface_setup(ctx,
1302                                      &mfc_context->gpe_context,
1303                                      &mfc_context->mfc_batchbuffer_surface,
1304                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_BATCHBUFFER),
1305                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_BATCHBUFFER));
1306 }
1307
1308 static void
1309 gen6_mfc_batchbuffer_surfaces_setup(VADriverContextP ctx, 
1310                                     struct encode_state *encode_state,
1311                                     struct intel_encoder_context *encoder_context)
1312 {
1313     gen6_mfc_batchbuffer_surfaces_input(ctx, encode_state, encoder_context);
1314     gen6_mfc_batchbuffer_surfaces_output(ctx, encode_state, encoder_context);
1315 }
1316
1317 static void
1318 gen6_mfc_batchbuffer_idrt_setup(VADriverContextP ctx, 
1319                                 struct encode_state *encode_state,
1320                                 struct intel_encoder_context *encoder_context)
1321 {
1322     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1323     struct gen6_interface_descriptor_data *desc;   
1324     int i;
1325     dri_bo *bo;
1326
1327     bo = mfc_context->gpe_context.idrt.bo;
1328     dri_bo_map(bo, 1);
1329     assert(bo->virtual);
1330     desc = bo->virtual;
1331
1332     for (i = 0; i < mfc_context->gpe_context.num_kernels; i++) {
1333         struct i965_kernel *kernel;
1334
1335         kernel = &mfc_context->gpe_context.kernels[i];
1336         assert(sizeof(*desc) == 32);
1337
1338         /*Setup the descritor table*/
1339         memset(desc, 0, sizeof(*desc));
1340         desc->desc0.kernel_start_pointer = (kernel->bo->offset >> 6);
1341         desc->desc2.sampler_count = 0;
1342         desc->desc2.sampler_state_pointer = 0;
1343         desc->desc3.binding_table_entry_count = 2;
1344         desc->desc3.binding_table_pointer = (BINDING_TABLE_OFFSET(0) >> 5);
1345         desc->desc4.constant_urb_entry_read_offset = 0;
1346         desc->desc4.constant_urb_entry_read_length = 4;
1347                 
1348         /*kernel start*/
1349         dri_bo_emit_reloc(bo,   
1350                           I915_GEM_DOMAIN_INSTRUCTION, 0,
1351                           0,
1352                           i * sizeof(*desc) + offsetof(struct gen6_interface_descriptor_data, desc0),
1353                           kernel->bo);
1354         desc++;
1355     }
1356
1357     dri_bo_unmap(bo);
1358 }
1359
1360 static void
1361 gen6_mfc_batchbuffer_constant_setup(VADriverContextP ctx, 
1362                                     struct encode_state *encode_state,
1363                                     struct intel_encoder_context *encoder_context)
1364 {
1365     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1366     
1367     (void)mfc_context;
1368 }
1369
1370 static void
1371 gen6_mfc_batchbuffer_emit_object_command(struct intel_batchbuffer *batch,
1372                                          int index,
1373                                          int head_offset,
1374                                          int batchbuffer_offset,
1375                                          int head_size,
1376                                          int tail_size,
1377                                          int number_mb_cmds,
1378                                          int first_object,
1379                                          int last_object,
1380                                          int last_slice,
1381                                          int mb_x,
1382                                          int mb_y,
1383                                          int width_in_mbs,
1384                                          int qp)
1385 {
1386     BEGIN_BATCH(batch, 12);
1387     
1388     OUT_BATCH(batch, CMD_MEDIA_OBJECT | (12 - 2));
1389     OUT_BATCH(batch, index);
1390     OUT_BATCH(batch, 0);
1391     OUT_BATCH(batch, 0);
1392     OUT_BATCH(batch, 0);
1393     OUT_BATCH(batch, 0);
1394    
1395     /*inline data */
1396     OUT_BATCH(batch, head_offset);
1397     OUT_BATCH(batch, batchbuffer_offset);
1398     OUT_BATCH(batch, 
1399               head_size << 16 |
1400               tail_size);
1401     OUT_BATCH(batch,
1402               number_mb_cmds << 16 |
1403               first_object << 2 |
1404               last_object << 1 |
1405               last_slice);
1406     OUT_BATCH(batch,
1407               mb_y << 8 |
1408               mb_x);
1409     OUT_BATCH(batch,
1410               qp << 16 |
1411               width_in_mbs);
1412
1413     ADVANCE_BATCH(batch);
1414 }
1415
1416 static void
1417 gen6_mfc_avc_batchbuffer_slice_command(VADriverContextP ctx,
1418                                        struct intel_encoder_context *encoder_context,
1419                                        VAEncSliceParameterBufferH264 *slice_param,
1420                                        int head_offset,
1421                                        unsigned short head_size,
1422                                        unsigned short tail_size,
1423                                        int batchbuffer_offset,
1424                                        int qp,
1425                                        int last_slice)
1426 {
1427     struct intel_batchbuffer *batch = encoder_context->base.batch;
1428     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1429     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1430     int total_mbs = slice_param->num_macroblocks;
1431     int number_mb_cmds = 128;
1432     int starting_mb = 0;
1433     int last_object = 0;
1434     int first_object = 1;
1435     int i;
1436     int mb_x, mb_y;
1437     int index = (slice_param->slice_type == SLICE_TYPE_I) ? MFC_BATCHBUFFER_AVC_INTRA : MFC_BATCHBUFFER_AVC_INTER;
1438
1439     for (i = 0; i < total_mbs / number_mb_cmds; i++) {
1440         last_object = (total_mbs - starting_mb) == number_mb_cmds;
1441         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1442         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1443         assert(mb_x <= 255 && mb_y <= 255);
1444
1445         starting_mb += number_mb_cmds;
1446
1447         gen6_mfc_batchbuffer_emit_object_command(batch,
1448                                                  index,
1449                                                  head_offset,
1450                                                  batchbuffer_offset,
1451                                                  head_size,
1452                                                  tail_size,
1453                                                  number_mb_cmds,
1454                                                  first_object,
1455                                                  last_object,
1456                                                  last_slice,
1457                                                  mb_x,
1458                                                  mb_y,
1459                                                  width_in_mbs,
1460                                                  qp);
1461
1462         if (first_object) {
1463             head_offset += head_size;
1464             batchbuffer_offset += head_size;
1465         }
1466
1467         if (last_object) {
1468             head_offset += tail_size;
1469             batchbuffer_offset += tail_size;
1470         }
1471
1472         batchbuffer_offset += number_mb_cmds * CMD_LEN_IN_OWORD;
1473
1474         first_object = 0;
1475     }
1476
1477     if (!last_object) {
1478         last_object = 1;
1479         number_mb_cmds = total_mbs % number_mb_cmds;
1480         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1481         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1482         assert(mb_x <= 255 && mb_y <= 255);
1483         starting_mb += number_mb_cmds;
1484
1485         gen6_mfc_batchbuffer_emit_object_command(batch,
1486                                                  index,
1487                                                  head_offset,
1488                                                  batchbuffer_offset,
1489                                                  head_size,
1490                                                  tail_size,
1491                                                  number_mb_cmds,
1492                                                  first_object,
1493                                                  last_object,
1494                                                  last_slice,
1495                                                  mb_x,
1496                                                  mb_y,
1497                                                  width_in_mbs,
1498                                                  qp);
1499     }
1500 }
1501                           
1502 /*
1503  * return size in Owords (16bytes)
1504  */         
1505 static int
1506 gen6_mfc_avc_batchbuffer_slice(VADriverContextP ctx,
1507                                struct encode_state *encode_state,
1508                                struct intel_encoder_context *encoder_context,
1509                                int slice_index,
1510                                int batchbuffer_offset)
1511 {
1512     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1513     struct intel_batchbuffer *slice_batch = mfc_context->aux_batchbuffer;
1514     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1515     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1516     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1517     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
1518     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1519     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1520     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1521     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1522     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1523     unsigned char *slice_header = NULL;
1524     int slice_header_length_in_bits = 0;
1525     unsigned int tail_data[] = { 0x0, 0x0 };
1526     long head_offset;
1527     int old_used = intel_batchbuffer_used_size(slice_batch), used;
1528     unsigned short head_size, tail_size;
1529
1530     if (rate_control_mode == VA_RC_CBR) {
1531         qp = mfc_context->bit_rate_control_context[1 - is_intra].QpPrimeY;
1532         pSliceParameter->slice_qp_delta = qp - 26;
1533     }
1534
1535     /* only support for 8-bit pixel bit-depth */
1536     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
1537     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
1538     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
1539     assert(qp >= 0 && qp < 52);
1540
1541     head_offset = old_used / 16;
1542     gen6_mfc_avc_slice_state(ctx,
1543                              pPicParameter,
1544                              pSliceParameter,
1545                              encode_state,
1546                              encoder_context,
1547                              (rate_control_mode == VA_RC_CBR),
1548                              qp,
1549                              slice_batch);
1550
1551     if (slice_index == 0)
1552         gen6_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1553
1554     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1555
1556     // slice hander
1557     mfc_context->insert_object(ctx,
1558                                encoder_context,
1559                                (unsigned int *)slice_header,
1560                                ALIGN(slice_header_length_in_bits, 32) >> 5,
1561                                slice_header_length_in_bits & 0x1f,
1562                                5,  /* first 5 bytes are start code + nal unit type */
1563                                1,
1564                                0,
1565                                1,
1566                                slice_batch);
1567     free(slice_header);
1568
1569     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1570     used = intel_batchbuffer_used_size(slice_batch);
1571     head_size = (used - old_used) / 16;
1572     old_used = used;
1573
1574     if (rate_control_mode == VA_RC_CBR) {
1575         qp = mfc_context->bit_rate_control_context[1 - is_intra].QpPrimeY;
1576     }
1577
1578     /* tail */
1579     if (last_slice) {    
1580         mfc_context->insert_object(ctx,
1581                                    encoder_context,
1582                                    tail_data,
1583                                    2,
1584                                    8,
1585                                    2,
1586                                    1,
1587                                    1,
1588                                    0,
1589                                    slice_batch);
1590     } else {
1591         mfc_context->insert_object(ctx,
1592                                    encoder_context,
1593                                    tail_data,
1594                                    1,
1595                                    8,
1596                                    1,
1597                                    1,
1598                                    1,
1599                                    0,
1600                                    slice_batch);
1601     }
1602
1603     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1604     used = intel_batchbuffer_used_size(slice_batch);
1605     tail_size = (used - old_used) / 16;
1606
1607    
1608     gen6_mfc_avc_batchbuffer_slice_command(ctx,
1609                                            encoder_context,
1610                                            pSliceParameter,
1611                                            head_offset,
1612                                            head_size,
1613                                            tail_size,
1614                                            batchbuffer_offset,
1615                                            qp,
1616                                            last_slice);
1617
1618     return head_size + tail_size + pSliceParameter->num_macroblocks * CMD_LEN_IN_OWORD;
1619 }
1620
1621 static void
1622 gen6_mfc_avc_batchbuffer_pipeline(VADriverContextP ctx,
1623                                   struct encode_state *encode_state,
1624                                   struct intel_encoder_context *encoder_context)
1625 {
1626     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1627     struct intel_batchbuffer *batch = encoder_context->base.batch;
1628     int i, size, offset = 0;
1629     intel_batchbuffer_start_atomic(batch, 0x4000); 
1630     gen6_gpe_pipeline_setup(ctx, &mfc_context->gpe_context, batch);
1631
1632     for ( i = 0; i < encode_state->num_slice_params_ext; i++) {
1633         size = gen6_mfc_avc_batchbuffer_slice(ctx, encode_state, encoder_context, i, offset);
1634         offset += size;
1635     }
1636
1637     intel_batchbuffer_end_atomic(batch);
1638     intel_batchbuffer_flush(batch);
1639 }
1640
1641 static void
1642 gen6_mfc_build_avc_batchbuffer(VADriverContextP ctx, 
1643                                struct encode_state *encode_state,
1644                                struct intel_encoder_context *encoder_context)
1645 {
1646     gen6_mfc_batchbuffer_surfaces_setup(ctx, encode_state, encoder_context);
1647     gen6_mfc_batchbuffer_idrt_setup(ctx, encode_state, encoder_context);
1648     gen6_mfc_batchbuffer_constant_setup(ctx, encode_state, encoder_context);
1649     gen6_mfc_avc_batchbuffer_pipeline(ctx, encode_state, encoder_context);
1650 }
1651
1652 static dri_bo *
1653 gen6_mfc_avc_hardware_batchbuffer(VADriverContextP ctx,
1654                                   struct encode_state *encode_state,
1655                                   struct intel_encoder_context *encoder_context)
1656 {
1657     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1658
1659     gen6_mfc_build_avc_batchbuffer(ctx, encode_state, encoder_context);
1660     dri_bo_reference(mfc_context->mfc_batchbuffer_surface.bo);
1661
1662     return mfc_context->mfc_batchbuffer_surface.bo;
1663 }
1664
1665 #endif
1666
1667 int interlace_check(VADriverContextP ctx,
1668                    struct encode_state *encode_state,
1669                    struct intel_encoder_context *encoder_context) {
1670     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1671     VAEncSliceParameterBufferH264 *pSliceParameter;
1672     int i;
1673     int mbCount = 0;
1674     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1675     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1676   
1677     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
1678         pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[i]->buffer; 
1679         mbCount += pSliceParameter->num_macroblocks; 
1680     }
1681     
1682     if ( mbCount == ( width_in_mbs * height_in_mbs ) )
1683         return 0;
1684
1685     return 1;
1686 }
1687
1688
1689 static void
1690 gen6_mfc_avc_pipeline_programing(VADriverContextP ctx,
1691                                  struct encode_state *encode_state,
1692                                  struct intel_encoder_context *encoder_context)
1693 {
1694     struct intel_batchbuffer *batch = encoder_context->base.batch;
1695     dri_bo *slice_batch_bo;
1696
1697     if ( interlace_check(ctx, encode_state, encoder_context) ) {
1698         fprintf(stderr, "Current VA driver don't support interlace mode!\n");
1699         assert(0);
1700         return; 
1701     }
1702
1703 #if __SOFTWARE__
1704     slice_batch_bo = gen6_mfc_avc_software_batchbuffer(ctx, encode_state, encoder_context);
1705 #else
1706     slice_batch_bo = gen6_mfc_avc_hardware_batchbuffer(ctx, encode_state, encoder_context);
1707 #endif
1708
1709     // begin programing
1710     intel_batchbuffer_start_atomic_bcs(batch, 0x4000); 
1711     intel_batchbuffer_emit_mi_flush(batch);
1712     
1713     // picture level programing
1714     gen6_mfc_avc_pipeline_picture_programing(ctx, encode_state, encoder_context);
1715
1716     BEGIN_BCS_BATCH(batch, 2);
1717     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_START | (1 << 8));
1718     OUT_BCS_RELOC(batch,
1719                   slice_batch_bo,
1720                   I915_GEM_DOMAIN_COMMAND, 0, 
1721                   0);
1722     ADVANCE_BCS_BATCH(batch);
1723
1724     // end programing
1725     intel_batchbuffer_end_atomic(batch);
1726
1727     dri_bo_unreference(slice_batch_bo);
1728 }
1729
1730 static VAStatus
1731 gen6_mfc_avc_encode_picture(VADriverContextP ctx, 
1732                             struct encode_state *encode_state,
1733                             struct intel_encoder_context *encoder_context)
1734 {
1735     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1736     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1737     int MAX_CBR_INTERATE = 4;
1738     int current_frame_bits_size;
1739     int i;
1740  
1741     for(i = 0; i < MAX_CBR_INTERATE; i++) {
1742         gen6_mfc_init(ctx, encoder_context);
1743         gen6_mfc_avc_prepare(ctx, encode_state, encoder_context);
1744         /*Programing bcs pipeline*/
1745         gen6_mfc_avc_pipeline_programing(ctx, encode_state, encoder_context);   //filling the pipeline
1746         gen6_mfc_run(ctx, encode_state, encoder_context);
1747         if ( rate_control_mode == VA_RC_CBR) {
1748             gen6_mfc_stop(ctx, encode_state, encoder_context, &current_frame_bits_size);
1749             //gen6_mfc_hrd_context_check(encode_state, mfc_context);
1750             if ( gen6_mfc_bit_rate_control_context_update(encode_state, mfc_context, current_frame_bits_size)) {
1751                 gen6_mfc_hrd_context_update(encode_state, mfc_context);
1752                 break;
1753             }
1754         } else {
1755             break;
1756         }
1757     }
1758
1759     return VA_STATUS_SUCCESS;
1760 }
1761
1762 VAStatus
1763 gen6_mfc_pipeline(VADriverContextP ctx,
1764                   VAProfile profile,
1765                   struct encode_state *encode_state,
1766                   struct intel_encoder_context *encoder_context)
1767 {
1768     VAStatus vaStatus;
1769
1770     switch (profile) {
1771     case VAProfileH264Baseline:
1772     case VAProfileH264Main:
1773     case VAProfileH264High:
1774         vaStatus = gen6_mfc_avc_encode_picture(ctx, encode_state, encoder_context);
1775         break;
1776
1777         /* FIXME: add for other profile */
1778     default:
1779         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1780         break;
1781     }
1782
1783     return vaStatus;
1784 }
1785
1786 void
1787 gen6_mfc_context_destroy(void *context)
1788 {
1789     struct gen6_mfc_context *mfc_context = context;
1790     int i;
1791
1792     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
1793     mfc_context->post_deblocking_output.bo = NULL;
1794
1795     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
1796     mfc_context->pre_deblocking_output.bo = NULL;
1797
1798     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
1799     mfc_context->uncompressed_picture_source.bo = NULL;
1800
1801     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
1802     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
1803
1804     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
1805         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
1806         mfc_context->direct_mv_buffers[i].bo = NULL;
1807     }
1808
1809     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
1810     mfc_context->intra_row_store_scratch_buffer.bo = NULL;
1811
1812     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
1813     mfc_context->macroblock_status_buffer.bo = NULL;
1814
1815     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
1816     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = NULL;
1817
1818     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
1819     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = NULL;
1820
1821
1822     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
1823         dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
1824         mfc_context->reference_surfaces[i].bo = NULL;  
1825     }
1826
1827     i965_gpe_context_destroy(&mfc_context->gpe_context);
1828
1829     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
1830     mfc_context->mfc_batchbuffer_surface.bo = NULL;
1831
1832     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
1833     mfc_context->aux_batchbuffer_surface.bo = NULL;
1834
1835     if (mfc_context->aux_batchbuffer)
1836         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
1837
1838     mfc_context->aux_batchbuffer = NULL;
1839
1840     free(mfc_context);
1841 }
1842
1843 Bool gen6_mfc_context_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
1844 {
1845     struct gen6_mfc_context *mfc_context = calloc(1, sizeof(struct gen6_mfc_context));
1846
1847     mfc_context->gpe_context.surface_state_binding_table.length = (SURFACE_STATE_PADDED_SIZE + sizeof(unsigned int)) * MAX_MEDIA_SURFACES_GEN6;
1848
1849     mfc_context->gpe_context.idrt.max_entries = MAX_GPE_KERNELS;
1850     mfc_context->gpe_context.idrt.entry_size = sizeof(struct gen6_interface_descriptor_data);
1851
1852     mfc_context->gpe_context.curbe.length = 32 * 4;
1853
1854     mfc_context->gpe_context.vfe_state.max_num_threads = 60 - 1;
1855     mfc_context->gpe_context.vfe_state.num_urb_entries = 16;
1856     mfc_context->gpe_context.vfe_state.gpgpu_mode = 0;
1857     mfc_context->gpe_context.vfe_state.urb_entry_size = 59 - 1;
1858     mfc_context->gpe_context.vfe_state.curbe_allocation_size = 37 - 1;
1859
1860     i965_gpe_load_kernels(ctx,
1861                           &mfc_context->gpe_context,
1862                           gen6_mfc_kernels,
1863                           NUM_MFC_KERNEL);
1864
1865     mfc_context->pipe_mode_select = gen6_mfc_pipe_mode_select;
1866     mfc_context->set_surface_state = gen6_mfc_surface_state;
1867     mfc_context->ind_obj_base_addr_state = gen6_mfc_ind_obj_base_addr_state;
1868     mfc_context->avc_img_state = gen6_mfc_avc_img_state;
1869     mfc_context->avc_qm_state = gen6_mfc_avc_qm_state;
1870     mfc_context->avc_fqm_state = gen6_mfc_avc_fqm_state;
1871     mfc_context->insert_object = gen6_mfc_avc_insert_object;
1872     mfc_context->buffer_suface_setup = i965_gpe_buffer_suface_setup;
1873
1874     encoder_context->mfc_context = mfc_context;
1875     encoder_context->mfc_context_destroy = gen6_mfc_context_destroy;
1876     encoder_context->mfc_pipeline = gen6_mfc_pipeline;
1877
1878     return True;
1879 }