Add the support of the chroma intra prediction on Haswell
[profile/ivi/vaapi-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 #include <math.h>
34
35 #include "intel_batchbuffer.h"
36 #include "i965_defines.h"
37 #include "i965_structs.h"
38 #include "i965_drv_video.h"
39 #include "i965_encoder.h"
40 #include "i965_encoder_utils.h"
41 #include "gen6_mfc.h"
42 #include "gen6_vme.h"
43 #include "intel_media.h"
44
45 static const uint32_t gen6_mfc_batchbuffer_avc_intra[][4] = {
46 #include "shaders/utils/mfc_batchbuffer_avc_intra.g6b"
47 };
48
49 static const uint32_t gen6_mfc_batchbuffer_avc_inter[][4] = {
50 #include "shaders/utils/mfc_batchbuffer_avc_inter.g6b"
51 };
52
53 static struct i965_kernel gen6_mfc_kernels[] = {
54     {
55         "MFC AVC INTRA BATCHBUFFER ",
56         MFC_BATCHBUFFER_AVC_INTRA,
57         gen6_mfc_batchbuffer_avc_intra,
58         sizeof(gen6_mfc_batchbuffer_avc_intra),
59         NULL
60     },
61
62     {
63         "MFC AVC INTER BATCHBUFFER ",
64         MFC_BATCHBUFFER_AVC_INTER,
65         gen6_mfc_batchbuffer_avc_inter,
66         sizeof(gen6_mfc_batchbuffer_avc_inter),
67         NULL
68     },
69 };
70
71 static void
72 gen6_mfc_pipe_mode_select(VADriverContextP ctx,
73                           int standard_select,
74                           struct intel_encoder_context *encoder_context)
75 {
76     struct intel_batchbuffer *batch = encoder_context->base.batch;
77     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
78
79     assert(standard_select == MFX_FORMAT_AVC);
80
81     BEGIN_BCS_BATCH(batch, 4);
82
83     OUT_BCS_BATCH(batch, MFX_PIPE_MODE_SELECT | (4 - 2));
84     OUT_BCS_BATCH(batch,
85                   (1 << 10) | /* disable Stream-Out , advanced QP/bitrate control need enable it*/
86                   ((!!mfc_context->post_deblocking_output.bo) << 9)  | /* Post Deblocking Output */
87                   ((!!mfc_context->pre_deblocking_output.bo) << 8)  | /* Pre Deblocking Output */
88                   (0 << 7)  | /* disable TLB prefectch */
89                   (0 << 5)  | /* not in stitch mode */
90                   (1 << 4)  | /* encoding mode */
91                   (2 << 0));  /* Standard Select: AVC */
92     OUT_BCS_BATCH(batch,
93                   (0 << 20) | /* round flag in PB slice */
94                   (0 << 19) | /* round flag in Intra8x8 */
95                   (0 << 7)  | /* expand NOA bus flag */
96                   (1 << 6)  | /* must be 1 */
97                   (0 << 5)  | /* disable clock gating for NOA */
98                   (0 << 4)  | /* terminate if AVC motion and POC table error occurs */
99                   (0 << 3)  | /* terminate if AVC mbdata error occurs */
100                   (0 << 2)  | /* terminate if AVC CABAC/CAVLC decode error occurs */
101                   (0 << 1)  | /* AVC long field motion vector */
102                   (0 << 0));  /* always calculate AVC ILDB boundary strength */
103     OUT_BCS_BATCH(batch, 0);
104
105     ADVANCE_BCS_BATCH(batch);
106 }
107
108 static void
109 gen6_mfc_surface_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
110 {
111     struct intel_batchbuffer *batch = encoder_context->base.batch;
112     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
113
114     BEGIN_BCS_BATCH(batch, 6);
115
116     OUT_BCS_BATCH(batch, MFX_SURFACE_STATE | (6 - 2));
117     OUT_BCS_BATCH(batch, 0);
118     OUT_BCS_BATCH(batch,
119                   ((mfc_context->surface_state.height - 1) << 19) |
120                   ((mfc_context->surface_state.width - 1) << 6));
121     OUT_BCS_BATCH(batch,
122                   (MFX_SURFACE_PLANAR_420_8 << 28) | /* 420 planar YUV surface */
123                   (1 << 27) | /* must be 1 for interleave U/V, hardware requirement */
124                   (0 << 22) | /* surface object control state, FIXME??? */
125                   ((mfc_context->surface_state.w_pitch - 1) << 3) | /* pitch */
126                   (0 << 2)  | /* must be 0 for interleave U/V */
127                   (1 << 1)  | /* must be y-tiled */
128                   (I965_TILEWALK_YMAJOR << 0));                         /* tile walk, TILEWALK_YMAJOR */
129     OUT_BCS_BATCH(batch,
130                   (0 << 16) |                                                           /* must be 0 for interleave U/V */
131                   (mfc_context->surface_state.h_pitch));                /* y offset for U(cb) */
132     OUT_BCS_BATCH(batch, 0);
133     ADVANCE_BCS_BATCH(batch);
134 }
135
136 static void
137 gen6_mfc_pipe_buf_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
138 {
139     struct intel_batchbuffer *batch = encoder_context->base.batch;
140     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
141     int i;
142
143     BEGIN_BCS_BATCH(batch, 24);
144
145     OUT_BCS_BATCH(batch, MFX_PIPE_BUF_ADDR_STATE | (24 - 2));
146
147     if (mfc_context->pre_deblocking_output.bo)
148         OUT_BCS_RELOC(batch, mfc_context->pre_deblocking_output.bo,
149                       I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
150                       0);
151     else
152         OUT_BCS_BATCH(batch, 0);                                                                                        /* pre output addr   */
153
154     if (mfc_context->post_deblocking_output.bo)
155         OUT_BCS_RELOC(batch, mfc_context->post_deblocking_output.bo,
156                       I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
157                       0);                                                                                       /* post output addr  */ 
158     else
159         OUT_BCS_BATCH(batch, 0);
160
161     OUT_BCS_RELOC(batch, mfc_context->uncompressed_picture_source.bo,
162                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
163                   0);                                                                                   /* uncompressed data */
164     OUT_BCS_RELOC(batch, mfc_context->macroblock_status_buffer.bo,
165                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
166                   0);                                                                                   /* StreamOut data*/
167     OUT_BCS_RELOC(batch, mfc_context->intra_row_store_scratch_buffer.bo,
168                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
169                   0);   
170     OUT_BCS_RELOC(batch, mfc_context->deblocking_filter_row_store_scratch_buffer.bo,
171                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
172                   0);
173     /* 7..22 Reference pictures*/
174     for (i = 0; i < ARRAY_ELEMS(mfc_context->reference_surfaces); i++) {
175         if ( mfc_context->reference_surfaces[i].bo != NULL) {
176             OUT_BCS_RELOC(batch, mfc_context->reference_surfaces[i].bo,
177                           I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
178                           0);                   
179         } else {
180             OUT_BCS_BATCH(batch, 0);
181         }
182     }
183     OUT_BCS_RELOC(batch, mfc_context->macroblock_status_buffer.bo,
184                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
185                   0);                                                                                   /* Macroblock status buffer*/
186
187     ADVANCE_BCS_BATCH(batch);
188 }
189
190 static void
191 gen6_mfc_ind_obj_base_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
192 {
193     struct intel_batchbuffer *batch = encoder_context->base.batch;
194     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
195     struct gen6_vme_context *vme_context = encoder_context->vme_context;
196
197     BEGIN_BCS_BATCH(batch, 11);
198
199     OUT_BCS_BATCH(batch, MFX_IND_OBJ_BASE_ADDR_STATE | (11 - 2));
200     OUT_BCS_BATCH(batch, 0);
201     OUT_BCS_BATCH(batch, 0);
202     /* MFX Indirect MV Object Base Address */
203     OUT_BCS_RELOC(batch, vme_context->vme_output.bo, I915_GEM_DOMAIN_INSTRUCTION, 0, 0);
204     OUT_BCS_BATCH(batch, 0);    
205     OUT_BCS_BATCH(batch, 0);
206     OUT_BCS_BATCH(batch, 0);
207     OUT_BCS_BATCH(batch, 0);
208     OUT_BCS_BATCH(batch, 0);
209     /*MFC Indirect PAK-BSE Object Base Address for Encoder*/    
210     OUT_BCS_RELOC(batch,
211                   mfc_context->mfc_indirect_pak_bse_object.bo,
212                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
213                   0);
214     OUT_BCS_RELOC(batch,
215                   mfc_context->mfc_indirect_pak_bse_object.bo,
216                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
217                   mfc_context->mfc_indirect_pak_bse_object.end_offset);
218
219     ADVANCE_BCS_BATCH(batch);
220 }
221
222 static void
223 gen6_mfc_bsp_buf_base_addr_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
224 {
225     struct intel_batchbuffer *batch = encoder_context->base.batch;
226     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
227
228     BEGIN_BCS_BATCH(batch, 4);
229
230     OUT_BCS_BATCH(batch, MFX_BSP_BUF_BASE_ADDR_STATE | (4 - 2));
231     OUT_BCS_RELOC(batch, mfc_context->bsd_mpc_row_store_scratch_buffer.bo,
232                   I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
233                   0);
234     OUT_BCS_BATCH(batch, 0);
235     OUT_BCS_BATCH(batch, 0);
236
237     ADVANCE_BCS_BATCH(batch);
238 }
239
240 static void
241 gen6_mfc_avc_img_state(VADriverContextP ctx,struct encode_state *encode_state,
242                        struct intel_encoder_context *encoder_context)
243 {
244     struct intel_batchbuffer *batch = encoder_context->base.batch;
245     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
246     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
247     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
248     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
249     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
250
251     BEGIN_BCS_BATCH(batch, 13);
252     OUT_BCS_BATCH(batch, MFX_AVC_IMG_STATE | (13 - 2));
253     OUT_BCS_BATCH(batch, 
254                   ((width_in_mbs * height_in_mbs) & 0xFFFF));
255     OUT_BCS_BATCH(batch, 
256                   (height_in_mbs << 16) | 
257                   (width_in_mbs << 0));
258     OUT_BCS_BATCH(batch, 
259                   (0 << 24) |     /*Second Chroma QP Offset*/
260                   (0 << 16) |     /*Chroma QP Offset*/
261                   (0 << 14) |   /*Max-bit conformance Intra flag*/
262                   (0 << 13) |   /*Max Macroblock size conformance Inter flag*/
263                   (1 << 12) |   /*Should always be written as "1" */
264                   (0 << 10) |   /*QM Preset FLag */
265                   (0 << 8)  |   /*Image Structure*/
266                   (0 << 0) );   /*Current Decoed Image Frame Store ID, reserved in Encode mode*/
267     OUT_BCS_BATCH(batch,
268                   (400 << 16) |   /*Mininum Frame size*/        
269                   (0 << 15) |   /*Disable reading of Macroblock Status Buffer*/
270                   (0 << 14) |   /*Load BitStream Pointer only once, 1 slic 1 frame*/
271                   (0 << 13) |   /*CABAC 0 word insertion test enable*/
272                   (1 << 12) |   /*MVUnpackedEnable,compliant to DXVA*/
273                   (1 << 10) |   /*Chroma Format IDC, 4:2:0*/
274                   (pPicParameter->pic_fields.bits.entropy_coding_mode_flag << 7)  |   /*0:CAVLC encoding mode,1:CABAC*/
275                   (0 << 6)  |   /*Only valid for VLD decoding mode*/
276                   (0 << 5)  |   /*Constrained Intra Predition Flag, from PPS*/
277                   (pSequenceParameter->seq_fields.bits.direct_8x8_inference_flag << 4)  |   /*Direct 8x8 inference flag*/
278                   (pPicParameter->pic_fields.bits.transform_8x8_mode_flag << 3)  |   /*8x8 or 4x4 IDCT Transform Mode Flag*/
279                   (1 << 2)  |   /*Frame MB only flag*/
280                   (0 << 1)  |   /*MBAFF mode is in active*/
281                   (0 << 0) );   /*Field picture flag*/
282     OUT_BCS_BATCH(batch, 
283                   (1<<16)   |   /*Frame Size Rate Control Flag*/  
284                   (1<<12)   |   
285                   (1<<9)    |   /*MB level Rate Control Enabling Flag*/
286                   (1 << 3)  |   /*FrameBitRateMinReportMask*/
287                   (1 << 2)  |   /*FrameBitRateMaxReportMask*/
288                   (1 << 1)  |   /*InterMBMaxSizeReportMask*/
289                   (1 << 0) );   /*IntraMBMaxSizeReportMask*/
290     OUT_BCS_BATCH(batch,                        /*Inter and Intra Conformance Max size limit*/
291                   (0x0600 << 16) |              /*InterMbMaxSz 192 Byte*/
292                   (0x0800) );                   /*IntraMbMaxSz 256 Byte*/
293     OUT_BCS_BATCH(batch, 0x00000000);   /*Reserved : MBZReserved*/
294     OUT_BCS_BATCH(batch, 0x01020304);   /*Slice QP Delta for bitrate control*/                  
295     OUT_BCS_BATCH(batch, 0xFEFDFCFB);           
296     OUT_BCS_BATCH(batch, 0x80601004);   /*MAX = 128KB, MIN = 64KB*/
297     OUT_BCS_BATCH(batch, 0x00800001);   
298     OUT_BCS_BATCH(batch, 0);
299
300     ADVANCE_BCS_BATCH(batch);
301 }
302
303 static void
304 gen6_mfc_avc_directmode_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
305 {
306     struct intel_batchbuffer *batch = encoder_context->base.batch;
307     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
308
309     int i;
310
311     BEGIN_BCS_BATCH(batch, 69);
312
313     OUT_BCS_BATCH(batch, MFX_AVC_DIRECTMODE_STATE | (69 - 2));
314
315     /* Reference frames and Current frames */
316     for(i = 0; i < NUM_MFC_DMV_BUFFERS; i++) {
317         if ( mfc_context->direct_mv_buffers[i].bo != NULL) { 
318             OUT_BCS_RELOC(batch, mfc_context->direct_mv_buffers[i].bo,
319                           I915_GEM_DOMAIN_INSTRUCTION, 0,
320                           0);
321         } else {
322             OUT_BCS_BATCH(batch, 0);
323         }
324     }
325
326     /* POL list */
327     for(i = 0; i < 32; i++) {
328         OUT_BCS_BATCH(batch, i/2);
329     }
330     OUT_BCS_BATCH(batch, 0);
331     OUT_BCS_BATCH(batch, 0);
332
333     ADVANCE_BCS_BATCH(batch);
334 }
335
336 static void
337 gen6_mfc_avc_slice_state(VADriverContextP ctx,
338                          VAEncPictureParameterBufferH264 *pic_param,
339                          VAEncSliceParameterBufferH264 *slice_param,
340                          struct encode_state *encode_state,
341                          struct intel_encoder_context *encoder_context,
342                          int rate_control_enable,
343                          int qp,
344                          struct intel_batchbuffer *batch)
345 {
346     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
347     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
348     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
349     int beginmb = slice_param->macroblock_address;
350     int endmb = beginmb + slice_param->num_macroblocks;
351     int beginx = beginmb % width_in_mbs;
352     int beginy = beginmb / width_in_mbs;
353     int nextx =  endmb % width_in_mbs;
354     int nexty = endmb / width_in_mbs;
355     int slice_type = slice_param->slice_type;
356     int last_slice = (endmb == (width_in_mbs * height_in_mbs));
357     int bit_rate_control_target, maxQpN, maxQpP;
358     unsigned char correct[6], grow, shrink;
359     int i;
360     int weighted_pred_idc = 0;
361     unsigned int luma_log2_weight_denom = slice_param->luma_log2_weight_denom;
362     unsigned int chroma_log2_weight_denom = slice_param->chroma_log2_weight_denom;
363
364     if (batch == NULL)
365         batch = encoder_context->base.batch;
366
367     bit_rate_control_target = slice_type;
368     if (slice_type == SLICE_TYPE_SP)
369         bit_rate_control_target = SLICE_TYPE_P;
370     else if (slice_type == SLICE_TYPE_SI)
371         bit_rate_control_target = SLICE_TYPE_I;
372
373     if (slice_type == SLICE_TYPE_P) {
374         weighted_pred_idc = pic_param->pic_fields.bits.weighted_pred_flag;
375     } else if (slice_type == SLICE_TYPE_B) {
376         weighted_pred_idc = pic_param->pic_fields.bits.weighted_bipred_idc;
377
378         if (weighted_pred_idc == 2) {
379             /* 8.4.3 - Derivation process for prediction weights (8-279) */
380             luma_log2_weight_denom = 5;
381             chroma_log2_weight_denom = 5;
382         }
383     }
384
385     maxQpN = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpNegModifier;
386     maxQpP = mfc_context->bit_rate_control_context[bit_rate_control_target].MaxQpPosModifier;
387
388     for (i = 0; i < 6; i++)
389         correct[i] = mfc_context->bit_rate_control_context[bit_rate_control_target].Correct[i];
390
391     grow = mfc_context->bit_rate_control_context[bit_rate_control_target].GrowInit + 
392         (mfc_context->bit_rate_control_context[bit_rate_control_target].GrowResistance << 4);
393     shrink = mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkInit + 
394         (mfc_context->bit_rate_control_context[bit_rate_control_target].ShrinkResistance << 4);
395
396     BEGIN_BCS_BATCH(batch, 11);;
397
398     OUT_BCS_BATCH(batch, MFX_AVC_SLICE_STATE | (11 - 2) );
399     OUT_BCS_BATCH(batch, slice_type);                   /*Slice Type: I:P:B Slice*/
400
401     if (slice_type == SLICE_TYPE_I) {
402         OUT_BCS_BATCH(batch, 0);                        /*no reference frames and pred_weight_table*/
403     } else {
404         OUT_BCS_BATCH(batch,
405                       (1 << 16) |                       /*1 reference frame*/
406                       (chroma_log2_weight_denom << 8) |
407                       (luma_log2_weight_denom << 0));
408     }
409
410     OUT_BCS_BATCH(batch, 
411                   (weighted_pred_idc << 30) |
412                   (slice_param->direct_spatial_mv_pred_flag<<29) |             /*Direct Prediction Type*/
413                   (slice_param->disable_deblocking_filter_idc << 27) |
414                   (slice_param->cabac_init_idc << 24) |
415                   (qp<<16) |                    /*Slice Quantization Parameter*/
416                   ((slice_param->slice_beta_offset_div2 & 0xf) << 8) |
417                   ((slice_param->slice_alpha_c0_offset_div2 & 0xf) << 0));
418     OUT_BCS_BATCH(batch,
419                   (beginy << 24) |                      /*First MB X&Y , the begin postion of current slice*/
420                   (beginx << 16) |
421                   slice_param->macroblock_address );
422     OUT_BCS_BATCH(batch, (nexty << 16) | nextx);                       /*Next slice first MB X&Y*/
423     OUT_BCS_BATCH(batch, 
424                   (0/*rate_control_enable*/ << 31) |            /*in CBR mode RateControlCounterEnable = enable*/
425                   (1 << 30) |           /*ResetRateControlCounter*/
426                   (0 << 28) |           /*RC Triggle Mode = Always Rate Control*/
427                   (4 << 24) |     /*RC Stable Tolerance, middle level*/
428                   (0/*rate_control_enable*/ << 23) |     /*RC Panic Enable*/                 
429                   (0 << 22) |     /*QP mode, don't modfiy CBP*/
430                   (0 << 21) |     /*MB Type Direct Conversion Enabled*/ 
431                   (0 << 20) |     /*MB Type Skip Conversion Enabled*/ 
432                   (last_slice << 19) |     /*IsLastSlice*/
433                   (0 << 18) |   /*BitstreamOutputFlag Compressed BitStream Output Disable Flag 0:enable 1:disable*/
434                   (1 << 17) |       /*HeaderPresentFlag*/       
435                   (1 << 16) |       /*SliceData PresentFlag*/
436                   (1 << 15) |       /*TailPresentFlag*/
437                   (1 << 13) |       /*RBSP NAL TYPE*/   
438                   (0 << 12) );    /*CabacZeroWordInsertionEnable*/
439     OUT_BCS_BATCH(batch, mfc_context->mfc_indirect_pak_bse_object.offset);
440     OUT_BCS_BATCH(batch,
441                   (maxQpN << 24) |     /*Target QP - 24 is lowest QP*/ 
442                   (maxQpP << 16) |     /*Target QP + 20 is highest QP*/
443                   (shrink << 8)  |
444                   (grow << 0));   
445     OUT_BCS_BATCH(batch,
446                   (correct[5] << 20) |
447                   (correct[4] << 16) |
448                   (correct[3] << 12) |
449                   (correct[2] << 8) |
450                   (correct[1] << 4) |
451                   (correct[0] << 0));
452     OUT_BCS_BATCH(batch, 0);
453
454     ADVANCE_BCS_BATCH(batch);
455 }
456
457 static void gen6_mfc_avc_qm_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, 58);
463
464     OUT_BCS_BATCH(batch, MFX_AVC_QM_STATE | 56);
465     OUT_BCS_BATCH(batch, 0xFF ) ; 
466     for( i = 0; i < 56; i++) {
467         OUT_BCS_BATCH(batch, 0x10101010); 
468     }   
469
470     ADVANCE_BCS_BATCH(batch);
471 }
472
473 static void gen6_mfc_avc_fqm_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
474 {
475     struct intel_batchbuffer *batch = encoder_context->base.batch;
476     int i;
477
478     BEGIN_BCS_BATCH(batch, 113);
479     OUT_BCS_BATCH(batch, MFC_AVC_FQM_STATE | (113 - 2));
480
481     for(i = 0; i < 112;i++) {
482         OUT_BCS_BATCH(batch, 0x10001000);
483     }   
484
485     ADVANCE_BCS_BATCH(batch);   
486 }
487
488 static void
489 gen6_mfc_avc_ref_idx_state(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
490 {
491     struct intel_batchbuffer *batch = encoder_context->base.batch;
492     int i;
493
494     BEGIN_BCS_BATCH(batch, 10);
495     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
496     OUT_BCS_BATCH(batch, 0);                  //Select L0
497     OUT_BCS_BATCH(batch, 0x80808020);         //Only 1 reference
498     for(i = 0; i < 7; i++) {
499         OUT_BCS_BATCH(batch, 0x80808080);
500     }   
501     ADVANCE_BCS_BATCH(batch);
502
503     BEGIN_BCS_BATCH(batch, 10);
504     OUT_BCS_BATCH(batch, MFX_AVC_REF_IDX_STATE | 8); 
505     OUT_BCS_BATCH(batch, 1);                  //Select L1
506     OUT_BCS_BATCH(batch, 0x80808022);         //Only 1 reference
507     for(i = 0; i < 7; i++) {
508         OUT_BCS_BATCH(batch, 0x80808080);
509     }   
510     ADVANCE_BCS_BATCH(batch);
511 }
512         
513 static void
514 gen6_mfc_avc_insert_object(VADriverContextP ctx, struct intel_encoder_context *encoder_context,
515                            unsigned int *insert_data, int lenght_in_dws, int data_bits_in_last_dw,
516                            int skip_emul_byte_count, int is_last_header, int is_end_of_slice, int emulation_flag,
517                            struct intel_batchbuffer *batch)
518 {
519     if (batch == NULL)
520         batch = encoder_context->base.batch;
521
522     BEGIN_BCS_BATCH(batch, lenght_in_dws + 2);
523
524     OUT_BCS_BATCH(batch, MFC_AVC_INSERT_OBJECT | (lenght_in_dws + 2 - 2));
525
526     OUT_BCS_BATCH(batch,
527                   (0 << 16) |   /* always start at offset 0 */
528                   (data_bits_in_last_dw << 8) |
529                   (skip_emul_byte_count << 4) |
530                   (!!emulation_flag << 3) |
531                   ((!!is_last_header) << 2) |
532                   ((!!is_end_of_slice) << 1) |
533                   (0 << 0));    /* FIXME: ??? */
534
535     intel_batchbuffer_data(batch, insert_data, lenght_in_dws * 4);
536     ADVANCE_BCS_BATCH(batch);
537 }
538
539 static void gen6_mfc_init(VADriverContextP ctx, 
540                             struct encode_state *encode_state,
541                             struct intel_encoder_context *encoder_context)
542 {
543     struct i965_driver_data *i965 = i965_driver_data(ctx);
544     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
545     dri_bo *bo;
546     int i;
547     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
548     int width_in_mbs = pSequenceParameter->picture_width_in_mbs;
549     int height_in_mbs = pSequenceParameter->picture_height_in_mbs;
550
551     /*Encode common setup for MFC*/
552     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
553     mfc_context->post_deblocking_output.bo = NULL;
554
555     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
556     mfc_context->pre_deblocking_output.bo = NULL;
557
558     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
559     mfc_context->uncompressed_picture_source.bo = NULL;
560
561     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
562     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
563
564     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
565         if ( mfc_context->direct_mv_buffers[i].bo != NULL);
566         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
567         mfc_context->direct_mv_buffers[i].bo = NULL;
568     }
569
570     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
571         if (mfc_context->reference_surfaces[i].bo != NULL)
572             dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
573         mfc_context->reference_surfaces[i].bo = NULL;  
574     }
575
576     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
577     bo = dri_bo_alloc(i965->intel.bufmgr,
578                       "Buffer",
579                       width_in_mbs * 64,
580                       64);
581     assert(bo);
582     mfc_context->intra_row_store_scratch_buffer.bo = bo;
583
584     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
585     bo = dri_bo_alloc(i965->intel.bufmgr,
586                       "Buffer",
587                       width_in_mbs * height_in_mbs * 16,
588                       64);
589     assert(bo);
590     mfc_context->macroblock_status_buffer.bo = bo;
591
592     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
593     bo = dri_bo_alloc(i965->intel.bufmgr,
594                       "Buffer",
595                       4 * width_in_mbs * 64,  /* 4 * width_in_mbs * 64 */
596                       64);
597     assert(bo);
598     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = bo;
599
600     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
601     bo = dri_bo_alloc(i965->intel.bufmgr,
602                       "Buffer",
603                       128 * width_in_mbs, /* 2 * widht_in_mbs * 64 */
604                       0x1000);
605     assert(bo);
606     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = bo;
607
608     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
609     mfc_context->mfc_batchbuffer_surface.bo = NULL;
610
611     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
612     mfc_context->aux_batchbuffer_surface.bo = NULL;
613
614     if (mfc_context->aux_batchbuffer)
615         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
616
617     mfc_context->aux_batchbuffer = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD, 0);
618     mfc_context->aux_batchbuffer_surface.bo = mfc_context->aux_batchbuffer->buffer;
619     dri_bo_reference(mfc_context->aux_batchbuffer_surface.bo);
620     mfc_context->aux_batchbuffer_surface.pitch = 16;
621     mfc_context->aux_batchbuffer_surface.num_blocks = mfc_context->aux_batchbuffer->size / 16;
622     mfc_context->aux_batchbuffer_surface.size_block = 16;
623
624     i965_gpe_context_init(ctx, &mfc_context->gpe_context);
625 }
626
627 static void gen6_mfc_avc_pipeline_picture_programing( VADriverContextP ctx,
628                                       struct encode_state *encode_state,
629                                       struct intel_encoder_context *encoder_context)
630 {
631     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
632
633     mfc_context->pipe_mode_select(ctx, MFX_FORMAT_AVC, encoder_context);
634     mfc_context->set_surface_state(ctx, encoder_context);
635     mfc_context->ind_obj_base_addr_state(ctx, encoder_context);
636     gen6_mfc_pipe_buf_addr_state(ctx, encoder_context);
637     gen6_mfc_bsp_buf_base_addr_state(ctx, encoder_context);
638     mfc_context->avc_img_state(ctx, encode_state, encoder_context);
639     mfc_context->avc_qm_state(ctx, encoder_context);
640     mfc_context->avc_fqm_state(ctx, encoder_context);
641     gen6_mfc_avc_directmode_state(ctx, encoder_context); 
642     gen6_mfc_avc_ref_idx_state(ctx, encoder_context);
643 }
644
645
646 static VAStatus gen6_mfc_run(VADriverContextP ctx, 
647                              struct encode_state *encode_state,
648                              struct intel_encoder_context *encoder_context)
649 {
650     struct intel_batchbuffer *batch = encoder_context->base.batch;
651
652     intel_batchbuffer_flush(batch);             //run the pipeline
653
654     return VA_STATUS_SUCCESS;
655 }
656
657 static VAStatus
658 gen6_mfc_stop(VADriverContextP ctx, 
659               struct encode_state *encode_state,
660               struct intel_encoder_context *encoder_context,
661               int *encoded_bits_size)
662 {
663     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
664     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
665     VACodedBufferSegment *coded_buffer_segment;
666     
667     vaStatus = i965_MapBuffer(ctx, pPicParameter->coded_buf, (void **)&coded_buffer_segment);
668     assert(vaStatus == VA_STATUS_SUCCESS);
669     *encoded_bits_size = coded_buffer_segment->size * 8;
670     i965_UnmapBuffer(ctx, pPicParameter->coded_buf);
671
672     return VA_STATUS_SUCCESS;
673 }
674
675 #if __SOFTWARE__
676
677 static int
678 gen6_mfc_avc_pak_object_intra(VADriverContextP ctx, int x, int y, int end_mb, int qp,unsigned int *msg,
679                               struct intel_encoder_context *encoder_context,
680                               unsigned char target_mb_size, unsigned char max_mb_size,
681                               struct intel_batchbuffer *batch)
682 {
683     int len_in_dwords = 11;
684
685     if (batch == NULL)
686         batch = encoder_context->base.batch;
687
688     BEGIN_BCS_BATCH(batch, len_in_dwords);
689
690     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
691     OUT_BCS_BATCH(batch, 0);
692     OUT_BCS_BATCH(batch, 0);
693     OUT_BCS_BATCH(batch, 
694                   (0 << 24) |           /* PackedMvNum, Debug*/
695                   (0 << 20) |           /* No motion vector */
696                   (1 << 19) |           /* CbpDcY */
697                   (1 << 18) |           /* CbpDcU */
698                   (1 << 17) |           /* CbpDcV */
699                   (msg[0] & 0xFFFF) );
700
701     OUT_BCS_BATCH(batch, (0xFFFF << 16) | (y << 8) | x);                /* Code Block Pattern for Y*/
702     OUT_BCS_BATCH(batch, 0x000F000F);                                                   /* Code Block Pattern */                
703     OUT_BCS_BATCH(batch, (0 << 27) | (end_mb << 26) | qp);      /* Last MB */
704
705     /*Stuff for Intra MB*/
706     OUT_BCS_BATCH(batch, msg[1]);                       /* We using Intra16x16 no 4x4 predmode*/        
707     OUT_BCS_BATCH(batch, msg[2]);       
708     OUT_BCS_BATCH(batch, msg[3]&0xFC);          
709     
710     /*MaxSizeInWord and TargetSzieInWord*/
711     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
712                   (target_mb_size << 16) );
713
714     ADVANCE_BCS_BATCH(batch);
715
716     return len_in_dwords;
717 }
718
719 static int
720 gen6_mfc_avc_pak_object_inter(VADriverContextP ctx, int x, int y, int end_mb, int qp,
721                               unsigned int *msg, unsigned int offset,
722                               struct intel_encoder_context *encoder_context,
723                               unsigned char target_mb_size,unsigned char max_mb_size, int slice_type,
724                               struct intel_batchbuffer *batch)
725 {
726     int len_in_dwords = 11;
727
728     if (batch == NULL)
729         batch = encoder_context->base.batch;
730
731     BEGIN_BCS_BATCH(batch, len_in_dwords);
732
733     OUT_BCS_BATCH(batch, MFC_AVC_PAK_OBJECT | (len_in_dwords - 2));
734
735     OUT_BCS_BATCH(batch, msg[2]);         /* 32 MV*/
736     OUT_BCS_BATCH(batch, offset);
737
738     OUT_BCS_BATCH(batch, msg[0]);
739
740     OUT_BCS_BATCH(batch, (0xFFFF<<16) | (y << 8) | x);        /* Code Block Pattern for Y*/
741     OUT_BCS_BATCH(batch, 0x000F000F);                         /* Code Block Pattern */  
742 #if 0 
743     if ( slice_type == SLICE_TYPE_B) {
744         OUT_BCS_BATCH(batch, (0xF<<28) | (end_mb << 26) | qp);  /* Last MB */
745     } else {
746         OUT_BCS_BATCH(batch, (end_mb << 26) | qp);      /* Last MB */
747     }
748 #else
749     OUT_BCS_BATCH(batch, (end_mb << 26) | qp);  /* Last MB */
750 #endif
751
752
753     /*Stuff for Inter MB*/
754     OUT_BCS_BATCH(batch, msg[1]);        
755     OUT_BCS_BATCH(batch, 0x0);    
756     OUT_BCS_BATCH(batch, 0x0);        
757
758     /*MaxSizeInWord and TargetSzieInWord*/
759     OUT_BCS_BATCH(batch, (max_mb_size << 24) |
760                   (target_mb_size << 16) );
761
762     ADVANCE_BCS_BATCH(batch);
763
764     return len_in_dwords;
765 }
766
767 static void 
768 gen6_mfc_avc_pipeline_slice_programing(VADriverContextP ctx,
769                                        struct encode_state *encode_state,
770                                        struct intel_encoder_context *encoder_context,
771                                        int slice_index,
772                                        struct intel_batchbuffer *slice_batch)
773 {
774     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
775     struct gen6_vme_context *vme_context = encoder_context->vme_context;
776     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
777     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
778     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
779     unsigned int *msg = NULL, offset = 0;
780     int is_intra = pSliceParameter->slice_type == SLICE_TYPE_I;
781     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
782     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
783     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
784     int i,x,y;
785     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
786     unsigned int rate_control_mode = encoder_context->rate_control_mode;
787     unsigned char *slice_header = NULL;
788     int slice_header_length_in_bits = 0;
789     unsigned int tail_data[] = { 0x0, 0x0 };
790     int slice_type = pSliceParameter->slice_type;
791
792
793     if (rate_control_mode == VA_RC_CBR) {
794         qp = mfc_context->bit_rate_control_context[slice_type].QpPrimeY;
795         pSliceParameter->slice_qp_delta = qp - pPicParameter->pic_init_qp;
796     }
797
798     /* only support for 8-bit pixel bit-depth */
799     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
800     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
801     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
802     assert(qp >= 0 && qp < 52);
803
804     gen6_mfc_avc_slice_state(ctx, 
805                              pPicParameter,
806                              pSliceParameter,
807                              encode_state, encoder_context,
808                              (rate_control_mode == VA_RC_CBR), qp, slice_batch);
809
810     if ( slice_index == 0) 
811         intel_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
812
813     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
814
815     // slice hander
816     mfc_context->insert_object(ctx, encoder_context,
817                                (unsigned int *)slice_header, ALIGN(slice_header_length_in_bits, 32) >> 5, slice_header_length_in_bits & 0x1f,
818                                5,  /* first 5 bytes are start code + nal unit type */
819                                1, 0, 1, slice_batch);
820
821     dri_bo_map(vme_context->vme_output.bo , 1);
822     msg = (unsigned int *)vme_context->vme_output.bo->virtual;
823
824     if (is_intra) {
825         msg += pSliceParameter->macroblock_address * INTRA_VME_OUTPUT_IN_DWS;
826     } else {
827         msg += pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_DWS;
828         msg += 32; /* the first 32 DWs are MVs */
829         offset = pSliceParameter->macroblock_address * INTER_VME_OUTPUT_IN_BYTES;
830     }
831    
832     for (i = pSliceParameter->macroblock_address; 
833          i < pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks; i++) {
834         int last_mb = (i == (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks - 1) );
835         x = i % width_in_mbs;
836         y = i / width_in_mbs;
837
838         if (is_intra) {
839             assert(msg);
840             gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
841             msg += INTRA_VME_OUTPUT_IN_DWS;
842         } else {
843             if (msg[0] & INTRA_MB_FLAG_MASK) {
844                 gen6_mfc_avc_pak_object_intra(ctx, x, y, last_mb, qp, msg, encoder_context, 0, 0, slice_batch);
845             } else {
846                 gen6_mfc_avc_pak_object_inter(ctx, x, y, last_mb, qp, msg, offset, encoder_context, 0, 0, pSliceParameter->slice_type, slice_batch);
847             }
848
849             msg += INTER_VME_OUTPUT_IN_DWS;
850             offset += INTER_VME_OUTPUT_IN_BYTES;
851         }
852     }
853    
854     dri_bo_unmap(vme_context->vme_output.bo);
855
856     if ( last_slice ) {    
857         mfc_context->insert_object(ctx, encoder_context,
858                                    tail_data, 2, 8,
859                                    2, 1, 1, 0, slice_batch);
860     } else {
861         mfc_context->insert_object(ctx, encoder_context,
862                                    tail_data, 1, 8,
863                                    1, 1, 1, 0, slice_batch);
864     }
865
866     free(slice_header);
867
868 }
869
870 static dri_bo *
871 gen6_mfc_avc_software_batchbuffer(VADriverContextP ctx,
872                                   struct encode_state *encode_state,
873                                   struct intel_encoder_context *encoder_context)
874 {
875     struct i965_driver_data *i965 = i965_driver_data(ctx);
876     struct intel_batchbuffer *batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_BSD, 0);
877     dri_bo *batch_bo = batch->buffer;
878     int i;
879
880     for (i = 0; i < encode_state->num_slice_params_ext; i++) {
881         gen6_mfc_avc_pipeline_slice_programing(ctx, encode_state, encoder_context, i, batch);
882     }
883
884     intel_batchbuffer_align(batch, 8);
885     
886     BEGIN_BCS_BATCH(batch, 2);
887     OUT_BCS_BATCH(batch, 0);
888     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_END);
889     ADVANCE_BCS_BATCH(batch);
890
891     dri_bo_reference(batch_bo);
892     intel_batchbuffer_free(batch);
893
894     return batch_bo;
895 }
896
897 #else
898
899 static void
900 gen6_mfc_batchbuffer_surfaces_input(VADriverContextP ctx,
901                                     struct encode_state *encode_state,
902                                     struct intel_encoder_context *encoder_context)
903
904 {
905     struct gen6_vme_context *vme_context = encoder_context->vme_context;
906     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
907
908     assert(vme_context->vme_output.bo);
909     mfc_context->buffer_suface_setup(ctx,
910                                      &mfc_context->gpe_context,
911                                      &vme_context->vme_output,
912                                      BINDING_TABLE_OFFSET(BIND_IDX_VME_OUTPUT),
913                                      SURFACE_STATE_OFFSET(BIND_IDX_VME_OUTPUT));
914     assert(mfc_context->aux_batchbuffer_surface.bo);
915     mfc_context->buffer_suface_setup(ctx,
916                                      &mfc_context->gpe_context,
917                                      &mfc_context->aux_batchbuffer_surface,
918                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_SLICE_HEADER),
919                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_SLICE_HEADER));
920 }
921
922 static void
923 gen6_mfc_batchbuffer_surfaces_output(VADriverContextP ctx,
924                                      struct encode_state *encode_state,
925                                      struct intel_encoder_context *encoder_context)
926
927 {
928     struct i965_driver_data *i965 = i965_driver_data(ctx);
929     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
930     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
931     int width_in_mbs = pSequenceParameter->picture_width_in_mbs;
932     int height_in_mbs = pSequenceParameter->picture_height_in_mbs;
933     mfc_context->mfc_batchbuffer_surface.num_blocks = width_in_mbs * height_in_mbs + encode_state->num_slice_params_ext * 8 + 1;
934     mfc_context->mfc_batchbuffer_surface.size_block = 16 * CMD_LEN_IN_OWORD; /* 3 OWORDs */
935     mfc_context->mfc_batchbuffer_surface.pitch = 16;
936     mfc_context->mfc_batchbuffer_surface.bo = dri_bo_alloc(i965->intel.bufmgr, 
937                                                            "MFC batchbuffer",
938                                                            mfc_context->mfc_batchbuffer_surface.num_blocks * mfc_context->mfc_batchbuffer_surface.size_block,
939                                                            0x1000);
940     mfc_context->buffer_suface_setup(ctx,
941                                      &mfc_context->gpe_context,
942                                      &mfc_context->mfc_batchbuffer_surface,
943                                      BINDING_TABLE_OFFSET(BIND_IDX_MFC_BATCHBUFFER),
944                                      SURFACE_STATE_OFFSET(BIND_IDX_MFC_BATCHBUFFER));
945 }
946
947 static void
948 gen6_mfc_batchbuffer_surfaces_setup(VADriverContextP ctx, 
949                                     struct encode_state *encode_state,
950                                     struct intel_encoder_context *encoder_context)
951 {
952     gen6_mfc_batchbuffer_surfaces_input(ctx, encode_state, encoder_context);
953     gen6_mfc_batchbuffer_surfaces_output(ctx, encode_state, encoder_context);
954 }
955
956 static void
957 gen6_mfc_batchbuffer_idrt_setup(VADriverContextP ctx, 
958                                 struct encode_state *encode_state,
959                                 struct intel_encoder_context *encoder_context)
960 {
961     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
962     struct gen6_interface_descriptor_data *desc;   
963     int i;
964     dri_bo *bo;
965
966     bo = mfc_context->gpe_context.idrt.bo;
967     dri_bo_map(bo, 1);
968     assert(bo->virtual);
969     desc = bo->virtual;
970
971     for (i = 0; i < mfc_context->gpe_context.num_kernels; i++) {
972         struct i965_kernel *kernel;
973
974         kernel = &mfc_context->gpe_context.kernels[i];
975         assert(sizeof(*desc) == 32);
976
977         /*Setup the descritor table*/
978         memset(desc, 0, sizeof(*desc));
979         desc->desc0.kernel_start_pointer = (kernel->bo->offset >> 6);
980         desc->desc2.sampler_count = 0;
981         desc->desc2.sampler_state_pointer = 0;
982         desc->desc3.binding_table_entry_count = 2;
983         desc->desc3.binding_table_pointer = (BINDING_TABLE_OFFSET(0) >> 5);
984         desc->desc4.constant_urb_entry_read_offset = 0;
985         desc->desc4.constant_urb_entry_read_length = 4;
986                 
987         /*kernel start*/
988         dri_bo_emit_reloc(bo,   
989                           I915_GEM_DOMAIN_INSTRUCTION, 0,
990                           0,
991                           i * sizeof(*desc) + offsetof(struct gen6_interface_descriptor_data, desc0),
992                           kernel->bo);
993         desc++;
994     }
995
996     dri_bo_unmap(bo);
997 }
998
999 static void
1000 gen6_mfc_batchbuffer_constant_setup(VADriverContextP ctx, 
1001                                     struct encode_state *encode_state,
1002                                     struct intel_encoder_context *encoder_context)
1003 {
1004     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1005     
1006     (void)mfc_context;
1007 }
1008
1009 static void
1010 gen6_mfc_batchbuffer_emit_object_command(struct intel_batchbuffer *batch,
1011                                          int index,
1012                                          int head_offset,
1013                                          int batchbuffer_offset,
1014                                          int head_size,
1015                                          int tail_size,
1016                                          int number_mb_cmds,
1017                                          int first_object,
1018                                          int last_object,
1019                                          int last_slice,
1020                                          int mb_x,
1021                                          int mb_y,
1022                                          int width_in_mbs,
1023                                          int qp)
1024 {
1025     BEGIN_BATCH(batch, 12);
1026     
1027     OUT_BATCH(batch, CMD_MEDIA_OBJECT | (12 - 2));
1028     OUT_BATCH(batch, index);
1029     OUT_BATCH(batch, 0);
1030     OUT_BATCH(batch, 0);
1031     OUT_BATCH(batch, 0);
1032     OUT_BATCH(batch, 0);
1033    
1034     /*inline data */
1035     OUT_BATCH(batch, head_offset);
1036     OUT_BATCH(batch, batchbuffer_offset);
1037     OUT_BATCH(batch, 
1038               head_size << 16 |
1039               tail_size);
1040     OUT_BATCH(batch,
1041               number_mb_cmds << 16 |
1042               first_object << 2 |
1043               last_object << 1 |
1044               last_slice);
1045     OUT_BATCH(batch,
1046               mb_y << 8 |
1047               mb_x);
1048     OUT_BATCH(batch,
1049               qp << 16 |
1050               width_in_mbs);
1051
1052     ADVANCE_BATCH(batch);
1053 }
1054
1055 static void
1056 gen6_mfc_avc_batchbuffer_slice_command(VADriverContextP ctx,
1057                                        struct intel_encoder_context *encoder_context,
1058                                        VAEncSliceParameterBufferH264 *slice_param,
1059                                        int head_offset,
1060                                        unsigned short head_size,
1061                                        unsigned short tail_size,
1062                                        int batchbuffer_offset,
1063                                        int qp,
1064                                        int last_slice)
1065 {
1066     struct intel_batchbuffer *batch = encoder_context->base.batch;
1067     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1068     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1069     int total_mbs = slice_param->num_macroblocks;
1070     int number_mb_cmds = 128;
1071     int starting_mb = 0;
1072     int last_object = 0;
1073     int first_object = 1;
1074     int i;
1075     int mb_x, mb_y;
1076     int index = (slice_param->slice_type == SLICE_TYPE_I) ? MFC_BATCHBUFFER_AVC_INTRA : MFC_BATCHBUFFER_AVC_INTER;
1077
1078     for (i = 0; i < total_mbs / number_mb_cmds; i++) {
1079         last_object = (total_mbs - starting_mb) == number_mb_cmds;
1080         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1081         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1082         assert(mb_x <= 255 && mb_y <= 255);
1083
1084         starting_mb += number_mb_cmds;
1085
1086         gen6_mfc_batchbuffer_emit_object_command(batch,
1087                                                  index,
1088                                                  head_offset,
1089                                                  batchbuffer_offset,
1090                                                  head_size,
1091                                                  tail_size,
1092                                                  number_mb_cmds,
1093                                                  first_object,
1094                                                  last_object,
1095                                                  last_slice,
1096                                                  mb_x,
1097                                                  mb_y,
1098                                                  width_in_mbs,
1099                                                  qp);
1100
1101         if (first_object) {
1102             head_offset += head_size;
1103             batchbuffer_offset += head_size;
1104         }
1105
1106         if (last_object) {
1107             head_offset += tail_size;
1108             batchbuffer_offset += tail_size;
1109         }
1110
1111         batchbuffer_offset += number_mb_cmds * CMD_LEN_IN_OWORD;
1112
1113         first_object = 0;
1114     }
1115
1116     if (!last_object) {
1117         last_object = 1;
1118         number_mb_cmds = total_mbs % number_mb_cmds;
1119         mb_x = (slice_param->macroblock_address + starting_mb) % width_in_mbs;
1120         mb_y = (slice_param->macroblock_address + starting_mb) / width_in_mbs;
1121         assert(mb_x <= 255 && mb_y <= 255);
1122         starting_mb += number_mb_cmds;
1123
1124         gen6_mfc_batchbuffer_emit_object_command(batch,
1125                                                  index,
1126                                                  head_offset,
1127                                                  batchbuffer_offset,
1128                                                  head_size,
1129                                                  tail_size,
1130                                                  number_mb_cmds,
1131                                                  first_object,
1132                                                  last_object,
1133                                                  last_slice,
1134                                                  mb_x,
1135                                                  mb_y,
1136                                                  width_in_mbs,
1137                                                  qp);
1138     }
1139 }
1140                           
1141 /*
1142  * return size in Owords (16bytes)
1143  */         
1144 static int
1145 gen6_mfc_avc_batchbuffer_slice(VADriverContextP ctx,
1146                                struct encode_state *encode_state,
1147                                struct intel_encoder_context *encoder_context,
1148                                int slice_index,
1149                                int batchbuffer_offset)
1150 {
1151     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1152     struct intel_batchbuffer *slice_batch = mfc_context->aux_batchbuffer;
1153     VAEncSequenceParameterBufferH264 *pSequenceParameter = (VAEncSequenceParameterBufferH264 *)encode_state->seq_param_ext->buffer;
1154     VAEncPictureParameterBufferH264 *pPicParameter = (VAEncPictureParameterBufferH264 *)encode_state->pic_param_ext->buffer;
1155     VAEncSliceParameterBufferH264 *pSliceParameter = (VAEncSliceParameterBufferH264 *)encode_state->slice_params_ext[slice_index]->buffer; 
1156     int width_in_mbs = (mfc_context->surface_state.width + 15) / 16;
1157     int height_in_mbs = (mfc_context->surface_state.height + 15) / 16;
1158     int last_slice = (pSliceParameter->macroblock_address + pSliceParameter->num_macroblocks) == (width_in_mbs * height_in_mbs);
1159     int qp = pPicParameter->pic_init_qp + pSliceParameter->slice_qp_delta;
1160     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1161     unsigned char *slice_header = NULL;
1162     int slice_header_length_in_bits = 0;
1163     unsigned int tail_data[] = { 0x0, 0x0 };
1164     long head_offset;
1165     int old_used = intel_batchbuffer_used_size(slice_batch), used;
1166     unsigned short head_size, tail_size;
1167     int slice_type = pSliceParameter->slice_type;
1168
1169     if (rate_control_mode == VA_RC_CBR) {
1170         qp = mfc_context->bit_rate_control_context[slice_type].QpPrimeY;
1171         pSliceParameter->slice_qp_delta = qp - pPicParameter->pic_init_qp;
1172     }
1173
1174     /* only support for 8-bit pixel bit-depth */
1175     assert(pSequenceParameter->bit_depth_luma_minus8 == 0);
1176     assert(pSequenceParameter->bit_depth_chroma_minus8 == 0);
1177     assert(pPicParameter->pic_init_qp >= 0 && pPicParameter->pic_init_qp < 52);
1178     assert(qp >= 0 && qp < 52);
1179
1180     head_offset = old_used / 16;
1181     gen6_mfc_avc_slice_state(ctx,
1182                              pPicParameter,
1183                              pSliceParameter,
1184                              encode_state,
1185                              encoder_context,
1186                              (rate_control_mode == VA_RC_CBR),
1187                              qp,
1188                              slice_batch);
1189
1190     if (slice_index == 0)
1191         intel_mfc_avc_pipeline_header_programing(ctx, encode_state, encoder_context, slice_batch);
1192
1193     slice_header_length_in_bits = build_avc_slice_header(pSequenceParameter, pPicParameter, pSliceParameter, &slice_header);
1194
1195     // slice hander
1196     mfc_context->insert_object(ctx,
1197                                encoder_context,
1198                                (unsigned int *)slice_header,
1199                                ALIGN(slice_header_length_in_bits, 32) >> 5,
1200                                slice_header_length_in_bits & 0x1f,
1201                                5,  /* first 5 bytes are start code + nal unit type */
1202                                1,
1203                                0,
1204                                1,
1205                                slice_batch);
1206     free(slice_header);
1207
1208     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1209     used = intel_batchbuffer_used_size(slice_batch);
1210     head_size = (used - old_used) / 16;
1211     old_used = used;
1212
1213     /* tail */
1214     if (last_slice) {    
1215         mfc_context->insert_object(ctx,
1216                                    encoder_context,
1217                                    tail_data,
1218                                    2,
1219                                    8,
1220                                    2,
1221                                    1,
1222                                    1,
1223                                    0,
1224                                    slice_batch);
1225     } else {
1226         mfc_context->insert_object(ctx,
1227                                    encoder_context,
1228                                    tail_data,
1229                                    1,
1230                                    8,
1231                                    1,
1232                                    1,
1233                                    1,
1234                                    0,
1235                                    slice_batch);
1236     }
1237
1238     intel_batchbuffer_align(slice_batch, 16); /* aligned by an Oword */
1239     used = intel_batchbuffer_used_size(slice_batch);
1240     tail_size = (used - old_used) / 16;
1241
1242    
1243     gen6_mfc_avc_batchbuffer_slice_command(ctx,
1244                                            encoder_context,
1245                                            pSliceParameter,
1246                                            head_offset,
1247                                            head_size,
1248                                            tail_size,
1249                                            batchbuffer_offset,
1250                                            qp,
1251                                            last_slice);
1252
1253     return head_size + tail_size + pSliceParameter->num_macroblocks * CMD_LEN_IN_OWORD;
1254 }
1255
1256 static void
1257 gen6_mfc_avc_batchbuffer_pipeline(VADriverContextP ctx,
1258                                   struct encode_state *encode_state,
1259                                   struct intel_encoder_context *encoder_context)
1260 {
1261     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1262     struct intel_batchbuffer *batch = encoder_context->base.batch;
1263     int i, size, offset = 0;
1264     intel_batchbuffer_start_atomic(batch, 0x4000); 
1265     gen6_gpe_pipeline_setup(ctx, &mfc_context->gpe_context, batch);
1266
1267     for ( i = 0; i < encode_state->num_slice_params_ext; i++) {
1268         size = gen6_mfc_avc_batchbuffer_slice(ctx, encode_state, encoder_context, i, offset);
1269         offset += size;
1270     }
1271
1272     intel_batchbuffer_end_atomic(batch);
1273     intel_batchbuffer_flush(batch);
1274 }
1275
1276 static void
1277 gen6_mfc_build_avc_batchbuffer(VADriverContextP ctx, 
1278                                struct encode_state *encode_state,
1279                                struct intel_encoder_context *encoder_context)
1280 {
1281     gen6_mfc_batchbuffer_surfaces_setup(ctx, encode_state, encoder_context);
1282     gen6_mfc_batchbuffer_idrt_setup(ctx, encode_state, encoder_context);
1283     gen6_mfc_batchbuffer_constant_setup(ctx, encode_state, encoder_context);
1284     gen6_mfc_avc_batchbuffer_pipeline(ctx, encode_state, encoder_context);
1285 }
1286
1287 static dri_bo *
1288 gen6_mfc_avc_hardware_batchbuffer(VADriverContextP ctx,
1289                                   struct encode_state *encode_state,
1290                                   struct intel_encoder_context *encoder_context)
1291 {
1292     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1293
1294     gen6_mfc_build_avc_batchbuffer(ctx, encode_state, encoder_context);
1295     dri_bo_reference(mfc_context->mfc_batchbuffer_surface.bo);
1296
1297     return mfc_context->mfc_batchbuffer_surface.bo;
1298 }
1299
1300 #endif
1301
1302
1303 static void
1304 gen6_mfc_avc_pipeline_programing(VADriverContextP ctx,
1305                                  struct encode_state *encode_state,
1306                                  struct intel_encoder_context *encoder_context)
1307 {
1308     struct intel_batchbuffer *batch = encoder_context->base.batch;
1309     dri_bo *slice_batch_bo;
1310
1311     if ( intel_mfc_interlace_check(ctx, encode_state, encoder_context) ) {
1312         fprintf(stderr, "Current VA driver don't support interlace mode!\n");
1313         assert(0);
1314         return; 
1315     }
1316
1317 #if __SOFTWARE__
1318     slice_batch_bo = gen6_mfc_avc_software_batchbuffer(ctx, encode_state, encoder_context);
1319 #else
1320     slice_batch_bo = gen6_mfc_avc_hardware_batchbuffer(ctx, encode_state, encoder_context);
1321 #endif
1322
1323     // begin programing
1324     intel_batchbuffer_start_atomic_bcs(batch, 0x4000); 
1325     intel_batchbuffer_emit_mi_flush(batch);
1326     
1327     // picture level programing
1328     gen6_mfc_avc_pipeline_picture_programing(ctx, encode_state, encoder_context);
1329
1330     BEGIN_BCS_BATCH(batch, 2);
1331     OUT_BCS_BATCH(batch, MI_BATCH_BUFFER_START | (1 << 8));
1332     OUT_BCS_RELOC(batch,
1333                   slice_batch_bo,
1334                   I915_GEM_DOMAIN_COMMAND, 0, 
1335                   0);
1336     ADVANCE_BCS_BATCH(batch);
1337
1338     // end programing
1339     intel_batchbuffer_end_atomic(batch);
1340
1341     dri_bo_unreference(slice_batch_bo);
1342 }
1343
1344 static VAStatus
1345 gen6_mfc_avc_encode_picture(VADriverContextP ctx, 
1346                             struct encode_state *encode_state,
1347                             struct intel_encoder_context *encoder_context)
1348 {
1349     struct gen6_mfc_context *mfc_context = encoder_context->mfc_context;
1350     unsigned int rate_control_mode = encoder_context->rate_control_mode;
1351     int current_frame_bits_size;
1352     int sts;
1353  
1354     for (;;) {
1355         gen6_mfc_init(ctx, encode_state, encoder_context);
1356         intel_mfc_avc_prepare(ctx, encode_state, encoder_context);
1357         /*Programing bcs pipeline*/
1358         gen6_mfc_avc_pipeline_programing(ctx, encode_state, encoder_context);   //filling the pipeline
1359         gen6_mfc_run(ctx, encode_state, encoder_context);
1360         if (rate_control_mode == VA_RC_CBR /*|| rate_control_mode == VA_RC_VBR*/) {
1361             gen6_mfc_stop(ctx, encode_state, encoder_context, &current_frame_bits_size);
1362             sts = intel_mfc_brc_postpack(encode_state, mfc_context, current_frame_bits_size);
1363             if (sts == BRC_NO_HRD_VIOLATION) {
1364                 intel_mfc_hrd_context_update(encode_state, mfc_context);
1365                 break;
1366             }
1367             else if (sts == BRC_OVERFLOW_WITH_MIN_QP || sts == BRC_UNDERFLOW_WITH_MAX_QP) {
1368                 if (!mfc_context->hrd.violation_noted) {
1369                     fprintf(stderr, "Unrepairable %s!\n", (sts == BRC_OVERFLOW_WITH_MIN_QP)? "overflow": "underflow");
1370                     mfc_context->hrd.violation_noted = 1;
1371                 }
1372                 return VA_STATUS_SUCCESS;
1373             }
1374         } else {
1375             break;
1376         }
1377     }
1378
1379     return VA_STATUS_SUCCESS;
1380 }
1381
1382 VAStatus
1383 gen6_mfc_pipeline(VADriverContextP ctx,
1384                   VAProfile profile,
1385                   struct encode_state *encode_state,
1386                   struct intel_encoder_context *encoder_context)
1387 {
1388     VAStatus vaStatus;
1389
1390     switch (profile) {
1391     case VAProfileH264Baseline:
1392     case VAProfileH264Main:
1393     case VAProfileH264High:
1394         vaStatus = gen6_mfc_avc_encode_picture(ctx, encode_state, encoder_context);
1395         break;
1396
1397         /* FIXME: add for other profile */
1398     default:
1399         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1400         break;
1401     }
1402
1403     return vaStatus;
1404 }
1405
1406 void
1407 gen6_mfc_context_destroy(void *context)
1408 {
1409     struct gen6_mfc_context *mfc_context = context;
1410     int i;
1411
1412     dri_bo_unreference(mfc_context->post_deblocking_output.bo);
1413     mfc_context->post_deblocking_output.bo = NULL;
1414
1415     dri_bo_unreference(mfc_context->pre_deblocking_output.bo);
1416     mfc_context->pre_deblocking_output.bo = NULL;
1417
1418     dri_bo_unreference(mfc_context->uncompressed_picture_source.bo);
1419     mfc_context->uncompressed_picture_source.bo = NULL;
1420
1421     dri_bo_unreference(mfc_context->mfc_indirect_pak_bse_object.bo); 
1422     mfc_context->mfc_indirect_pak_bse_object.bo = NULL;
1423
1424     for (i = 0; i < NUM_MFC_DMV_BUFFERS; i++){
1425         dri_bo_unreference(mfc_context->direct_mv_buffers[i].bo);
1426         mfc_context->direct_mv_buffers[i].bo = NULL;
1427     }
1428
1429     dri_bo_unreference(mfc_context->intra_row_store_scratch_buffer.bo);
1430     mfc_context->intra_row_store_scratch_buffer.bo = NULL;
1431
1432     dri_bo_unreference(mfc_context->macroblock_status_buffer.bo);
1433     mfc_context->macroblock_status_buffer.bo = NULL;
1434
1435     dri_bo_unreference(mfc_context->deblocking_filter_row_store_scratch_buffer.bo);
1436     mfc_context->deblocking_filter_row_store_scratch_buffer.bo = NULL;
1437
1438     dri_bo_unreference(mfc_context->bsd_mpc_row_store_scratch_buffer.bo);
1439     mfc_context->bsd_mpc_row_store_scratch_buffer.bo = NULL;
1440
1441
1442     for (i = 0; i < MAX_MFC_REFERENCE_SURFACES; i++){
1443         dri_bo_unreference(mfc_context->reference_surfaces[i].bo);
1444         mfc_context->reference_surfaces[i].bo = NULL;  
1445     }
1446
1447     i965_gpe_context_destroy(&mfc_context->gpe_context);
1448
1449     dri_bo_unreference(mfc_context->mfc_batchbuffer_surface.bo);
1450     mfc_context->mfc_batchbuffer_surface.bo = NULL;
1451
1452     dri_bo_unreference(mfc_context->aux_batchbuffer_surface.bo);
1453     mfc_context->aux_batchbuffer_surface.bo = NULL;
1454
1455     if (mfc_context->aux_batchbuffer)
1456         intel_batchbuffer_free(mfc_context->aux_batchbuffer);
1457
1458     mfc_context->aux_batchbuffer = NULL;
1459
1460     free(mfc_context);
1461 }
1462
1463 Bool gen6_mfc_context_init(VADriverContextP ctx, struct intel_encoder_context *encoder_context)
1464 {
1465     struct gen6_mfc_context *mfc_context = calloc(1, sizeof(struct gen6_mfc_context));
1466
1467     mfc_context->gpe_context.surface_state_binding_table.length = (SURFACE_STATE_PADDED_SIZE + sizeof(unsigned int)) * MAX_MEDIA_SURFACES_GEN6;
1468
1469     mfc_context->gpe_context.idrt.max_entries = MAX_GPE_KERNELS;
1470     mfc_context->gpe_context.idrt.entry_size = sizeof(struct gen6_interface_descriptor_data);
1471
1472     mfc_context->gpe_context.curbe.length = 32 * 4;
1473
1474     mfc_context->gpe_context.vfe_state.max_num_threads = 60 - 1;
1475     mfc_context->gpe_context.vfe_state.num_urb_entries = 16;
1476     mfc_context->gpe_context.vfe_state.gpgpu_mode = 0;
1477     mfc_context->gpe_context.vfe_state.urb_entry_size = 59 - 1;
1478     mfc_context->gpe_context.vfe_state.curbe_allocation_size = 37 - 1;
1479
1480     i965_gpe_load_kernels(ctx,
1481                           &mfc_context->gpe_context,
1482                           gen6_mfc_kernels,
1483                           NUM_MFC_KERNEL);
1484
1485     mfc_context->pipe_mode_select = gen6_mfc_pipe_mode_select;
1486     mfc_context->set_surface_state = gen6_mfc_surface_state;
1487     mfc_context->ind_obj_base_addr_state = gen6_mfc_ind_obj_base_addr_state;
1488     mfc_context->avc_img_state = gen6_mfc_avc_img_state;
1489     mfc_context->avc_qm_state = gen6_mfc_avc_qm_state;
1490     mfc_context->avc_fqm_state = gen6_mfc_avc_fqm_state;
1491     mfc_context->insert_object = gen6_mfc_avc_insert_object;
1492     mfc_context->buffer_suface_setup = i965_gpe_buffer_suface_setup;
1493
1494     encoder_context->mfc_context = mfc_context;
1495     encoder_context->mfc_context_destroy = gen6_mfc_context_destroy;
1496     encoder_context->mfc_pipeline = gen6_mfc_pipeline;
1497     encoder_context->mfc_brc_prepare = intel_mfc_brc_prepare;
1498
1499     return True;
1500 }