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