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