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