OSDN Git Service

i965_drv: add support for per-codec max resolution
[android-x86/hardware-intel-common-vaapi.git] / src / i965_drv_video.c
1 /*
2  * Copyright ?2009 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  *    Xiang Haihao <haihao.xiang@intel.com>
26  *    Zou Nan hai <nanhai.zou@intel.com>
27  *
28  */
29
30 #include "sysdeps.h"
31 #include <unistd.h>
32 #include <dlfcn.h>
33
34 #ifdef HAVE_VA_X11
35 # include "i965_output_dri.h"
36 #endif
37
38 #ifdef HAVE_VA_WAYLAND
39 # include "i965_output_wayland.h"
40 #endif
41
42 #include "intel_version.h"
43 #include "intel_driver.h"
44 #include "intel_memman.h"
45 #include "intel_batchbuffer.h"
46 #include "i965_defines.h"
47 #include "i965_drv_video.h"
48 #include "i965_decoder.h"
49 #include "i965_encoder.h"
50
51 #include "gen9_vp9_encapi.h"
52
53 #define CONFIG_ID_OFFSET                0x01000000
54 #define CONTEXT_ID_OFFSET               0x02000000
55 #define SURFACE_ID_OFFSET               0x04000000
56 #define BUFFER_ID_OFFSET                0x08000000
57 #define IMAGE_ID_OFFSET                 0x0a000000
58 #define SUBPIC_ID_OFFSET                0x10000000
59
60 #define HAS_MPEG2_DECODING(ctx)  ((ctx)->codec_info->has_mpeg2_decoding && \
61                                   (ctx)->intel.has_bsd)
62
63 #define HAS_MPEG2_ENCODING(ctx)  ((ctx)->codec_info->has_mpeg2_encoding && \
64                                   (ctx)->intel.has_bsd)
65
66 #define HAS_H264_DECODING(ctx)  ((ctx)->codec_info->has_h264_decoding && \
67                                  (ctx)->intel.has_bsd)
68
69 #define HAS_H264_ENCODING(ctx)  ((ctx)->codec_info->has_h264_encoding && \
70                                  (ctx)->intel.has_bsd)
71
72 #define HAS_LP_H264_ENCODING(ctx)  ((ctx)->codec_info->has_lp_h264_encoding && \
73                                     (ctx)->intel.has_bsd)
74
75 #define HAS_VC1_DECODING(ctx)   ((ctx)->codec_info->has_vc1_decoding && \
76                                  (ctx)->intel.has_bsd)
77
78 #define HAS_JPEG_DECODING(ctx)  ((ctx)->codec_info->has_jpeg_decoding && \
79                                  (ctx)->intel.has_bsd)
80                                                                   
81 #define HAS_JPEG_ENCODING(ctx)  ((ctx)->codec_info->has_jpeg_encoding && \
82                                  (ctx)->intel.has_bsd)      
83
84 #define HAS_VPP(ctx)    ((ctx)->codec_info->has_vpp)
85
86 #define HAS_ACCELERATED_GETIMAGE(ctx)   ((ctx)->codec_info->has_accelerated_getimage)
87
88 #define HAS_ACCELERATED_PUTIMAGE(ctx)   ((ctx)->codec_info->has_accelerated_putimage)
89
90 #define HAS_TILED_SURFACE(ctx) ((ctx)->codec_info->has_tiled_surface)
91
92 #define HAS_VP8_DECODING(ctx)   ((ctx)->codec_info->has_vp8_decoding && \
93                                  (ctx)->intel.has_bsd)
94
95 #define HAS_VP8_ENCODING(ctx)   ((ctx)->codec_info->has_vp8_encoding && \
96                                  (ctx)->intel.has_bsd)
97
98 #define HAS_H264_MVC_DECODING(ctx) \
99     (HAS_H264_DECODING(ctx) && (ctx)->codec_info->h264_mvc_dec_profiles)
100
101 #define HAS_H264_MVC_DECODING_PROFILE(ctx, profile)                     \
102     (HAS_H264_MVC_DECODING(ctx) &&                                      \
103      ((ctx)->codec_info->h264_mvc_dec_profiles & (1U << profile)))
104
105 #define HAS_H264_MVC_ENCODING(ctx)  ((ctx)->codec_info->has_h264_mvc_encoding && \
106                                      (ctx)->intel.has_bsd)
107
108 #define HAS_HEVC_DECODING(ctx)          ((ctx)->codec_info->has_hevc_decoding && \
109                                          (ctx)->intel.has_bsd)
110
111 #define HAS_HEVC_ENCODING(ctx)          ((ctx)->codec_info->has_hevc_encoding && \
112                                          (ctx)->intel.has_bsd)
113
114 #define HAS_VP9_DECODING(ctx)          ((ctx)->codec_info->has_vp9_decoding && \
115                                          (ctx)->intel.has_bsd)
116
117 #define HAS_VP9_DECODING_PROFILE(ctx, profile)                     \
118     (HAS_VP9_DECODING(ctx) &&                                      \
119      ((ctx)->codec_info->vp9_dec_profiles & (1U << (profile - VAProfileVP9Profile0))))
120
121 #define HAS_HEVC10_DECODING(ctx)        ((ctx)->codec_info->has_hevc10_decoding && \
122                                          (ctx)->intel.has_bsd)
123
124 #define HAS_VPP_P010(ctx)        ((ctx)->codec_info->has_vpp_p010 && \
125                                          (ctx)->intel.has_bsd)
126
127 #define HAS_VP9_ENCODING(ctx)          ((ctx)->codec_info->has_vp9_encoding && \
128                                          (ctx)->intel.has_bsd)
129
130 static int get_sampling_from_fourcc(unsigned int fourcc);
131
132 /* Check whether we are rendering to X11 (VA/X11 or VA/GLX API) */
133 #define IS_VA_X11(ctx) \
134     (((ctx)->display_type & VA_DISPLAY_MAJOR_MASK) == VA_DISPLAY_X11)
135
136 /* Check whether we are rendering to Wayland */
137 #define IS_VA_WAYLAND(ctx) \
138     (((ctx)->display_type & VA_DISPLAY_MAJOR_MASK) == VA_DISPLAY_WAYLAND)
139
140 #define I965_BIT        1
141 #define I965_2BITS      (I965_BIT << 1)
142 #define I965_4BITS      (I965_BIT << 2)
143 #define I965_8BITS      (I965_BIT << 3)
144 #define I965_16BITS     (I965_BIT << 4)
145 #define I965_32BITS     (I965_BIT << 5)
146
147 #define PLANE_0         0
148 #define PLANE_1         1
149 #define PLANE_2         2
150
151 #define OFFSET_0        0
152 #define OFFSET_4        4
153 #define OFFSET_8        8
154 #define OFFSET_16       16
155 #define OFFSET_24       24
156
157 /* hfactor, vfactor, num_planes, bpp[], num_components, components[] */
158 #define I_NV12  2, 2, 2, {I965_8BITS, I965_4BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_1, OFFSET_8} }
159 #define I_I420  2, 2, 3, {I965_8BITS, I965_2BITS, I965_2BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_2, OFFSET_0} }
160 #define I_IYUV  I_I420
161 #define I_IMC3  I_I420
162 #define I_YV12  2, 2, 3, {I965_8BITS, I965_2BITS, I965_2BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_2, OFFSET_0}, {PLANE_1, OFFSET_0} }
163 #define I_IMC1  I_YV12
164
165 #define I_P010  2, 2, 2, {I965_16BITS, I965_8BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_1, OFFSET_16} }
166
167 #define I_422H  2, 1, 3, {I965_8BITS, I965_4BITS, I965_4BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_2, OFFSET_0} }
168 #define I_422V  1, 2, 3, {I965_8BITS, I965_4BITS, I965_4BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_2, OFFSET_0} }
169 #define I_YV16  2, 1, 3, {I965_8BITS, I965_4BITS, I965_4BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_2, OFFSET_0}, {PLANE_1, OFFSET_0} }
170 #define I_YUY2  2, 1, 1, {I965_16BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_24} }
171 #define I_UYVY  2, 1, 1, {I965_16BITS}, 3, { {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_16} }
172
173 #define I_444P  1, 1, 3, {I965_8BITS, I965_8BITS, I965_8BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_2, OFFSET_0} }
174
175 #define I_411P  4, 1, 3, {I965_8BITS, I965_2BITS, I965_2BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_1, OFFSET_0}, {PLANE_2, OFFSET_0} }
176
177 #define I_Y800  1, 1, 1, {I965_8BITS}, 1, { {PLANE_0, OFFSET_0} }
178
179 #define I_RGBA  1, 1, 1, {I965_32BITS}, 4, { {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_16}, {PLANE_0, OFFSET_24} }
180 #define I_RGBX  1, 1, 1, {I965_32BITS}, 3, { {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_16} }
181 #define I_BGRA  1, 1, 1, {I965_32BITS}, 4, { {PLANE_0, OFFSET_16}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_24} }
182 #define I_BGRX  1, 1, 1, {I965_32BITS}, 3, { {PLANE_0, OFFSET_16}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_0} }
183
184 #define I_ARGB  1, 1, 1, {I965_32BITS}, 4, { {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_16}, {PLANE_0, OFFSET_24}, {PLANE_0, OFFSET_0} }
185 #define I_ABGR  1, 1, 1, {I965_32BITS}, 4, { {PLANE_0, OFFSET_24}, {PLANE_0, OFFSET_16}, {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_0} }
186
187 #define I_IA88  1, 1, 1, {I965_16BITS}, 2, { {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_8} }
188 #define I_AI88  1, 1, 1, {I965_16BITS}, 2, { {PLANE_0, OFFSET_8}, {PLANE_0, OFFSET_0} }
189
190 #define I_IA44  1, 1, 1, {I965_8BITS}, 2, { {PLANE_0, OFFSET_0}, {PLANE_0, OFFSET_4} }
191 #define I_AI44  1, 1, 1, {I965_8BITS}, 2, { {PLANE_0, OFFSET_4}, {PLANE_0, OFFSET_0} }
192
193 /* flag */
194 #define I_S             1
195 #define I_I             2
196 #define I_SI            (I_S | I_I)
197
198 #define DEF_FOUCC_INFO(FOURCC, FORMAT, SUB, FLAG)       { VA_FOURCC_##FOURCC, I965_COLOR_##FORMAT, SUBSAMPLE_##SUB, FLAG, I_##FOURCC }
199 #define DEF_YUV(FOURCC, SUB, FLAG)                      DEF_FOUCC_INFO(FOURCC, YUV, SUB, FLAG)
200 #define DEF_RGB(FOURCC, SUB, FLAG)                      DEF_FOUCC_INFO(FOURCC, RGB, SUB, FLAG)
201 #define DEF_INDEX(FOURCC, SUB, FLAG)                    DEF_FOUCC_INFO(FOURCC, INDEX, SUB, FLAG)
202
203 static const i965_fourcc_info i965_fourcc_infos[] = {
204     DEF_YUV(NV12, YUV420, I_SI),
205     DEF_YUV(I420, YUV420, I_SI),
206     DEF_YUV(IYUV, YUV420, I_S),
207     DEF_YUV(IMC3, YUV420, I_S),
208     DEF_YUV(YV12, YUV420, I_SI),
209     DEF_YUV(IMC1, YUV420, I_S),
210
211     DEF_YUV(P010, YUV420, I_SI),
212
213     DEF_YUV(422H, YUV422H, I_SI),
214     DEF_YUV(422V, YUV422V, I_S),
215     DEF_YUV(YV16, YUV422H, I_S),
216     DEF_YUV(YUY2, YUV422H, I_SI),
217     DEF_YUV(UYVY, YUV422H, I_SI),
218
219     DEF_YUV(444P, YUV444, I_S),
220
221     DEF_YUV(411P, YUV411, I_S),
222
223     DEF_YUV(Y800, YUV400, I_S),
224
225     DEF_RGB(RGBA, RGBX, I_SI),
226     DEF_RGB(RGBX, RGBX, I_SI),
227     DEF_RGB(BGRA, RGBX, I_SI),
228     DEF_RGB(BGRX, RGBX, I_SI),
229
230     DEF_RGB(ARGB, RGBX, I_I),
231     DEF_RGB(ABGR, RGBX, I_I),
232
233     DEF_INDEX(IA88, RGBX, I_I),
234     DEF_INDEX(AI88, RGBX, I_I),
235
236     DEF_INDEX(IA44, RGBX, I_I),
237     DEF_INDEX(AI44, RGBX, I_I)
238 };
239
240 const i965_fourcc_info *
241 get_fourcc_info(unsigned int fourcc)
242 {
243     unsigned int i;
244
245     for (i = 0; i < ARRAY_ELEMS(i965_fourcc_infos); i++) {
246         const i965_fourcc_info * const info = &i965_fourcc_infos[i];
247
248         if (info->fourcc == fourcc)
249             return info;
250     }
251
252     return NULL;
253 }
254
255 static int
256 get_bpp_from_fourcc(unsigned int fourcc)
257 {
258     const i965_fourcc_info *info = get_fourcc_info(fourcc);
259     unsigned int i = 0;
260     unsigned int bpp = 0;
261
262     if (!info)
263         return 0;
264
265     for (i = 0; i < info->num_planes; i++)
266         bpp += info->bpp[i];
267
268     return bpp;
269 }
270
271 enum {
272     I965_SURFACETYPE_RGBA = 1,
273     I965_SURFACETYPE_YUV,
274     I965_SURFACETYPE_INDEXED
275 };
276
277 /* List of supported display attributes */
278 static const VADisplayAttribute i965_display_attributes[] = {
279     {
280         VADisplayAttribBrightness,
281         -100, 100, DEFAULT_BRIGHTNESS,
282         VA_DISPLAY_ATTRIB_GETTABLE | VA_DISPLAY_ATTRIB_SETTABLE
283     },
284
285     {
286         VADisplayAttribContrast,
287         0, 100, DEFAULT_CONTRAST,
288         VA_DISPLAY_ATTRIB_GETTABLE | VA_DISPLAY_ATTRIB_SETTABLE
289     },
290
291     {
292         VADisplayAttribHue,
293         -180, 180, DEFAULT_HUE,
294         VA_DISPLAY_ATTRIB_GETTABLE | VA_DISPLAY_ATTRIB_SETTABLE
295     },
296
297     {
298         VADisplayAttribSaturation,
299         0, 100, DEFAULT_SATURATION,
300         VA_DISPLAY_ATTRIB_GETTABLE | VA_DISPLAY_ATTRIB_SETTABLE
301     },
302
303     {
304         VADisplayAttribRotation,
305         0, 3, VA_ROTATION_NONE,
306         VA_DISPLAY_ATTRIB_GETTABLE|VA_DISPLAY_ATTRIB_SETTABLE
307     },
308 };
309
310 /* List of supported image formats */
311 typedef struct {
312     unsigned int        type;
313     VAImageFormat       va_format;
314 } i965_image_format_map_t;
315
316 static const i965_image_format_map_t
317 i965_image_formats_map[I965_MAX_IMAGE_FORMATS + 1] = {
318     { I965_SURFACETYPE_YUV,
319       { VA_FOURCC_YV12, VA_LSB_FIRST, 12, } },
320     { I965_SURFACETYPE_YUV,
321       { VA_FOURCC_I420, VA_LSB_FIRST, 12, } },
322     { I965_SURFACETYPE_YUV,
323       { VA_FOURCC_NV12, VA_LSB_FIRST, 12, } },
324     { I965_SURFACETYPE_YUV,
325       { VA_FOURCC_YUY2, VA_LSB_FIRST, 16, } },
326     { I965_SURFACETYPE_YUV,
327       { VA_FOURCC_UYVY, VA_LSB_FIRST, 16, } },
328     { I965_SURFACETYPE_YUV,
329       { VA_FOURCC_422H, VA_LSB_FIRST, 16, } },
330     { I965_SURFACETYPE_RGBA,
331       { VA_FOURCC_RGBX, VA_LSB_FIRST, 32, 24, 0x000000ff, 0x0000ff00, 0x00ff0000 } },
332     { I965_SURFACETYPE_RGBA,
333       { VA_FOURCC_BGRX, VA_LSB_FIRST, 32, 24, 0x00ff0000, 0x0000ff00, 0x000000ff } },
334     { I965_SURFACETYPE_YUV,
335       { VA_FOURCC_P010, VA_LSB_FIRST, 24, } },
336 };
337
338 /* List of supported subpicture formats */
339 typedef struct {
340     unsigned int        type;
341     unsigned int        format;
342     VAImageFormat       va_format;
343     unsigned int        va_flags;
344 } i965_subpic_format_map_t;
345
346 #define COMMON_SUBPICTURE_FLAGS                 \
347     (VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD| \
348      VA_SUBPICTURE_GLOBAL_ALPHA)
349
350 static const i965_subpic_format_map_t
351 i965_subpic_formats_map[I965_MAX_SUBPIC_FORMATS + 1] = {
352     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_P4A4_UNORM,
353       { VA_FOURCC_IA44, VA_MSB_FIRST, 8, },
354       COMMON_SUBPICTURE_FLAGS },
355     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_A4P4_UNORM,
356       { VA_FOURCC_AI44, VA_MSB_FIRST, 8, },
357       COMMON_SUBPICTURE_FLAGS },
358     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_P8A8_UNORM,
359       { VA_FOURCC_IA88, VA_MSB_FIRST, 16, },
360       COMMON_SUBPICTURE_FLAGS },
361     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_A8P8_UNORM,
362       { VA_FOURCC_AI88, VA_MSB_FIRST, 16, },
363       COMMON_SUBPICTURE_FLAGS },
364      { I965_SURFACETYPE_RGBA, I965_SURFACEFORMAT_B8G8R8A8_UNORM,
365       { VA_FOURCC_BGRA, VA_LSB_FIRST, 32,
366         32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 },
367       COMMON_SUBPICTURE_FLAGS },
368     { I965_SURFACETYPE_RGBA, I965_SURFACEFORMAT_R8G8B8A8_UNORM,
369       { VA_FOURCC_RGBA, VA_LSB_FIRST, 32,
370         32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 },
371       COMMON_SUBPICTURE_FLAGS },
372 };
373
374 static const i965_subpic_format_map_t *
375 get_subpic_format(const VAImageFormat *va_format)
376 {
377     unsigned int i;
378     for (i = 0; i965_subpic_formats_map[i].type != 0; i++) {
379         const i965_subpic_format_map_t * const m = &i965_subpic_formats_map[i];
380         if (m->va_format.fourcc == va_format->fourcc &&
381             (m->type == I965_SURFACETYPE_RGBA ?
382              (m->va_format.byte_order == va_format->byte_order &&
383               m->va_format.red_mask   == va_format->red_mask   &&
384               m->va_format.green_mask == va_format->green_mask &&
385               m->va_format.blue_mask  == va_format->blue_mask  &&
386               m->va_format.alpha_mask == va_format->alpha_mask) : 1))
387             return m;
388     }
389     return NULL;
390 }
391
392 /* Checks whether the surface is in busy state */
393 static bool
394 is_surface_busy(struct i965_driver_data *i965,
395     struct object_surface *obj_surface)
396 {
397     assert(obj_surface != NULL);
398
399     if (obj_surface->locked_image_id != VA_INVALID_ID)
400         return true;
401     if (obj_surface->derived_image_id != VA_INVALID_ID)
402         return true;
403     return false;
404 }
405
406 /* Checks whether the image is in busy state */
407 static bool
408 is_image_busy(struct i965_driver_data *i965, struct object_image *obj_image, VASurfaceID surface)
409 {
410     struct object_buffer *obj_buffer;
411
412     assert(obj_image != NULL);
413
414     if (obj_image->derived_surface != VA_INVALID_ID &&
415         obj_image->derived_surface == surface)
416         return true;
417
418     obj_buffer = BUFFER(obj_image->image.buf);
419     if (obj_buffer && obj_buffer->export_refcount > 0)
420         return true;
421     return false;
422 }
423
424 #define I965_PACKED_HEADER_BASE         0
425 #define I965_SEQ_PACKED_HEADER_BASE     0
426 #define I965_SEQ_PACKED_HEADER_END      2
427 #define I965_PIC_PACKED_HEADER_BASE     2
428 #define I965_PACKED_MISC_HEADER_BASE    4
429
430 int
431 va_enc_packed_type_to_idx(int packed_type)
432 {
433     int idx = 0;
434
435     if (packed_type & VAEncPackedHeaderMiscMask) {
436         idx = I965_PACKED_MISC_HEADER_BASE;
437         packed_type = (~VAEncPackedHeaderMiscMask & packed_type);
438         ASSERT_RET(packed_type > 0, 0);
439         idx += (packed_type - 1);
440     } else {
441         idx = I965_PACKED_HEADER_BASE;
442
443         switch (packed_type) {
444         case VAEncPackedHeaderSequence:
445             idx = I965_SEQ_PACKED_HEADER_BASE + 0;
446             break;
447
448         case VAEncPackedHeaderPicture:
449             idx = I965_PIC_PACKED_HEADER_BASE + 0;
450             break;
451
452         case VAEncPackedHeaderSlice:
453             idx = I965_PIC_PACKED_HEADER_BASE + 1;
454             break;
455
456         default:
457             /* Should not get here */
458             ASSERT_RET(0, 0);
459             break;
460         }
461     }
462
463     ASSERT_RET(idx < 5, 0);
464     return idx;
465 }
466
467 #define CALL_VTABLE(vawr, status, param) status = (vawr->vtable->param)
468
469 static VAStatus
470 i965_surface_wrapper(VADriverContextP ctx, VASurfaceID surface)
471 {
472     struct i965_driver_data *i965 = i965_driver_data(ctx);
473     struct object_surface *obj_surface = SURFACE(surface);
474     VAStatus va_status = VA_STATUS_SUCCESS;
475
476     if (!obj_surface) {
477         return VA_STATUS_ERROR_INVALID_SURFACE;
478     }
479
480     if (obj_surface->wrapper_surface != VA_INVALID_ID) {
481         /* the wrapped surface already exists. just return it */
482        return va_status;
483     }
484
485     if (obj_surface->fourcc == 0)
486         i965_check_alloc_surface_bo(ctx, obj_surface,
487                                     1, VA_FOURCC_NV12, SUBSAMPLE_YUV420);
488
489     /*
490      * TBD: Support more surface formats.
491      * Currently only NV12 is support as NV12 is used by decoding.
492      */
493     if (obj_surface->fourcc != VA_FOURCC_NV12 )
494         return VA_STATUS_ERROR_INVALID_PARAMETER;
495
496     if ((i965->wrapper_pdrvctx == NULL) ||
497         (obj_surface->bo == NULL))
498         return VA_STATUS_ERROR_INVALID_PARAMETER;
499
500     {
501         int fd_handle;
502         VASurfaceAttrib attrib_list[2];
503         VASurfaceAttribExternalBuffers buffer_descriptor;
504         VAGenericID wrapper_surface;
505
506         if (drm_intel_bo_gem_export_to_prime(obj_surface->bo, &fd_handle) != 0)
507             return VA_STATUS_ERROR_OPERATION_FAILED;
508
509         obj_surface->exported_primefd = fd_handle;
510
511         memset(&attrib_list, 0, sizeof(attrib_list));
512         memset(&buffer_descriptor, 0, sizeof(buffer_descriptor));
513
514         attrib_list[0].type = VASurfaceAttribExternalBufferDescriptor;
515         attrib_list[0].flags = VA_SURFACE_ATTRIB_SETTABLE;
516         attrib_list[0].value.value.p = &buffer_descriptor;
517         attrib_list[0].value.type = VAGenericValueTypePointer;
518
519         attrib_list[1].type = VASurfaceAttribMemoryType;
520         attrib_list[1].flags = VA_SURFACE_ATTRIB_SETTABLE;
521         attrib_list[1].value.value.i = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME;
522         attrib_list[1].value.type = VAGenericValueTypeInteger;
523
524         buffer_descriptor.num_buffers = 1;
525         buffer_descriptor.num_planes = 2;
526         buffer_descriptor.width = obj_surface->orig_width;
527         buffer_descriptor.height = obj_surface->orig_height;
528         buffer_descriptor.pixel_format = obj_surface->fourcc;
529         buffer_descriptor.data_size = obj_surface->size;
530         buffer_descriptor.pitches[0] = obj_surface->width;
531         buffer_descriptor.pitches[1] = obj_surface->cb_cr_pitch;
532         buffer_descriptor.offsets[0] = 0;
533         buffer_descriptor.offsets[1] = obj_surface->width * obj_surface->height;
534         buffer_descriptor.buffers = (void *)&fd_handle;
535
536         CALL_VTABLE(i965->wrapper_pdrvctx, va_status,
537                     vaCreateSurfaces2(i965->wrapper_pdrvctx,
538                                       VA_RT_FORMAT_YUV420,
539                                       obj_surface->orig_width,
540                                       obj_surface->orig_height,
541                                       &wrapper_surface, 1,
542                                       attrib_list, 2));
543
544         if (va_status == VA_STATUS_SUCCESS) {
545             obj_surface->wrapper_surface = wrapper_surface;
546         } else {
547             /* This needs to be checked */
548             va_status = VA_STATUS_ERROR_OPERATION_FAILED;
549         }
550         return va_status;
551     }
552
553 }
554
555 VAStatus 
556 i965_QueryConfigProfiles(VADriverContextP ctx,
557                          VAProfile *profile_list,       /* out */
558                          int *num_profiles)             /* out */
559 {
560     struct i965_driver_data * const i965 = i965_driver_data(ctx);
561     int i = 0;
562
563     if (HAS_MPEG2_DECODING(i965) ||
564         HAS_MPEG2_ENCODING(i965)) {
565         profile_list[i++] = VAProfileMPEG2Simple;
566         profile_list[i++] = VAProfileMPEG2Main;
567     }
568
569     if (HAS_H264_DECODING(i965) ||
570         HAS_H264_ENCODING(i965) ||
571         HAS_LP_H264_ENCODING(i965)) {
572         profile_list[i++] = VAProfileH264ConstrainedBaseline;
573         profile_list[i++] = VAProfileH264Main;
574         profile_list[i++] = VAProfileH264High;
575     }
576     if (HAS_H264_MVC_DECODING_PROFILE(i965, VAProfileH264MultiviewHigh) ||
577         HAS_H264_MVC_ENCODING(i965))
578         profile_list[i++] = VAProfileH264MultiviewHigh;
579     if (HAS_H264_MVC_DECODING_PROFILE(i965, VAProfileH264StereoHigh) ||
580         HAS_H264_MVC_ENCODING(i965))
581         profile_list[i++] = VAProfileH264StereoHigh;
582
583     if (HAS_VC1_DECODING(i965)) {
584         profile_list[i++] = VAProfileVC1Simple;
585         profile_list[i++] = VAProfileVC1Main;
586         profile_list[i++] = VAProfileVC1Advanced;
587     }
588
589     if (HAS_VPP(i965)) {
590         profile_list[i++] = VAProfileNone;
591     }
592
593     if (HAS_JPEG_DECODING(i965) ||
594         HAS_JPEG_ENCODING(i965)) {
595         profile_list[i++] = VAProfileJPEGBaseline;
596     }
597
598     if (HAS_VP8_DECODING(i965) ||
599         HAS_VP8_ENCODING(i965)) {
600         profile_list[i++] = VAProfileVP8Version0_3;
601     }
602
603     if (HAS_HEVC_DECODING(i965)||
604         HAS_HEVC_ENCODING(i965)) {
605         profile_list[i++] = VAProfileHEVCMain;
606     }
607
608     if (HAS_HEVC10_DECODING(i965)) {
609         profile_list[i++] = VAProfileHEVCMain10;
610     }
611
612     if(HAS_VP9_DECODING_PROFILE(i965, VAProfileVP9Profile0) ||
613         HAS_VP9_ENCODING(i965)) {
614         profile_list[i++] = VAProfileVP9Profile0;
615     }
616
617     if(HAS_VP9_DECODING_PROFILE(i965, VAProfileVP9Profile2)) {
618         profile_list[i++] = VAProfileVP9Profile2;
619     }
620
621     if (i965->wrapper_pdrvctx) {
622         VAProfile wrapper_list[4];
623         int wrapper_num;
624         VADriverContextP pdrvctx;
625         VAStatus va_status;
626
627         pdrvctx = i965->wrapper_pdrvctx;
628         CALL_VTABLE(pdrvctx, va_status,
629                     vaQueryConfigProfiles(pdrvctx,
630                                           wrapper_list, &wrapper_num));
631
632         if (va_status == VA_STATUS_SUCCESS) {
633             int j;
634             for (j = 0; j < wrapper_num; j++)
635                 if (wrapper_list[j] != VAProfileNone)
636                     profile_list[i++] = wrapper_list[j];
637         }
638     }
639
640     /* If the assert fails then I965_MAX_PROFILES needs to be bigger */
641     ASSERT_RET(i <= I965_MAX_PROFILES, VA_STATUS_ERROR_OPERATION_FAILED);
642     *num_profiles = i;
643
644     return VA_STATUS_SUCCESS;
645 }
646
647 VAStatus 
648 i965_QueryConfigEntrypoints(VADriverContextP ctx,
649                             VAProfile profile,
650                             VAEntrypoint *entrypoint_list,      /* out */
651                             int *num_entrypoints)               /* out */
652 {
653     struct i965_driver_data * const i965 = i965_driver_data(ctx);
654     int n = 0;
655
656     switch (profile) {
657     case VAProfileMPEG2Simple:
658     case VAProfileMPEG2Main:
659         if (HAS_MPEG2_DECODING(i965))
660             entrypoint_list[n++] = VAEntrypointVLD;
661
662         if (HAS_MPEG2_ENCODING(i965))
663             entrypoint_list[n++] = VAEntrypointEncSlice;
664
665         break;
666
667     case VAProfileH264ConstrainedBaseline:
668     case VAProfileH264Main:
669     case VAProfileH264High:
670         if (HAS_H264_DECODING(i965))
671             entrypoint_list[n++] = VAEntrypointVLD;
672
673         if (HAS_H264_ENCODING(i965))
674             entrypoint_list[n++] = VAEntrypointEncSlice;
675
676         if (HAS_LP_H264_ENCODING(i965))
677             entrypoint_list[n++] = VAEntrypointEncSliceLP;
678
679         break;
680    case VAProfileH264MultiviewHigh:
681    case VAProfileH264StereoHigh:
682        if (HAS_H264_MVC_DECODING_PROFILE(i965, profile))
683             entrypoint_list[n++] = VAEntrypointVLD;
684
685        if (HAS_H264_MVC_ENCODING(i965))
686             entrypoint_list[n++] = VAEntrypointEncSlice;
687         break;
688
689     case VAProfileVC1Simple:
690     case VAProfileVC1Main:
691     case VAProfileVC1Advanced:
692         if (HAS_VC1_DECODING(i965))
693             entrypoint_list[n++] = VAEntrypointVLD;
694         break;
695
696     case VAProfileNone:
697         if (HAS_VPP(i965))
698             entrypoint_list[n++] = VAEntrypointVideoProc;
699         break;
700
701     case VAProfileJPEGBaseline:
702         if (HAS_JPEG_DECODING(i965))
703             entrypoint_list[n++] = VAEntrypointVLD;
704         
705         if (HAS_JPEG_ENCODING(i965))
706             entrypoint_list[n++] = VAEntrypointEncPicture;
707         break;
708
709     case VAProfileVP8Version0_3:
710         if (HAS_VP8_DECODING(i965))
711             entrypoint_list[n++] = VAEntrypointVLD;
712         
713         if (HAS_VP8_ENCODING(i965))
714             entrypoint_list[n++] = VAEntrypointEncSlice;
715
716         break;
717
718     case VAProfileHEVCMain:
719         if (HAS_HEVC_DECODING(i965))
720             entrypoint_list[n++] = VAEntrypointVLD;
721
722         if (HAS_HEVC_ENCODING(i965))
723             entrypoint_list[n++] = VAEntrypointEncSlice;
724
725         break;
726
727     case VAProfileHEVCMain10:
728         if (HAS_HEVC10_DECODING(i965))
729             entrypoint_list[n++] = VAEntrypointVLD;
730
731         break;
732
733     case VAProfileVP9Profile0:
734     case VAProfileVP9Profile2:
735         if(HAS_VP9_DECODING_PROFILE(i965, profile))
736             entrypoint_list[n++] = VAEntrypointVLD;
737
738         if (HAS_VP9_ENCODING(i965) && (profile == VAProfileVP9Profile0))
739             entrypoint_list[n++] = VAEntrypointEncSlice;
740
741         if(profile == VAProfileVP9Profile0) {
742           if (i965->wrapper_pdrvctx) {
743               VAStatus va_status = VA_STATUS_SUCCESS;
744               VADriverContextP pdrvctx = i965->wrapper_pdrvctx;
745
746               CALL_VTABLE(pdrvctx, va_status,
747                           vaQueryConfigEntrypoints(pdrvctx, profile,
748                                                    entrypoint_list,
749                                                    num_entrypoints));
750               return va_status;
751           }
752         }
753
754         break;
755
756     default:
757         break;
758     }
759
760     /* If the assert fails then I965_MAX_ENTRYPOINTS needs to be bigger */
761     ASSERT_RET(n <= I965_MAX_ENTRYPOINTS, VA_STATUS_ERROR_OPERATION_FAILED);
762     *num_entrypoints = n;
763     return n > 0 ? VA_STATUS_SUCCESS : VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
764 }
765
766 static VAStatus
767 i965_validate_config(VADriverContextP ctx, VAProfile profile,
768     VAEntrypoint entrypoint)
769 {
770     struct i965_driver_data * const i965 = i965_driver_data(ctx);
771     VAStatus va_status;
772
773     /* Validate profile & entrypoint */
774     switch (profile) {
775     case VAProfileMPEG2Simple:
776     case VAProfileMPEG2Main:
777         if ((HAS_MPEG2_DECODING(i965) && entrypoint == VAEntrypointVLD) ||
778             (HAS_MPEG2_ENCODING(i965) && entrypoint == VAEntrypointEncSlice)) {
779             va_status = VA_STATUS_SUCCESS;
780         } else {
781             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
782         }
783         break;
784
785     case VAProfileH264ConstrainedBaseline:
786     case VAProfileH264Main:
787     case VAProfileH264High:
788         if ((HAS_H264_DECODING(i965) && entrypoint == VAEntrypointVLD) ||
789             (HAS_H264_ENCODING(i965) && entrypoint == VAEntrypointEncSlice) ||
790             (HAS_LP_H264_ENCODING(i965) && entrypoint == VAEntrypointEncSliceLP)) {
791             va_status = VA_STATUS_SUCCESS;
792         } else {
793             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
794         }
795         break;
796
797     case VAProfileVC1Simple:
798     case VAProfileVC1Main:
799     case VAProfileVC1Advanced:
800         if (HAS_VC1_DECODING(i965) && entrypoint == VAEntrypointVLD) {
801             va_status = VA_STATUS_SUCCESS;
802         } else {
803             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
804         }
805         break;
806
807     case VAProfileNone:
808         if (HAS_VPP(i965) && VAEntrypointVideoProc == entrypoint) {
809             va_status = VA_STATUS_SUCCESS;
810         } else {
811             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
812         }
813         break;
814
815     case VAProfileJPEGBaseline:
816         if ((HAS_JPEG_DECODING(i965) && entrypoint == VAEntrypointVLD) ||
817             (HAS_JPEG_ENCODING(i965) && entrypoint == VAEntrypointEncPicture)) {
818             va_status = VA_STATUS_SUCCESS;
819         } else {
820             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
821         }
822         break;
823
824     case VAProfileVP8Version0_3:
825         if ((HAS_VP8_DECODING(i965) && entrypoint == VAEntrypointVLD) ||
826             (HAS_VP8_ENCODING(i965) && entrypoint == VAEntrypointEncSlice)) {
827             va_status = VA_STATUS_SUCCESS;
828         } else {
829             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
830         }
831         break;
832
833     case VAProfileH264MultiviewHigh:
834     case VAProfileH264StereoHigh:
835         if ((HAS_H264_MVC_DECODING_PROFILE(i965, profile) &&
836              entrypoint == VAEntrypointVLD) ||
837             (HAS_H264_MVC_ENCODING(i965) && entrypoint == VAEntrypointEncSlice)) {
838             va_status = VA_STATUS_SUCCESS;
839         } else {
840             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
841         }
842
843         break;
844
845     case VAProfileHEVCMain:
846         if ((HAS_HEVC_DECODING(i965) && (entrypoint == VAEntrypointVLD))||
847             (HAS_HEVC_ENCODING(i965) && (entrypoint == VAEntrypointEncSlice)))
848             va_status = VA_STATUS_SUCCESS;
849         else
850             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
851
852         break;
853
854     case VAProfileHEVCMain10:
855         if (HAS_HEVC10_DECODING(i965) && (entrypoint == VAEntrypointVLD))
856             va_status = VA_STATUS_SUCCESS;
857         else
858             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
859
860         break;
861
862     case VAProfileVP9Profile0:
863     case VAProfileVP9Profile2:
864         if ((HAS_VP9_DECODING_PROFILE(i965, profile)) && (entrypoint == VAEntrypointVLD))
865             va_status = VA_STATUS_SUCCESS;
866        else if ((HAS_VP9_ENCODING(i965)) && (entrypoint == VAEntrypointEncSlice))
867             va_status = VA_STATUS_SUCCESS;
868         else if ((profile == VAProfileVP9Profile0) && i965->wrapper_pdrvctx)
869             va_status = VA_STATUS_SUCCESS;
870         else
871             va_status = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
872         break;
873
874     default:
875         va_status = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
876         break;
877     }
878     return va_status;
879 }
880
881 static uint32_t
882 i965_get_default_chroma_formats(VADriverContextP ctx, VAProfile profile,
883     VAEntrypoint entrypoint)
884 {
885     struct i965_driver_data * const i965 = i965_driver_data(ctx);
886     uint32_t chroma_formats = VA_RT_FORMAT_YUV420;
887
888     switch (profile) {
889     case VAProfileH264ConstrainedBaseline:
890     case VAProfileH264Main:
891     case VAProfileH264High:
892         if (HAS_H264_DECODING(i965) && entrypoint == VAEntrypointVLD)
893             chroma_formats |= i965->codec_info->h264_dec_chroma_formats;
894         break;
895
896     case VAProfileH264MultiviewHigh:
897     case VAProfileH264StereoHigh:
898         if (HAS_H264_MVC_DECODING(i965) && entrypoint == VAEntrypointVLD)
899             chroma_formats |= i965->codec_info->h264_dec_chroma_formats;
900         break;
901
902     case VAProfileJPEGBaseline:
903         if (HAS_JPEG_DECODING(i965) && entrypoint == VAEntrypointVLD)
904             chroma_formats |= i965->codec_info->jpeg_dec_chroma_formats;
905         if (HAS_JPEG_ENCODING(i965) && entrypoint == VAEntrypointEncPicture)
906             chroma_formats |= i965->codec_info->jpeg_enc_chroma_formats;
907         break;
908
909     case VAProfileHEVCMain10:
910         if (HAS_HEVC10_DECODING(i965) && entrypoint == VAEntrypointVLD)
911             chroma_formats |= i965->codec_info->hevc_dec_chroma_formats;
912         break;
913
914     case VAProfileNone:
915         if(HAS_VPP_P010(i965))
916             chroma_formats |= VA_RT_FORMAT_YUV420_10BPP;
917         break;
918
919     case VAProfileVP9Profile0:
920     case VAProfileVP9Profile2:
921         if (HAS_VP9_DECODING_PROFILE(i965, profile) && entrypoint == VAEntrypointVLD)
922             chroma_formats |= i965->codec_info->vp9_dec_chroma_formats;
923         break;
924
925     default:
926         break;
927     }
928     return chroma_formats;
929 }
930
931 VAStatus 
932 i965_GetConfigAttributes(VADriverContextP ctx,
933                          VAProfile profile,
934                          VAEntrypoint entrypoint,
935                          VAConfigAttrib *attrib_list,  /* in/out */
936                          int num_attribs)
937 {
938     VAStatus va_status;
939     int i;
940
941     va_status = i965_validate_config(ctx, profile, entrypoint);
942     if (va_status != VA_STATUS_SUCCESS)
943         return va_status;
944
945     /* Other attributes don't seem to be defined */
946     /* What to do if we don't know the attribute? */
947     for (i = 0; i < num_attribs; i++) {
948         attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
949         switch (attrib_list[i].type) {
950         case VAConfigAttribRTFormat:
951             attrib_list[i].value = i965_get_default_chroma_formats(ctx,
952                 profile, entrypoint);
953             break;
954
955         case VAConfigAttribRateControl:
956             if (entrypoint == VAEntrypointEncSlice) {
957                 attrib_list[i].value = VA_RC_CQP;
958
959                 if (profile != VAProfileMPEG2Main &&
960                     profile != VAProfileMPEG2Simple)
961                     attrib_list[i].value |= VA_RC_CBR;
962
963                 if (profile == VAProfileVP9Profile0)
964                     attrib_list[i].value |= VA_RC_VBR;
965
966                 break;
967             } else if (entrypoint == VAEntrypointEncSliceLP) {
968                 struct i965_driver_data * const i965 = i965_driver_data(ctx);
969
970                 /* Support low power encoding for H.264 only by now */
971                 if (profile == VAProfileH264ConstrainedBaseline ||
972                     profile == VAProfileH264Main ||
973                     profile == VAProfileH264High)
974                     attrib_list[i].value = i965->codec_info->lp_h264_brc_mode;
975                 else
976                     attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
977             } else
978                 attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
979
980             break;
981
982         case VAConfigAttribEncPackedHeaders:
983             if (entrypoint == VAEntrypointEncSlice ||
984                 entrypoint == VAEntrypointEncSliceLP) {
985                 attrib_list[i].value = VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_MISC;
986                 if (profile == VAProfileH264ConstrainedBaseline ||
987                     profile == VAProfileH264Main ||
988                     profile == VAProfileH264High ||
989                     profile == VAProfileH264StereoHigh ||
990                     profile == VAProfileH264MultiviewHigh ||
991                     profile == VAProfileHEVCMain) {
992                     attrib_list[i].value |= (VA_ENC_PACKED_HEADER_RAW_DATA |
993                                              VA_ENC_PACKED_HEADER_SLICE);
994                 }
995                 else if (profile == VAProfileVP9Profile0)
996                     attrib_list[i].value = VA_ENC_PACKED_HEADER_RAW_DATA;
997                 break;
998             }
999             else if (entrypoint == VAEntrypointEncPicture) {
1000                 if (profile == VAProfileJPEGBaseline)
1001                     attrib_list[i].value = VA_ENC_PACKED_HEADER_RAW_DATA;
1002             }
1003             break;
1004
1005         case VAConfigAttribEncMaxRefFrames:
1006             if (entrypoint == VAEntrypointEncSlice)
1007                 attrib_list[i].value = (1 << 16) | (1 << 0);
1008             else if (entrypoint == VAEntrypointEncSliceLP) {
1009                 /* Don't support B frame for low power mode */
1010                 if (profile == VAProfileH264ConstrainedBaseline ||
1011                     profile == VAProfileH264Main ||
1012                     profile == VAProfileH264High)
1013                     attrib_list[i].value = (1 << 0);
1014                 else
1015                     attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
1016             }
1017
1018             break;
1019
1020         case VAConfigAttribEncQualityRange:
1021             if (entrypoint == VAEntrypointEncSlice ||
1022                 entrypoint == VAEntrypointEncSliceLP) {
1023                 attrib_list[i].value = 1;
1024                 if (profile == VAProfileH264ConstrainedBaseline ||
1025                     profile == VAProfileH264Main ||
1026                     profile == VAProfileH264High )
1027                     attrib_list[i].value = ENCODER_QUALITY_RANGE;
1028                 break;
1029             }
1030             break;
1031     
1032         case VAConfigAttribEncJPEG:
1033             if( entrypoint == VAEntrypointEncPicture) {
1034                 VAConfigAttribValEncJPEG *configVal = (VAConfigAttribValEncJPEG*)&(attrib_list[i].value);
1035                 (configVal->bits).arithmatic_coding_mode = 0; // Huffman coding is used
1036                 (configVal->bits).progressive_dct_mode = 0;   // Only Sequential DCT is supported
1037                 (configVal->bits).non_interleaved_mode = 1;   // Support both interleaved and non-interleaved
1038                 (configVal->bits).differential_mode = 0;      // Baseline DCT is non-differential 
1039                 (configVal->bits).max_num_components = 3;     // Only 3 components supported
1040                 (configVal->bits).max_num_scans = 1;          // Only 1 scan per frame
1041                 (configVal->bits).max_num_huffman_tables = 3; // Max 3 huffman tables
1042                 (configVal->bits).max_num_quantization_tables = 3; // Max 3 quantization tables
1043             }
1044             break;
1045
1046         case VAConfigAttribDecSliceMode:
1047             attrib_list[i].value = VA_DEC_SLICE_MODE_NORMAL;
1048             break;
1049
1050         case VAConfigAttribEncROI:
1051             if ((entrypoint == VAEntrypointEncSliceLP) &&
1052                 (profile == VAProfileH264ConstrainedBaseline ||
1053                  profile == VAProfileH264Main ||
1054                  profile == VAProfileH264High))
1055                 attrib_list[i].value = 3;
1056             else
1057                 attrib_list[i].value = 0;
1058
1059             break;
1060
1061         default:
1062             /* Do nothing */
1063             attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
1064             break;
1065         }
1066     }
1067
1068     return VA_STATUS_SUCCESS;
1069 }
1070
1071 static void 
1072 i965_destroy_config(struct object_heap *heap, struct object_base *obj)
1073 {
1074     object_heap_free(heap, obj);
1075 }
1076
1077 static VAConfigAttrib *
1078 i965_lookup_config_attribute(struct object_config *obj_config,
1079     VAConfigAttribType type)
1080 {
1081     int i;
1082
1083     for (i = 0; i < obj_config->num_attribs; i++) {
1084         VAConfigAttrib * const attrib = &obj_config->attrib_list[i];
1085         if (attrib->type == type)
1086             return attrib;
1087     }
1088     return NULL;
1089 }
1090
1091 static VAStatus
1092 i965_append_config_attribute(struct object_config *obj_config,
1093     const VAConfigAttrib *new_attrib)
1094 {
1095     VAConfigAttrib *attrib;
1096
1097     if (obj_config->num_attribs >= I965_MAX_CONFIG_ATTRIBUTES)
1098         return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
1099
1100     attrib = &obj_config->attrib_list[obj_config->num_attribs++];
1101     attrib->type = new_attrib->type;
1102     attrib->value = new_attrib->value;
1103     return VA_STATUS_SUCCESS;
1104 }
1105
1106 static VAStatus
1107 i965_ensure_config_attribute(struct object_config *obj_config,
1108     const VAConfigAttrib *new_attrib)
1109 {
1110     VAConfigAttrib *attrib;
1111
1112     /* Check for existing attributes */
1113     attrib = i965_lookup_config_attribute(obj_config, new_attrib->type);
1114     if (attrib) {
1115         /* Update existing attribute */
1116         attrib->value = new_attrib->value;
1117         return VA_STATUS_SUCCESS;
1118     }
1119     return i965_append_config_attribute(obj_config, new_attrib);
1120 }
1121
1122 VAStatus 
1123 i965_CreateConfig(VADriverContextP ctx,
1124                   VAProfile profile,
1125                   VAEntrypoint entrypoint,
1126                   VAConfigAttrib *attrib_list,
1127                   int num_attribs,
1128                   VAConfigID *config_id)        /* out */
1129 {
1130     struct i965_driver_data * const i965 = i965_driver_data(ctx);
1131     struct object_config *obj_config;
1132     int configID;
1133     int i;
1134     VAStatus vaStatus;
1135
1136     vaStatus = i965_validate_config(ctx, profile, entrypoint);
1137
1138     if (VA_STATUS_SUCCESS != vaStatus) {
1139         return vaStatus;
1140     }
1141
1142     configID = NEW_CONFIG_ID();
1143     obj_config = CONFIG(configID);
1144
1145     if (NULL == obj_config) {
1146         vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
1147         return vaStatus;
1148     }
1149
1150     obj_config->profile = profile;
1151     obj_config->entrypoint = entrypoint;
1152     obj_config->num_attribs = 0;
1153     obj_config->wrapper_config = VA_INVALID_ID;
1154
1155     for (i = 0; i < num_attribs; i++) {
1156         vaStatus = i965_ensure_config_attribute(obj_config, &attrib_list[i]);
1157         if (vaStatus != VA_STATUS_SUCCESS)
1158             break;
1159     }
1160
1161     if (vaStatus == VA_STATUS_SUCCESS) {
1162         VAConfigAttrib attrib, *attrib_found;
1163         attrib.type = VAConfigAttribRTFormat;
1164         attrib.value = i965_get_default_chroma_formats(ctx, profile, entrypoint);
1165         attrib_found = i965_lookup_config_attribute(obj_config, attrib.type);
1166         if (!attrib_found || !attrib_found->value)
1167             vaStatus = i965_append_config_attribute(obj_config, &attrib);
1168         else if (!(attrib_found->value & attrib.value))
1169             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT;
1170     }
1171
1172     if ((vaStatus == VA_STATUS_SUCCESS) &&
1173         (profile == VAProfileVP9Profile0) &&
1174         (entrypoint == VAEntrypointVLD) &&
1175         !HAS_VP9_DECODING(i965)) {
1176
1177         if (i965->wrapper_pdrvctx) {
1178             VAGenericID wrapper_config;
1179
1180             CALL_VTABLE(i965->wrapper_pdrvctx, vaStatus,
1181                         vaCreateConfig(i965->wrapper_pdrvctx, profile,
1182                                        entrypoint, attrib_list,
1183                                        num_attribs, &wrapper_config));
1184
1185             if (vaStatus == VA_STATUS_SUCCESS)
1186                 obj_config->wrapper_config = wrapper_config;
1187         }
1188     }
1189
1190     /* Error recovery */
1191     if (VA_STATUS_SUCCESS != vaStatus) {
1192         i965_destroy_config(&i965->config_heap, (struct object_base *)obj_config);
1193     } else {
1194         *config_id = configID;
1195     }
1196
1197     return vaStatus;
1198 }
1199
1200 VAStatus 
1201 i965_DestroyConfig(VADriverContextP ctx, VAConfigID config_id)
1202 {
1203     struct i965_driver_data *i965 = i965_driver_data(ctx);
1204     struct object_config *obj_config = CONFIG(config_id);
1205     VAStatus vaStatus;
1206
1207     if (NULL == obj_config) {
1208         vaStatus = VA_STATUS_ERROR_INVALID_CONFIG;
1209         return vaStatus;
1210     }
1211
1212     if ((obj_config->wrapper_config != VA_INVALID_ID) &&
1213         i965->wrapper_pdrvctx) {
1214         CALL_VTABLE(i965->wrapper_pdrvctx, vaStatus,
1215                     vaDestroyConfig(i965->wrapper_pdrvctx,
1216                                     obj_config->wrapper_config));
1217         obj_config->wrapper_config = VA_INVALID_ID;
1218     }
1219
1220     i965_destroy_config(&i965->config_heap, (struct object_base *)obj_config);
1221     return VA_STATUS_SUCCESS;
1222 }
1223
1224 VAStatus i965_QueryConfigAttributes(VADriverContextP ctx,
1225                                     VAConfigID config_id,
1226                                     VAProfile *profile,                 /* out */
1227                                     VAEntrypoint *entrypoint,           /* out */
1228                                     VAConfigAttrib *attrib_list,        /* out */
1229                                     int *num_attribs)                   /* out */
1230 {
1231     struct i965_driver_data *i965 = i965_driver_data(ctx);
1232     struct object_config *obj_config = CONFIG(config_id);
1233     VAStatus vaStatus = VA_STATUS_SUCCESS;
1234     int i;
1235
1236     ASSERT_RET(obj_config, VA_STATUS_ERROR_INVALID_CONFIG);
1237     *profile = obj_config->profile;
1238     *entrypoint = obj_config->entrypoint;
1239     *num_attribs = obj_config->num_attribs;
1240
1241     for(i = 0; i < obj_config->num_attribs; i++) {
1242         attrib_list[i] = obj_config->attrib_list[i];
1243     }
1244
1245     return vaStatus;
1246 }
1247
1248 void
1249 i965_destroy_surface_storage(struct object_surface *obj_surface)
1250 {
1251     if (!obj_surface)
1252         return;
1253
1254     dri_bo_unreference(obj_surface->bo);
1255     obj_surface->bo = NULL;
1256
1257     if (obj_surface->free_private_data != NULL) {
1258         obj_surface->free_private_data(&obj_surface->private_data);
1259         obj_surface->private_data = NULL;
1260     }
1261 }
1262
1263 static void 
1264 i965_destroy_surface(struct object_heap *heap, struct object_base *obj)
1265 {
1266     struct object_surface *obj_surface = (struct object_surface *)obj;
1267
1268     i965_destroy_surface_storage(obj_surface);
1269     object_heap_free(heap, obj);
1270 }
1271
1272 static VAStatus
1273 i965_surface_native_memory(VADriverContextP ctx,
1274                            struct object_surface *obj_surface,
1275                            int format,
1276                            int expected_fourcc)
1277 {
1278     struct i965_driver_data *i965 = i965_driver_data(ctx);
1279     int tiling = HAS_TILED_SURFACE(i965);
1280
1281     if (!expected_fourcc)
1282         return VA_STATUS_SUCCESS;
1283
1284     // todo, should we disable tiling for 422 format?
1285     if (expected_fourcc == VA_FOURCC_I420 ||
1286         expected_fourcc == VA_FOURCC_IYUV ||
1287         expected_fourcc == VA_FOURCC_YV12 ||
1288         expected_fourcc == VA_FOURCC_YV16)
1289         tiling = 0;
1290
1291     return i965_check_alloc_surface_bo(ctx, obj_surface, tiling, expected_fourcc, get_sampling_from_fourcc(expected_fourcc));
1292 }
1293     
1294 static VAStatus
1295 i965_suface_external_memory(VADriverContextP ctx,
1296                             struct object_surface *obj_surface,
1297                             int external_memory_type,
1298                             VASurfaceAttribExternalBuffers *memory_attibute,
1299                             int index)
1300 {
1301     struct i965_driver_data *i965 = i965_driver_data(ctx);
1302
1303     if (!memory_attibute ||
1304         !memory_attibute->buffers ||
1305         index > memory_attibute->num_buffers)
1306         return VA_STATUS_ERROR_INVALID_PARAMETER;
1307
1308     ASSERT_RET(obj_surface->orig_width == memory_attibute->width, VA_STATUS_ERROR_INVALID_PARAMETER);
1309     ASSERT_RET(obj_surface->orig_height == memory_attibute->height, VA_STATUS_ERROR_INVALID_PARAMETER);
1310     ASSERT_RET(memory_attibute->num_planes >= 1, VA_STATUS_ERROR_INVALID_PARAMETER);
1311
1312     obj_surface->fourcc = memory_attibute->pixel_format;
1313     obj_surface->width = memory_attibute->pitches[0];
1314     obj_surface->size = memory_attibute->data_size;
1315
1316     if (memory_attibute->num_planes == 1)
1317         obj_surface->height = memory_attibute->data_size / obj_surface->width;
1318     else 
1319         obj_surface->height = memory_attibute->offsets[1] / obj_surface->width;
1320
1321     obj_surface->x_cb_offset = 0; /* X offset is always 0 */
1322     obj_surface->x_cr_offset = 0;
1323
1324     switch (obj_surface->fourcc) {
1325     case VA_FOURCC_NV12:
1326     case VA_FOURCC_P010:
1327         ASSERT_RET(memory_attibute->num_planes == 2, VA_STATUS_ERROR_INVALID_PARAMETER);
1328         ASSERT_RET(memory_attibute->pitches[0] == memory_attibute->pitches[1], VA_STATUS_ERROR_INVALID_PARAMETER);
1329
1330         obj_surface->subsampling = SUBSAMPLE_YUV420;
1331         obj_surface->y_cb_offset = obj_surface->height;
1332         obj_surface->y_cr_offset = obj_surface->height;
1333         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1334         obj_surface->cb_cr_height = obj_surface->orig_height / 2;
1335         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1336
1337         break;
1338
1339     case VA_FOURCC_YV12:
1340     case VA_FOURCC_IMC1:
1341         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1342         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1343
1344         obj_surface->subsampling = SUBSAMPLE_YUV420;
1345         obj_surface->y_cr_offset = obj_surface->height;
1346         obj_surface->y_cb_offset = memory_attibute->offsets[2] / obj_surface->width;
1347         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1348         obj_surface->cb_cr_height = obj_surface->orig_height / 2;
1349         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1350         
1351         break;
1352
1353     case VA_FOURCC_I420:
1354     case VA_FOURCC_IYUV:
1355     case VA_FOURCC_IMC3:
1356         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1357         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1358
1359         obj_surface->subsampling = SUBSAMPLE_YUV420;
1360         obj_surface->y_cb_offset = obj_surface->height;
1361         obj_surface->y_cr_offset = memory_attibute->offsets[2] / obj_surface->width;
1362         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1363         obj_surface->cb_cr_height = obj_surface->orig_height / 2;
1364         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1365
1366         break;
1367
1368     case VA_FOURCC_YUY2:
1369     case VA_FOURCC_UYVY:
1370         ASSERT_RET(memory_attibute->num_planes == 1, VA_STATUS_ERROR_INVALID_PARAMETER);
1371
1372         obj_surface->subsampling = SUBSAMPLE_YUV422H;
1373         obj_surface->y_cb_offset = 0;
1374         obj_surface->y_cr_offset = 0;
1375         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1376         obj_surface->cb_cr_height = obj_surface->orig_height;
1377         obj_surface->cb_cr_pitch = memory_attibute->pitches[0];
1378
1379         break;
1380
1381     case VA_FOURCC_RGBA:
1382     case VA_FOURCC_RGBX:
1383     case VA_FOURCC_BGRA:
1384     case VA_FOURCC_BGRX:
1385         ASSERT_RET(memory_attibute->num_planes == 1, VA_STATUS_ERROR_INVALID_PARAMETER);
1386
1387         obj_surface->subsampling = SUBSAMPLE_RGBX;
1388         obj_surface->y_cb_offset = 0;
1389         obj_surface->y_cr_offset = 0;
1390         obj_surface->cb_cr_width = 0;
1391         obj_surface->cb_cr_height = 0;
1392         obj_surface->cb_cr_pitch = 0;
1393
1394         break;
1395
1396     case VA_FOURCC_Y800: /* monochrome surface */
1397         ASSERT_RET(memory_attibute->num_planes == 1, VA_STATUS_ERROR_INVALID_PARAMETER);
1398         
1399         obj_surface->subsampling = SUBSAMPLE_YUV400;
1400         obj_surface->y_cb_offset = 0;
1401         obj_surface->y_cr_offset = 0;
1402         obj_surface->cb_cr_width = 0;
1403         obj_surface->cb_cr_height = 0;
1404         obj_surface->cb_cr_pitch = 0;
1405
1406         break;
1407
1408     case VA_FOURCC_411P:
1409         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1410         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1411
1412         obj_surface->subsampling = SUBSAMPLE_YUV411;
1413         obj_surface->y_cb_offset = 0;
1414         obj_surface->y_cr_offset = 0;
1415         obj_surface->cb_cr_width = obj_surface->orig_width / 4;
1416         obj_surface->cb_cr_height = obj_surface->orig_height;
1417         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1418
1419         break;
1420
1421     case VA_FOURCC_422H:
1422         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1423         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1424
1425         obj_surface->subsampling = SUBSAMPLE_YUV422H;
1426         obj_surface->y_cb_offset = obj_surface->height;
1427         obj_surface->y_cr_offset = memory_attibute->offsets[2] / obj_surface->width;
1428         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1429         obj_surface->cb_cr_height = obj_surface->orig_height;
1430         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1431
1432         break;
1433
1434     case VA_FOURCC_YV16:
1435         assert(memory_attibute->num_planes == 3);
1436         assert(memory_attibute->pitches[1] == memory_attibute->pitches[2]);
1437
1438         obj_surface->subsampling = SUBSAMPLE_YUV422H;
1439         obj_surface->y_cr_offset = memory_attibute->offsets[1] / obj_surface->width;
1440         obj_surface->y_cb_offset = memory_attibute->offsets[2] / obj_surface->width;
1441         obj_surface->cb_cr_width = obj_surface->orig_width / 2;
1442         obj_surface->cb_cr_height = obj_surface->orig_height;
1443         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1444
1445         break;
1446
1447     case VA_FOURCC_422V:
1448         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1449         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1450
1451         obj_surface->subsampling = SUBSAMPLE_YUV422H;
1452         obj_surface->y_cb_offset = obj_surface->height;
1453         obj_surface->y_cr_offset = memory_attibute->offsets[2] / obj_surface->width;
1454         obj_surface->cb_cr_width = obj_surface->orig_width;
1455         obj_surface->cb_cr_height = obj_surface->orig_height / 2;
1456         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1457
1458         break;
1459
1460     case VA_FOURCC_444P:
1461         ASSERT_RET(memory_attibute->num_planes == 3, VA_STATUS_ERROR_INVALID_PARAMETER);
1462         ASSERT_RET(memory_attibute->pitches[1] == memory_attibute->pitches[2], VA_STATUS_ERROR_INVALID_PARAMETER);
1463
1464         obj_surface->subsampling = SUBSAMPLE_YUV444;
1465         obj_surface->y_cb_offset = obj_surface->height;
1466         obj_surface->y_cr_offset = memory_attibute->offsets[2] / obj_surface->width;
1467         obj_surface->cb_cr_width = obj_surface->orig_width;
1468         obj_surface->cb_cr_height = obj_surface->orig_height;
1469         obj_surface->cb_cr_pitch = memory_attibute->pitches[1];
1470
1471         break;
1472
1473     default:
1474
1475         return VA_STATUS_ERROR_INVALID_PARAMETER;
1476     }
1477
1478     if (external_memory_type == I965_SURFACE_MEM_GEM_FLINK)
1479         obj_surface->bo = drm_intel_bo_gem_create_from_name(i965->intel.bufmgr,
1480                                                             "gem flinked vaapi surface",
1481                                                             memory_attibute->buffers[index]);
1482     else if (external_memory_type == I965_SURFACE_MEM_DRM_PRIME)
1483         obj_surface->bo = drm_intel_bo_gem_create_from_prime(i965->intel.bufmgr,
1484                                                              memory_attibute->buffers[index],
1485                                                              obj_surface->size);
1486
1487     if (!obj_surface->bo)
1488         return VA_STATUS_ERROR_INVALID_PARAMETER;
1489
1490     return VA_STATUS_SUCCESS;
1491 }
1492
1493 /* byte-per-pixel of the first plane */
1494 static int
1495 bpp_1stplane_by_fourcc(unsigned int fourcc)
1496 {
1497     const i965_fourcc_info *info = get_fourcc_info(fourcc);
1498
1499     if (info && (info->flag & I_S))
1500         return info->bpp[0] / 8;
1501     else
1502         return 0;
1503 }
1504
1505 static VAStatus
1506 i965_CreateSurfaces2(
1507     VADriverContextP    ctx,
1508     unsigned int        format,
1509     unsigned int        width,
1510     unsigned int        height,
1511     VASurfaceID        *surfaces,
1512     unsigned int        num_surfaces,
1513     VASurfaceAttrib    *attrib_list,
1514     unsigned int        num_attribs
1515     )
1516 {
1517     struct i965_driver_data *i965 = i965_driver_data(ctx);
1518     int i,j;
1519     VAStatus vaStatus = VA_STATUS_SUCCESS;
1520     int expected_fourcc = 0;
1521     int memory_type = I965_SURFACE_MEM_NATIVE; /* native */
1522     VASurfaceAttribExternalBuffers *memory_attibute = NULL;
1523
1524     for (i = 0; i < num_attribs && attrib_list; i++) {
1525         if ((attrib_list[i].type == VASurfaceAttribPixelFormat) &&
1526             (attrib_list[i].flags & VA_SURFACE_ATTRIB_SETTABLE)) {
1527             ASSERT_RET(attrib_list[i].value.type == VAGenericValueTypeInteger, VA_STATUS_ERROR_INVALID_PARAMETER);
1528             expected_fourcc = attrib_list[i].value.value.i;
1529         }
1530
1531         if ((attrib_list[i].type == VASurfaceAttribMemoryType) &&
1532             (attrib_list[i].flags & VA_SURFACE_ATTRIB_SETTABLE)) {
1533             
1534             ASSERT_RET(attrib_list[i].value.type == VAGenericValueTypeInteger, VA_STATUS_ERROR_INVALID_PARAMETER);
1535
1536             if (attrib_list[i].value.value.i == VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM)
1537                 memory_type = I965_SURFACE_MEM_GEM_FLINK; /* flinked GEM handle */
1538             else if (attrib_list[i].value.value.i == VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME)
1539                 memory_type = I965_SURFACE_MEM_DRM_PRIME; /* drm prime fd */
1540             else if (attrib_list[i].value.value.i == VA_SURFACE_ATTRIB_MEM_TYPE_VA)
1541                 memory_type = I965_SURFACE_MEM_NATIVE; /* va native memory, to be allocated */
1542         }
1543
1544         if ((attrib_list[i].type == VASurfaceAttribExternalBufferDescriptor) &&
1545             (attrib_list[i].flags == VA_SURFACE_ATTRIB_SETTABLE)) {
1546             ASSERT_RET(attrib_list[i].value.type == VAGenericValueTypePointer, VA_STATUS_ERROR_INVALID_PARAMETER);
1547             memory_attibute = (VASurfaceAttribExternalBuffers *)attrib_list[i].value.value.p;
1548         }
1549     }
1550
1551     /* support 420 & 422 & RGB32 format, 422 and RGB32 are only used
1552      * for post-processing (including color conversion) */
1553     if (VA_RT_FORMAT_YUV420 != format &&
1554         VA_RT_FORMAT_YUV420_10BPP != format &&
1555         VA_RT_FORMAT_YUV422 != format &&
1556         VA_RT_FORMAT_YUV444 != format &&
1557         VA_RT_FORMAT_YUV411 != format &&
1558         VA_RT_FORMAT_YUV400 != format &&
1559         VA_RT_FORMAT_RGB32  != format) {
1560         return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT;
1561     }
1562
1563     for (i = 0; i < num_surfaces; i++) {
1564         int surfaceID = NEW_SURFACE_ID();
1565         struct object_surface *obj_surface = SURFACE(surfaceID);
1566
1567         if (NULL == obj_surface) {
1568             vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
1569             break;
1570         }
1571
1572         surfaces[i] = surfaceID;
1573         obj_surface->status = VASurfaceReady;
1574         obj_surface->orig_width = width;
1575         obj_surface->orig_height = height;
1576         obj_surface->user_disable_tiling = false;
1577         obj_surface->user_h_stride_set = false;
1578         obj_surface->user_v_stride_set = false;
1579
1580         obj_surface->subpic_render_idx = 0;
1581         for(j = 0; j < I965_MAX_SUBPIC_SUM; j++){
1582            obj_surface->subpic[j] = VA_INVALID_ID;
1583            obj_surface->obj_subpic[j] = NULL;
1584         }
1585
1586         assert(i965->codec_info->min_linear_wpitch);
1587         assert(i965->codec_info->min_linear_hpitch);
1588         obj_surface->width = ALIGN(width, i965->codec_info->min_linear_wpitch);
1589         obj_surface->height = ALIGN(height, i965->codec_info->min_linear_hpitch);
1590         obj_surface->flags = SURFACE_REFERENCED;
1591         obj_surface->fourcc = 0;
1592         obj_surface->expected_format = format;
1593         obj_surface->bo = NULL;
1594         obj_surface->locked_image_id = VA_INVALID_ID;
1595         obj_surface->derived_image_id = VA_INVALID_ID;
1596         obj_surface->private_data = NULL;
1597         obj_surface->free_private_data = NULL;
1598         obj_surface->subsampling = SUBSAMPLE_YUV420;
1599
1600         obj_surface->wrapper_surface = VA_INVALID_ID;
1601         obj_surface->exported_primefd = -1;
1602
1603         switch (memory_type) {
1604         case I965_SURFACE_MEM_NATIVE:
1605             if (memory_attibute) {
1606                 if (!(memory_attibute->flags & VA_SURFACE_EXTBUF_DESC_ENABLE_TILING))
1607                     obj_surface->user_disable_tiling = true;
1608
1609                 if (memory_attibute->pixel_format) {
1610                     if (expected_fourcc)
1611                         ASSERT_RET(memory_attibute->pixel_format == expected_fourcc, VA_STATUS_ERROR_INVALID_PARAMETER);
1612                     else
1613                         expected_fourcc = memory_attibute->pixel_format;
1614                 }
1615                 ASSERT_RET(expected_fourcc, VA_STATUS_ERROR_INVALID_PARAMETER);
1616                 if (memory_attibute->pitches[0]) {
1617                     int bpp_1stplane = bpp_1stplane_by_fourcc(expected_fourcc);
1618                     ASSERT_RET(bpp_1stplane, VA_STATUS_ERROR_INVALID_PARAMETER);
1619                     obj_surface->width = memory_attibute->pitches[0];
1620                     obj_surface->user_h_stride_set = true;
1621                     ASSERT_RET(IS_ALIGNED(obj_surface->width, 16), VA_STATUS_ERROR_INVALID_PARAMETER);
1622                     ASSERT_RET(obj_surface->width >= width * bpp_1stplane, VA_STATUS_ERROR_INVALID_PARAMETER);
1623
1624                     if (memory_attibute->offsets[1]) {
1625                         ASSERT_RET(!memory_attibute->offsets[0], VA_STATUS_ERROR_INVALID_PARAMETER);
1626                         obj_surface->height = memory_attibute->offsets[1]/memory_attibute->pitches[0];
1627                         obj_surface->user_v_stride_set = true;
1628                         ASSERT_RET(IS_ALIGNED(obj_surface->height, 16), VA_STATUS_ERROR_INVALID_PARAMETER);
1629                         ASSERT_RET(obj_surface->height >= height, VA_STATUS_ERROR_INVALID_PARAMETER);
1630                     }
1631                 }
1632             }
1633             vaStatus = i965_surface_native_memory(ctx,
1634                                                   obj_surface,
1635                                                   format,
1636                                                   expected_fourcc);
1637             break;
1638
1639         case I965_SURFACE_MEM_GEM_FLINK:
1640         case I965_SURFACE_MEM_DRM_PRIME:
1641             vaStatus = i965_suface_external_memory(ctx,
1642                                                    obj_surface,
1643                                                    memory_type,
1644                                                    memory_attibute,
1645                                                    i);
1646             break;
1647         }
1648         if (VA_STATUS_SUCCESS != vaStatus) {
1649             i965_destroy_surface(&i965->surface_heap, (struct object_base *)obj_surface);
1650             break;
1651         }
1652     }
1653
1654     /* Error recovery */
1655     if (VA_STATUS_SUCCESS != vaStatus) {
1656         /* surfaces[i-1] was the last successful allocation */
1657         for (; i--; ) {
1658             struct object_surface *obj_surface = SURFACE(surfaces[i]);
1659
1660             surfaces[i] = VA_INVALID_SURFACE;
1661             assert(obj_surface);
1662             i965_destroy_surface(&i965->surface_heap, (struct object_base *)obj_surface);
1663         }
1664     }
1665
1666     return vaStatus;
1667 }
1668
1669 VAStatus 
1670 i965_CreateSurfaces(VADriverContextP ctx,
1671                     int width,
1672                     int height,
1673                     int format,
1674                     int num_surfaces,
1675                     VASurfaceID *surfaces)      /* out */
1676 {
1677     return i965_CreateSurfaces2(ctx,
1678                                 format,
1679                                 width,
1680                                 height,
1681                                 surfaces,
1682                                 num_surfaces,
1683                                 NULL,
1684                                 0);
1685 }
1686
1687 VAStatus 
1688 i965_DestroySurfaces(VADriverContextP ctx,
1689                      VASurfaceID *surface_list,
1690                      int num_surfaces)
1691 {
1692     struct i965_driver_data *i965 = i965_driver_data(ctx);
1693     int i;
1694     VAStatus va_status = VA_STATUS_SUCCESS;
1695
1696     for (i = num_surfaces; i--; ) {
1697         struct object_surface *obj_surface = SURFACE(surface_list[i]);
1698
1699         ASSERT_RET(obj_surface, VA_STATUS_ERROR_INVALID_SURFACE);
1700
1701         if ((obj_surface->wrapper_surface != VA_INVALID_ID) &&
1702             i965->wrapper_pdrvctx) {
1703             CALL_VTABLE(i965->wrapper_pdrvctx, va_status,
1704                         vaDestroySurfaces(i965->wrapper_pdrvctx,
1705                                           &(obj_surface->wrapper_surface),
1706                                           1));
1707             obj_surface->wrapper_surface = VA_INVALID_ID;
1708         }
1709         if (obj_surface->exported_primefd >= 0) {
1710            close(obj_surface->exported_primefd);
1711            obj_surface->exported_primefd = -1;
1712         }
1713
1714         i965_destroy_surface(&i965->surface_heap, (struct object_base *)obj_surface);
1715     }
1716
1717     return va_status;
1718 }
1719
1720 VAStatus 
1721 i965_QueryImageFormats(VADriverContextP ctx,
1722                        VAImageFormat *format_list,      /* out */
1723                        int *num_formats)                /* out */
1724 {
1725     int n;
1726
1727     for (n = 0; i965_image_formats_map[n].va_format.fourcc != 0; n++) {
1728         const i965_image_format_map_t * const m = &i965_image_formats_map[n];
1729         if (format_list)
1730             format_list[n] = m->va_format;
1731     }
1732
1733     if (num_formats)
1734         *num_formats = n;
1735
1736     return VA_STATUS_SUCCESS;
1737 }
1738
1739 /*
1740  * Guess the format when the usage of a VA surface is unknown
1741  * 1. Without a valid context: YV12
1742  * 2. The current context is valid:
1743  *    a) always NV12 on GEN6 and later
1744  *    b) I420 for MPEG-2 and NV12 for other codec on GEN4 & GEN5
1745  */
1746 static void
1747 i965_guess_surface_format(VADriverContextP ctx,
1748                           VASurfaceID surface,
1749                           unsigned int *fourcc,
1750                           unsigned int *is_tiled)
1751 {
1752     struct i965_driver_data *i965 = i965_driver_data(ctx);
1753     struct object_context *obj_context = NULL;
1754     struct object_config *obj_config = NULL;
1755
1756     *fourcc = VA_FOURCC_YV12;
1757     *is_tiled = 0;
1758
1759     if (i965->current_context_id == VA_INVALID_ID)
1760         return;
1761
1762     obj_context = CONTEXT(i965->current_context_id);
1763
1764     if (!obj_context)
1765         return;
1766
1767     obj_config = obj_context->obj_config;
1768     assert(obj_config);
1769
1770     if (!obj_config)
1771         return;
1772
1773     if (IS_GEN6(i965->intel.device_info) ||
1774         IS_GEN7(i965->intel.device_info) ||
1775         IS_GEN8(i965->intel.device_info) ||
1776         IS_GEN9(i965->intel.device_info)) {
1777         *fourcc = VA_FOURCC_NV12;
1778         *is_tiled = 1;
1779         return;
1780     }
1781
1782     switch (obj_config->profile) {
1783     case VAProfileMPEG2Simple:
1784     case VAProfileMPEG2Main:
1785         *fourcc = VA_FOURCC_I420;
1786         *is_tiled = 0;
1787         break;
1788
1789     default:
1790         *fourcc = VA_FOURCC_NV12;
1791         *is_tiled = 0;
1792         break;
1793     }
1794 }
1795
1796 VAStatus 
1797 i965_QuerySubpictureFormats(VADriverContextP ctx,
1798                             VAImageFormat *format_list,         /* out */
1799                             unsigned int *flags,                /* out */
1800                             unsigned int *num_formats)          /* out */
1801 {
1802     int n;
1803
1804     for (n = 0; i965_subpic_formats_map[n].va_format.fourcc != 0; n++) {
1805         const i965_subpic_format_map_t * const m = &i965_subpic_formats_map[n];
1806         if (format_list)
1807             format_list[n] = m->va_format;
1808         if (flags)
1809             flags[n] = m->va_flags;
1810     }
1811
1812     if (num_formats)
1813         *num_formats = n;
1814
1815     return VA_STATUS_SUCCESS;
1816 }
1817
1818 static void 
1819 i965_destroy_subpic(struct object_heap *heap, struct object_base *obj)
1820 {
1821     //    struct object_subpic *obj_subpic = (struct object_subpic *)obj;
1822
1823     object_heap_free(heap, obj);
1824 }
1825
1826 VAStatus 
1827 i965_CreateSubpicture(VADriverContextP ctx,
1828                       VAImageID image,
1829                       VASubpictureID *subpicture)         /* out */
1830 {
1831     struct i965_driver_data *i965 = i965_driver_data(ctx);
1832     VASubpictureID subpicID = NEW_SUBPIC_ID()
1833     struct object_subpic *obj_subpic = SUBPIC(subpicID);
1834
1835     if (!obj_subpic)
1836         return VA_STATUS_ERROR_ALLOCATION_FAILED;
1837
1838     struct object_image *obj_image = IMAGE(image);
1839     if (!obj_image)
1840         return VA_STATUS_ERROR_INVALID_IMAGE;
1841
1842     const i965_subpic_format_map_t * const m = get_subpic_format(&obj_image->image.format);
1843     if (!m)
1844         return VA_STATUS_ERROR_UNKNOWN; /* XXX: VA_STATUS_ERROR_UNSUPPORTED_FORMAT? */
1845
1846     *subpicture = subpicID;
1847     obj_subpic->image  = image;
1848     obj_subpic->obj_image = obj_image;
1849     obj_subpic->format = m->format;
1850     obj_subpic->width  = obj_image->image.width;
1851     obj_subpic->height = obj_image->image.height;
1852     obj_subpic->pitch  = obj_image->image.pitches[0];
1853     obj_subpic->bo     = obj_image->bo;
1854     obj_subpic->global_alpha = 1.0;
1855  
1856     return VA_STATUS_SUCCESS;
1857 }
1858
1859 VAStatus 
1860 i965_DestroySubpicture(VADriverContextP ctx,
1861                        VASubpictureID subpicture)
1862 {
1863     struct i965_driver_data *i965 = i965_driver_data(ctx);
1864     struct object_subpic *obj_subpic = SUBPIC(subpicture);
1865
1866     if (!obj_subpic)
1867         return VA_STATUS_ERROR_INVALID_SUBPICTURE;
1868
1869     ASSERT_RET(obj_subpic->obj_image, VA_STATUS_ERROR_INVALID_SUBPICTURE);
1870     i965_destroy_subpic(&i965->subpic_heap, (struct object_base *)obj_subpic);
1871     return VA_STATUS_SUCCESS;
1872 }
1873
1874 VAStatus 
1875 i965_SetSubpictureImage(VADriverContextP ctx,
1876                         VASubpictureID subpicture,
1877                         VAImageID image)
1878 {
1879     /* TODO */
1880     return VA_STATUS_ERROR_UNIMPLEMENTED;
1881 }
1882
1883 VAStatus 
1884 i965_SetSubpictureChromakey(VADriverContextP ctx,
1885                             VASubpictureID subpicture,
1886                             unsigned int chromakey_min,
1887                             unsigned int chromakey_max,
1888                             unsigned int chromakey_mask)
1889 {
1890     /* TODO */
1891     return VA_STATUS_ERROR_UNIMPLEMENTED;
1892 }
1893
1894 VAStatus 
1895 i965_SetSubpictureGlobalAlpha(VADriverContextP ctx,
1896                               VASubpictureID subpicture,
1897                               float global_alpha)
1898 {
1899     struct i965_driver_data *i965 = i965_driver_data(ctx);
1900     struct object_subpic *obj_subpic = SUBPIC(subpicture);
1901
1902     if(global_alpha > 1.0 || global_alpha < 0.0){
1903        return VA_STATUS_ERROR_INVALID_PARAMETER;
1904     }
1905
1906     if (!obj_subpic)
1907         return VA_STATUS_ERROR_INVALID_SUBPICTURE;
1908
1909     obj_subpic->global_alpha  = global_alpha;
1910
1911     return VA_STATUS_SUCCESS;
1912 }
1913
1914 VAStatus 
1915 i965_AssociateSubpicture(VADriverContextP ctx,
1916                          VASubpictureID subpicture,
1917                          VASurfaceID *target_surfaces,
1918                          int num_surfaces,
1919                          short src_x, /* upper left offset in subpicture */
1920                          short src_y,
1921                          unsigned short src_width,
1922                          unsigned short src_height,
1923                          short dest_x, /* upper left offset in surface */
1924                          short dest_y,
1925                          unsigned short dest_width,
1926                          unsigned short dest_height,
1927                          /*
1928                           * whether to enable chroma-keying or global-alpha
1929                           * see VA_SUBPICTURE_XXX values
1930                           */
1931                          unsigned int flags)
1932 {
1933     struct i965_driver_data *i965 = i965_driver_data(ctx);
1934     struct object_subpic *obj_subpic = SUBPIC(subpicture);
1935     int i, j;
1936
1937     if (!obj_subpic)
1938         return VA_STATUS_ERROR_INVALID_SUBPICTURE;
1939     
1940     ASSERT_RET(obj_subpic->obj_image, VA_STATUS_ERROR_INVALID_SUBPICTURE);
1941
1942     obj_subpic->src_rect.x      = src_x;
1943     obj_subpic->src_rect.y      = src_y;
1944     obj_subpic->src_rect.width  = src_width;
1945     obj_subpic->src_rect.height = src_height;
1946     obj_subpic->dst_rect.x      = dest_x;
1947     obj_subpic->dst_rect.y      = dest_y;
1948     obj_subpic->dst_rect.width  = dest_width;
1949     obj_subpic->dst_rect.height = dest_height;
1950     obj_subpic->flags           = flags;
1951
1952     for (i = 0; i < num_surfaces; i++) {
1953         struct object_surface *obj_surface = SURFACE(target_surfaces[i]);
1954         if (!obj_surface)
1955             return VA_STATUS_ERROR_INVALID_SURFACE;
1956
1957         for(j = 0; j < I965_MAX_SUBPIC_SUM; j ++){
1958             if(obj_surface->subpic[j] == VA_INVALID_ID){
1959                 assert(obj_surface->obj_subpic[j] == NULL);
1960                 obj_surface->subpic[j] = subpicture;
1961                 obj_surface->obj_subpic[j] = obj_subpic;
1962                 break;
1963             }
1964         }
1965         
1966         if(j == I965_MAX_SUBPIC_SUM){
1967             return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
1968         }
1969
1970     }
1971     return VA_STATUS_SUCCESS;
1972 }
1973
1974
1975 VAStatus 
1976 i965_DeassociateSubpicture(VADriverContextP ctx,
1977                            VASubpictureID subpicture,
1978                            VASurfaceID *target_surfaces,
1979                            int num_surfaces)
1980 {
1981     struct i965_driver_data *i965 = i965_driver_data(ctx);
1982     struct object_subpic *obj_subpic = SUBPIC(subpicture);
1983     int i, j;
1984
1985     if (!obj_subpic)
1986         return VA_STATUS_ERROR_INVALID_SUBPICTURE;
1987
1988     for (i = 0; i < num_surfaces; i++) {
1989         struct object_surface *obj_surface = SURFACE(target_surfaces[i]);
1990         if (!obj_surface)
1991             return VA_STATUS_ERROR_INVALID_SURFACE;
1992
1993         for(j = 0; j < I965_MAX_SUBPIC_SUM; j ++){
1994             if (obj_surface->subpic[j] == subpicture) {
1995                 assert(obj_surface->obj_subpic[j] == obj_subpic);
1996                 obj_surface->subpic[j] = VA_INVALID_ID;
1997                 obj_surface->obj_subpic[j] = NULL;
1998                 break;
1999             }
2000         }
2001         
2002         if(j == I965_MAX_SUBPIC_SUM){
2003             return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
2004         }
2005     }
2006     return VA_STATUS_SUCCESS;
2007 }
2008
2009 void
2010 i965_reference_buffer_store(struct buffer_store **ptr, 
2011                             struct buffer_store *buffer_store)
2012 {
2013     assert(*ptr == NULL);
2014
2015     if (buffer_store) {
2016         buffer_store->ref_count++;
2017         *ptr = buffer_store;
2018     }
2019 }
2020
2021 void 
2022 i965_release_buffer_store(struct buffer_store **ptr)
2023 {
2024     struct buffer_store *buffer_store = *ptr;
2025
2026     if (buffer_store == NULL)
2027         return;
2028
2029     assert(buffer_store->bo || buffer_store->buffer);
2030     assert(!(buffer_store->bo && buffer_store->buffer));
2031     buffer_store->ref_count--;
2032     
2033     if (buffer_store->ref_count == 0) {
2034         dri_bo_unreference(buffer_store->bo);
2035         free(buffer_store->buffer);
2036         buffer_store->bo = NULL;
2037         buffer_store->buffer = NULL;
2038         free(buffer_store);
2039     }
2040
2041     *ptr = NULL;
2042 }
2043
2044 static void 
2045 i965_destroy_context(struct object_heap *heap, struct object_base *obj)
2046 {
2047     struct object_context *obj_context = (struct object_context *)obj;
2048     int i;
2049
2050     if (obj_context->hw_context) {
2051         obj_context->hw_context->destroy(obj_context->hw_context);
2052         obj_context->hw_context = NULL;
2053     }
2054
2055     if (obj_context->codec_type == CODEC_PROC) {
2056         i965_release_buffer_store(&obj_context->codec_state.proc.pipeline_param);
2057
2058     } else if (obj_context->codec_type == CODEC_ENC) {
2059         assert(obj_context->codec_state.encode.num_slice_params <= obj_context->codec_state.encode.max_slice_params);
2060         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param);
2061         i965_release_buffer_store(&obj_context->codec_state.encode.seq_param);
2062
2063         i965_release_buffer_store(&obj_context->codec_state.encode.q_matrix);
2064         i965_release_buffer_store(&obj_context->codec_state.encode.huffman_table);
2065
2066         for (i = 0; i < obj_context->codec_state.encode.num_slice_params; i++)
2067             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params[i]);
2068
2069         free(obj_context->codec_state.encode.slice_params);
2070
2071         assert(obj_context->codec_state.encode.num_slice_params_ext <= obj_context->codec_state.encode.max_slice_params_ext);
2072         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param_ext);
2073         i965_release_buffer_store(&obj_context->codec_state.encode.seq_param_ext);
2074
2075         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_param); i++)
2076             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_param[i]);
2077
2078         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_data); i++)
2079             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data[i]);
2080
2081         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.misc_param); i++)
2082             i965_release_buffer_store(&obj_context->codec_state.encode.misc_param[i]);
2083
2084         for (i = 0; i < obj_context->codec_state.encode.num_slice_params_ext; i++)
2085             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params_ext[i]);
2086
2087         free(obj_context->codec_state.encode.slice_params_ext);
2088         if (obj_context->codec_state.encode.slice_rawdata_index) {
2089             free(obj_context->codec_state.encode.slice_rawdata_index);
2090             obj_context->codec_state.encode.slice_rawdata_index = NULL;
2091         }
2092         if (obj_context->codec_state.encode.slice_rawdata_count) {
2093             free(obj_context->codec_state.encode.slice_rawdata_count);
2094             obj_context->codec_state.encode.slice_rawdata_count = NULL;
2095         }
2096
2097         if (obj_context->codec_state.encode.slice_header_index) {
2098             free(obj_context->codec_state.encode.slice_header_index);
2099             obj_context->codec_state.encode.slice_header_index = NULL;
2100         }
2101
2102         for (i = 0; i < obj_context->codec_state.encode.num_packed_header_params_ext; i++)
2103             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_params_ext[i]);
2104         free(obj_context->codec_state.encode.packed_header_params_ext);
2105
2106         for (i = 0; i < obj_context->codec_state.encode.num_packed_header_data_ext; i++)
2107             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data_ext[i]);
2108         free(obj_context->codec_state.encode.packed_header_data_ext);
2109
2110         i965_release_buffer_store(&obj_context->codec_state.encode.encmb_map);
2111     } else {
2112         assert(obj_context->codec_state.decode.num_slice_params <= obj_context->codec_state.decode.max_slice_params);
2113         assert(obj_context->codec_state.decode.num_slice_datas <= obj_context->codec_state.decode.max_slice_datas);
2114
2115         i965_release_buffer_store(&obj_context->codec_state.decode.pic_param);
2116         i965_release_buffer_store(&obj_context->codec_state.decode.iq_matrix);
2117         i965_release_buffer_store(&obj_context->codec_state.decode.bit_plane);
2118
2119         for (i = 0; i < obj_context->codec_state.decode.num_slice_params; i++)
2120             i965_release_buffer_store(&obj_context->codec_state.decode.slice_params[i]);
2121
2122         for (i = 0; i < obj_context->codec_state.decode.num_slice_datas; i++)
2123             i965_release_buffer_store(&obj_context->codec_state.decode.slice_datas[i]);
2124
2125         free(obj_context->codec_state.decode.slice_params);
2126         free(obj_context->codec_state.decode.slice_datas);
2127     }
2128
2129     free(obj_context->render_targets);
2130     object_heap_free(heap, obj);
2131 }
2132
2133 static inline void
2134 max_resolution(struct i965_driver_data *i965,
2135                struct object_config *obj_config,
2136                int *w,                                  /* out */
2137                int *h)                                  /* out */
2138 {
2139     if (i965->codec_info->max_resolution) {
2140         i965->codec_info->max_resolution(i965, obj_config, w, h);
2141     } else {
2142         *w = i965->codec_info->max_width;
2143         *h = i965->codec_info->max_height;
2144     }
2145 }
2146
2147 VAStatus
2148 i965_CreateContext(VADriverContextP ctx,
2149                    VAConfigID config_id,
2150                    int picture_width,
2151                    int picture_height,
2152                    int flag,
2153                    VASurfaceID *render_targets,
2154                    int num_render_targets,
2155                    VAContextID *context)                /* out */
2156 {
2157     struct i965_driver_data *i965 = i965_driver_data(ctx);
2158     struct object_config *obj_config = CONFIG(config_id);
2159     struct object_context *obj_context = NULL;
2160     VAConfigAttrib *attrib;
2161     VAStatus vaStatus = VA_STATUS_SUCCESS;
2162     int contextID;
2163     int i;
2164     int max_width;
2165     int max_height;
2166
2167     if (NULL == obj_config) {
2168         vaStatus = VA_STATUS_ERROR_INVALID_CONFIG;
2169         return vaStatus;
2170     }
2171
2172     max_resolution(i965, obj_config, &max_width, &max_height);
2173
2174     if (picture_width > max_width ||
2175         picture_height > max_height) {
2176         vaStatus = VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED;
2177         return vaStatus;
2178     }
2179
2180     /* Validate flag */
2181     /* Validate picture dimensions */
2182     contextID = NEW_CONTEXT_ID();
2183     obj_context = CONTEXT(contextID);
2184
2185     if (NULL == obj_context) {
2186         vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
2187         return vaStatus;
2188     }
2189
2190     *context = contextID;
2191     obj_context->flags = flag;
2192     obj_context->context_id = contextID;
2193     obj_context->obj_config = obj_config;
2194     obj_context->picture_width = picture_width;
2195     obj_context->picture_height = picture_height;
2196     obj_context->num_render_targets = num_render_targets;
2197     obj_context->render_targets = 
2198         (VASurfaceID *)calloc(num_render_targets, sizeof(VASurfaceID));
2199     obj_context->hw_context = NULL;
2200     obj_context->wrapper_context = VA_INVALID_ID;
2201
2202     if (!obj_context->render_targets)
2203         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2204
2205     for(i = 0; i < num_render_targets; i++) {
2206         if (NULL == SURFACE(render_targets[i])) {
2207             vaStatus = VA_STATUS_ERROR_INVALID_SURFACE;
2208             break;
2209         }
2210
2211         obj_context->render_targets[i] = render_targets[i];
2212     }
2213
2214     if (VA_STATUS_SUCCESS == vaStatus) {
2215         if (VAEntrypointVideoProc == obj_config->entrypoint) {
2216             obj_context->codec_type = CODEC_PROC;
2217             memset(&obj_context->codec_state.proc, 0, sizeof(obj_context->codec_state.proc));
2218             obj_context->codec_state.proc.current_render_target = VA_INVALID_ID;
2219             assert(i965->codec_info->proc_hw_context_init);
2220             obj_context->hw_context = i965->codec_info->proc_hw_context_init(ctx, obj_config);
2221          } else if ((VAEntrypointEncSlice == obj_config->entrypoint) || 
2222                     (VAEntrypointEncPicture == obj_config->entrypoint) ||
2223                     (VAEntrypointEncSliceLP == obj_config->entrypoint)) {
2224             VAConfigAttrib *packed_attrib;
2225             obj_context->codec_type = CODEC_ENC;
2226             memset(&obj_context->codec_state.encode, 0, sizeof(obj_context->codec_state.encode));
2227             obj_context->codec_state.encode.current_render_target = VA_INVALID_ID;
2228             obj_context->codec_state.encode.max_slice_params = NUM_SLICES;
2229             obj_context->codec_state.encode.slice_params = calloc(obj_context->codec_state.encode.max_slice_params,
2230                                                                sizeof(*obj_context->codec_state.encode.slice_params));
2231             obj_context->codec_state.encode.max_packed_header_params_ext = NUM_SLICES;
2232             obj_context->codec_state.encode.packed_header_params_ext =
2233                 calloc(obj_context->codec_state.encode.max_packed_header_params_ext,
2234                        sizeof(struct buffer_store *));
2235
2236             obj_context->codec_state.encode.max_packed_header_data_ext = NUM_SLICES;
2237             obj_context->codec_state.encode.packed_header_data_ext =
2238                 calloc(obj_context->codec_state.encode.max_packed_header_data_ext,
2239                        sizeof(struct buffer_store *));
2240
2241             obj_context->codec_state.encode.max_slice_num = NUM_SLICES;
2242             obj_context->codec_state.encode.slice_rawdata_index =
2243                 calloc(obj_context->codec_state.encode.max_slice_num, sizeof(int));
2244             obj_context->codec_state.encode.slice_rawdata_count =
2245                 calloc(obj_context->codec_state.encode.max_slice_num, sizeof(int));
2246
2247             obj_context->codec_state.encode.slice_header_index =
2248                 calloc(obj_context->codec_state.encode.max_slice_num, sizeof(int));
2249
2250             obj_context->codec_state.encode.vps_sps_seq_index = 0;
2251
2252             obj_context->codec_state.encode.slice_index = 0;
2253             packed_attrib = i965_lookup_config_attribute(obj_config, VAConfigAttribEncPackedHeaders);
2254             if (packed_attrib) {
2255                 obj_context->codec_state.encode.packed_header_flag = packed_attrib->value;
2256                 if (obj_config->profile == VAProfileVP9Profile0)
2257                     obj_context->codec_state.encode.packed_header_flag =
2258                             packed_attrib->value & VA_ENC_PACKED_HEADER_RAW_DATA;
2259             } else {
2260                 /* use the default value. SPS/PPS/RAWDATA is passed from user
2261                  * while Slice_header data is generated by driver.
2262                  */
2263                 obj_context->codec_state.encode.packed_header_flag =
2264                                VA_ENC_PACKED_HEADER_SEQUENCE |
2265                                VA_ENC_PACKED_HEADER_PICTURE |
2266                                VA_ENC_PACKED_HEADER_RAW_DATA;
2267
2268                 /* it is not used for VP9 */
2269                 if (obj_config->profile == VAProfileVP9Profile0)
2270                     obj_context->codec_state.encode.packed_header_flag = 0;
2271             }
2272             assert(i965->codec_info->enc_hw_context_init);
2273             obj_context->hw_context = i965->codec_info->enc_hw_context_init(ctx, obj_config);
2274         } else {
2275             obj_context->codec_type = CODEC_DEC;
2276             memset(&obj_context->codec_state.decode, 0, sizeof(obj_context->codec_state.decode));
2277             obj_context->codec_state.decode.current_render_target = -1;
2278             obj_context->codec_state.decode.max_slice_params = NUM_SLICES;
2279             obj_context->codec_state.decode.max_slice_datas = NUM_SLICES;
2280             obj_context->codec_state.decode.slice_params = calloc(obj_context->codec_state.decode.max_slice_params,
2281                                                                sizeof(*obj_context->codec_state.decode.slice_params));
2282             obj_context->codec_state.decode.slice_datas = calloc(obj_context->codec_state.decode.max_slice_datas,
2283                                                               sizeof(*obj_context->codec_state.decode.slice_datas));
2284
2285             assert(i965->codec_info->dec_hw_context_init);
2286             obj_context->hw_context = i965->codec_info->dec_hw_context_init(ctx, obj_config);
2287         }
2288     }
2289
2290     attrib = i965_lookup_config_attribute(obj_config, VAConfigAttribRTFormat);
2291     if (!attrib)
2292         return VA_STATUS_ERROR_INVALID_CONFIG;
2293     obj_context->codec_state.base.chroma_formats = attrib->value;
2294
2295     if (obj_config->wrapper_config != VA_INVALID_ID) {
2296         /* The wrapper_pdrvctx should exist when wrapper_config is valid.
2297          * So it won't check i965->wrapper_pdrvctx again.
2298          * Fixme if it is incorrect.
2299          */
2300         VAGenericID wrapper_context;
2301
2302         /*
2303          * The render_surface is not passed when calling
2304          * vaCreateContext.
2305          * If it is needed, we must get the wrapped surface
2306          * for the corresponding Surface_list.
2307          * So the wrapped surface conversion is deferred.
2308          */
2309         CALL_VTABLE(i965->wrapper_pdrvctx, vaStatus,
2310                     vaCreateContext(i965->wrapper_pdrvctx,
2311                                     obj_config->wrapper_config,
2312                                     picture_width, picture_height,
2313                                     flag, NULL, 0,
2314                                     &wrapper_context));
2315
2316         if (vaStatus == VA_STATUS_SUCCESS)
2317             obj_context->wrapper_context = wrapper_context;
2318     }
2319     /* Error recovery */
2320     if (VA_STATUS_SUCCESS != vaStatus) {
2321         i965_destroy_context(&i965->context_heap, (struct object_base *)obj_context);
2322     }
2323
2324     i965->current_context_id = contextID;
2325
2326     return vaStatus;
2327 }
2328
2329 VAStatus 
2330 i965_DestroyContext(VADriverContextP ctx, VAContextID context)
2331 {
2332     struct i965_driver_data *i965 = i965_driver_data(ctx);
2333     struct object_context *obj_context = CONTEXT(context);
2334     VAStatus va_status = VA_STATUS_SUCCESS;
2335
2336     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
2337
2338     if (i965->current_context_id == context)
2339         i965->current_context_id = VA_INVALID_ID;
2340
2341     if ((obj_context->wrapper_context != VA_INVALID_ID) &&
2342         i965->wrapper_pdrvctx) {
2343         CALL_VTABLE(i965->wrapper_pdrvctx, va_status,
2344                     vaDestroyContext(i965->wrapper_pdrvctx,
2345                                      obj_context->wrapper_context));
2346
2347         obj_context->wrapper_context = VA_INVALID_ID;
2348     }
2349
2350     i965_destroy_context(&i965->context_heap, (struct object_base *)obj_context);
2351
2352     return va_status;
2353 }
2354
2355 static void 
2356 i965_destroy_buffer(struct object_heap *heap, struct object_base *obj)
2357 {
2358     struct object_buffer *obj_buffer = (struct object_buffer *)obj;
2359
2360     assert(obj_buffer->buffer_store);
2361     i965_release_buffer_store(&obj_buffer->buffer_store);
2362     object_heap_free(heap, obj);
2363 }
2364
2365 static VAStatus
2366 i965_create_buffer_internal(VADriverContextP ctx,
2367                             VAContextID context,
2368                             VABufferType type,
2369                             unsigned int size,
2370                             unsigned int num_elements,
2371                             void *data,
2372                             dri_bo *store_bo,
2373                             VABufferID *buf_id)
2374 {
2375     struct i965_driver_data *i965 = i965_driver_data(ctx);
2376     struct object_buffer *obj_buffer = NULL;
2377     struct buffer_store *buffer_store = NULL;
2378     int bufferID;
2379     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
2380     struct object_context *obj_context = CONTEXT(context);
2381     int wrapper_flag = 0;
2382
2383     /* Validate type */
2384     switch (type) {
2385     case VAPictureParameterBufferType:
2386     case VAIQMatrixBufferType:
2387     case VAQMatrixBufferType:
2388     case VABitPlaneBufferType:
2389     case VASliceGroupMapBufferType:
2390     case VASliceParameterBufferType:
2391     case VASliceDataBufferType:
2392     case VAMacroblockParameterBufferType:
2393     case VAResidualDataBufferType:
2394     case VADeblockingParameterBufferType:
2395     case VAImageBufferType:
2396     case VAEncCodedBufferType:
2397     case VAEncSequenceParameterBufferType:
2398     case VAEncPictureParameterBufferType:
2399     case VAEncSliceParameterBufferType:
2400     case VAEncPackedHeaderParameterBufferType:
2401     case VAEncPackedHeaderDataBufferType:
2402     case VAEncMiscParameterBufferType:
2403     case VAProcPipelineParameterBufferType:
2404     case VAProcFilterParameterBufferType:
2405     case VAHuffmanTableBufferType:
2406     case VAProbabilityBufferType:
2407     case VAEncMacroblockMapBufferType:
2408         /* Ok */
2409         break;
2410
2411     default:
2412         return VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
2413     }
2414
2415     bufferID = NEW_BUFFER_ID();
2416     obj_buffer = BUFFER(bufferID);
2417
2418     if (NULL == obj_buffer) {
2419         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2420     }
2421
2422     if (type == VAEncCodedBufferType) {
2423         size += I965_CODEDBUFFER_HEADER_SIZE;
2424         size += 0x1000; /* for upper bound check */
2425     }
2426
2427     obj_buffer->max_num_elements = num_elements;
2428     obj_buffer->num_elements = num_elements;
2429     obj_buffer->size_element = size;
2430     obj_buffer->type = type;
2431     obj_buffer->export_refcount = 0;
2432     obj_buffer->buffer_store = NULL;
2433     obj_buffer->wrapper_buffer = VA_INVALID_ID;
2434     obj_buffer->context_id = context;
2435
2436     buffer_store = calloc(1, sizeof(struct buffer_store));
2437     assert(buffer_store);
2438     buffer_store->ref_count = 1;
2439
2440     if (obj_context &&
2441         (obj_context->wrapper_context != VA_INVALID_ID) &&
2442         i965->wrapper_pdrvctx) {
2443         VAGenericID wrapper_buffer;
2444         VADriverContextP pdrvctx = i965->wrapper_pdrvctx;
2445
2446         CALL_VTABLE(pdrvctx, vaStatus,
2447                     vaCreateBuffer(pdrvctx, obj_context->wrapper_context, type, size, num_elements,
2448                                    data, &wrapper_buffer));
2449         if (vaStatus == VA_STATUS_SUCCESS) {
2450             obj_buffer->wrapper_buffer = wrapper_buffer;
2451         } else {
2452             free(buffer_store);
2453             return vaStatus;
2454         }
2455         wrapper_flag = 1;
2456     }
2457
2458     if (store_bo != NULL) {
2459         buffer_store->bo = store_bo;
2460         dri_bo_reference(buffer_store->bo);
2461
2462         /* If the buffer is wrapped, the buffer_store is bogus. Unnecessary to copy it */
2463         if (data && !wrapper_flag)
2464             dri_bo_subdata(buffer_store->bo, 0, size * num_elements, data);
2465     } else if (type == VASliceDataBufferType || 
2466                type == VAImageBufferType || 
2467                type == VAEncCodedBufferType ||
2468                type == VAEncMacroblockMapBufferType ||
2469                type == VAProbabilityBufferType) {
2470
2471         /* If the buffer is wrapped, the bo/buffer of buffer_store is bogus.
2472          * So it is enough to allocate one 64 byte bo
2473          */
2474         if (wrapper_flag)
2475             buffer_store->bo = dri_bo_alloc(i965->intel.bufmgr, "Bogus buffer",
2476                                             64, 64);
2477         else
2478             buffer_store->bo = dri_bo_alloc(i965->intel.bufmgr,
2479                                             "Buffer",
2480                                             size * num_elements, 64);
2481         assert(buffer_store->bo);
2482
2483         /* If the buffer is wrapped, the bo/buffer of buffer_store is bogus.
2484          * In fact it can be skipped. But it is still allocated and it is
2485          * only to follow the normal flowchart of buffer_allocation/release.
2486          */
2487         if (!wrapper_flag) {
2488           if (type == VAEncCodedBufferType) {
2489             struct i965_coded_buffer_segment *coded_buffer_segment;
2490
2491             dri_bo_map(buffer_store->bo, 1);
2492             coded_buffer_segment = (struct i965_coded_buffer_segment *)buffer_store->bo->virtual;
2493             coded_buffer_segment->base.size = size - I965_CODEDBUFFER_HEADER_SIZE;
2494             coded_buffer_segment->base.bit_offset = 0;
2495             coded_buffer_segment->base.status = 0;
2496             coded_buffer_segment->base.buf = NULL;
2497             coded_buffer_segment->base.next = NULL;
2498             coded_buffer_segment->mapped = 0;
2499             coded_buffer_segment->codec = 0;
2500             coded_buffer_segment->status_support = 0;
2501             dri_bo_unmap(buffer_store->bo);
2502           } else if (data) {
2503               dri_bo_subdata(buffer_store->bo, 0, size * num_elements, data);
2504           }
2505        }
2506
2507     } else {
2508         int msize = size;
2509         
2510         if (type == VAEncPackedHeaderDataBufferType) {
2511             msize = ALIGN(size, 4);
2512         }
2513
2514         /* If the buffer is wrapped, it is enough to allocate 4 bytes */
2515         if (wrapper_flag)
2516             buffer_store->buffer = malloc(4);
2517         else
2518             buffer_store->buffer = malloc(msize * num_elements);
2519         assert(buffer_store->buffer);
2520
2521         if (data && (!wrapper_flag))
2522             memcpy(buffer_store->buffer, data, size * num_elements);
2523     }
2524
2525     buffer_store->num_elements = obj_buffer->num_elements;
2526     i965_reference_buffer_store(&obj_buffer->buffer_store, buffer_store);
2527     i965_release_buffer_store(&buffer_store);
2528     *buf_id = bufferID;
2529
2530     return VA_STATUS_SUCCESS;
2531 }
2532
2533 VAStatus 
2534 i965_CreateBuffer(VADriverContextP ctx,
2535                   VAContextID context,          /* in */
2536                   VABufferType type,            /* in */
2537                   unsigned int size,            /* in */
2538                   unsigned int num_elements,    /* in */
2539                   void *data,                   /* in */
2540                   VABufferID *buf_id)           /* out */
2541 {
2542     return i965_create_buffer_internal(ctx, context, type, size, num_elements, data, NULL, buf_id);
2543 }
2544
2545
2546 VAStatus 
2547 i965_BufferSetNumElements(VADriverContextP ctx,
2548                           VABufferID buf_id,           /* in */
2549                           unsigned int num_elements)   /* in */
2550 {
2551     struct i965_driver_data *i965 = i965_driver_data(ctx);
2552     struct object_buffer *obj_buffer = BUFFER(buf_id);
2553     VAStatus vaStatus = VA_STATUS_SUCCESS;
2554
2555     ASSERT_RET(obj_buffer, VA_STATUS_ERROR_INVALID_BUFFER);
2556
2557     /* When the wrapper_buffer exists, it will wrapper to the
2558      * buffer allocated from backend driver.
2559      */
2560     if ((obj_buffer->wrapper_buffer != VA_INVALID_ID) &&
2561         i965->wrapper_pdrvctx) {
2562         VADriverContextP pdrvctx = i965->wrapper_pdrvctx;
2563
2564         CALL_VTABLE(pdrvctx, vaStatus,
2565                     vaBufferSetNumElements(pdrvctx, obj_buffer->wrapper_buffer,
2566                                          num_elements));
2567         return vaStatus;
2568     }
2569
2570     if ((num_elements < 0) || 
2571         (num_elements > obj_buffer->max_num_elements)) {
2572         vaStatus = VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
2573     } else {
2574         obj_buffer->num_elements = num_elements;
2575         if (obj_buffer->buffer_store != NULL) {
2576             obj_buffer->buffer_store->num_elements = num_elements;
2577         }
2578     }
2579
2580     return vaStatus;
2581 }
2582
2583 VAStatus 
2584 i965_MapBuffer(VADriverContextP ctx,
2585                VABufferID buf_id,       /* in */
2586                void **pbuf)             /* out */
2587 {
2588     struct i965_driver_data *i965 = i965_driver_data(ctx);
2589     struct object_buffer *obj_buffer = BUFFER(buf_id);
2590     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
2591     struct object_context *obj_context;
2592
2593     ASSERT_RET(obj_buffer && obj_buffer->buffer_store, VA_STATUS_ERROR_INVALID_BUFFER);
2594
2595     obj_context = CONTEXT(obj_buffer->context_id);
2596
2597     /* When the wrapper_buffer exists, it will wrapper to the
2598      * buffer allocated from backend driver.
2599      */
2600     if ((obj_buffer->wrapper_buffer != VA_INVALID_ID) &&
2601         i965->wrapper_pdrvctx) {
2602         VADriverContextP pdrvctx = i965->wrapper_pdrvctx;
2603
2604         CALL_VTABLE(pdrvctx, vaStatus,
2605                     vaMapBuffer(pdrvctx, obj_buffer->wrapper_buffer, pbuf));
2606         return vaStatus;
2607     }
2608
2609     ASSERT_RET(obj_buffer->buffer_store->bo || obj_buffer->buffer_store->buffer, VA_STATUS_ERROR_INVALID_BUFFER);
2610     ASSERT_RET(!(obj_buffer->buffer_store->bo && obj_buffer->buffer_store->buffer), VA_STATUS_ERROR_INVALID_BUFFER);
2611
2612     if (obj_buffer->export_refcount > 0)
2613         return VA_STATUS_ERROR_INVALID_BUFFER;
2614
2615     if (NULL != obj_buffer->buffer_store->bo) {
2616         unsigned int tiling, swizzle;
2617
2618         dri_bo_get_tiling(obj_buffer->buffer_store->bo, &tiling, &swizzle);
2619
2620         if (tiling != I915_TILING_NONE)
2621             drm_intel_gem_bo_map_gtt(obj_buffer->buffer_store->bo);
2622         else
2623             dri_bo_map(obj_buffer->buffer_store->bo, 1);
2624
2625         ASSERT_RET(obj_buffer->buffer_store->bo->virtual, VA_STATUS_ERROR_OPERATION_FAILED);
2626         *pbuf = obj_buffer->buffer_store->bo->virtual;
2627         vaStatus = VA_STATUS_SUCCESS;
2628
2629         if (obj_buffer->type == VAEncCodedBufferType) {
2630             int i;
2631             unsigned char *buffer = NULL;
2632             unsigned int  header_offset = I965_CODEDBUFFER_HEADER_SIZE;
2633             struct i965_coded_buffer_segment *coded_buffer_segment = (struct i965_coded_buffer_segment *)(obj_buffer->buffer_store->bo->virtual);
2634
2635             if (!coded_buffer_segment->mapped) {
2636                 unsigned char delimiter0, delimiter1, delimiter2, delimiter3, delimiter4;
2637
2638                 coded_buffer_segment->base.buf = buffer = (unsigned char *)(obj_buffer->buffer_store->bo->virtual) + I965_CODEDBUFFER_HEADER_SIZE;
2639
2640                 if (obj_context &&
2641                     obj_context->hw_context &&
2642                     obj_context->hw_context->get_status &&
2643                     coded_buffer_segment->status_support) {
2644                     vaStatus = obj_context->hw_context->get_status(ctx, obj_context->hw_context, coded_buffer_segment);
2645                 } else {
2646
2647                     if (coded_buffer_segment->codec == CODEC_VP9) {
2648
2649                         if (obj_context == NULL)
2650                             return VA_STATUS_ERROR_ENCODING_ERROR;
2651
2652                         gen9_vp9_get_coded_status(ctx, (char *)coded_buffer_segment,
2653                                                   obj_context->hw_context);
2654                     }
2655                     else if (coded_buffer_segment->codec == CODEC_H264 ||
2656                         coded_buffer_segment->codec == CODEC_H264_MVC) {
2657                         delimiter0 = H264_DELIMITER0;
2658                         delimiter1 = H264_DELIMITER1;
2659                         delimiter2 = H264_DELIMITER2;
2660                         delimiter3 = H264_DELIMITER3;
2661                         delimiter4 = H264_DELIMITER4;
2662                     } else if (coded_buffer_segment->codec == CODEC_MPEG2) {
2663                         delimiter0 = MPEG2_DELIMITER0;
2664                         delimiter1 = MPEG2_DELIMITER1;
2665                         delimiter2 = MPEG2_DELIMITER2;
2666                         delimiter3 = MPEG2_DELIMITER3;
2667                         delimiter4 = MPEG2_DELIMITER4;
2668                     } else if(coded_buffer_segment->codec == CODEC_JPEG) {
2669                         //In JPEG End of Image (EOI = 0xDDF9) marker can be used for delimiter.
2670                         delimiter0 = 0xFF;
2671                         delimiter1 = 0xD9;
2672                     } else if (coded_buffer_segment->codec == CODEC_HEVC) {
2673                         delimiter0 = HEVC_DELIMITER0;
2674                         delimiter1 = HEVC_DELIMITER1;
2675                         delimiter2 = HEVC_DELIMITER2;
2676                         delimiter3 = HEVC_DELIMITER3;
2677                         delimiter4 = HEVC_DELIMITER4;
2678                     } else if (coded_buffer_segment->codec != CODEC_VP8) {
2679                         ASSERT_RET(0, VA_STATUS_ERROR_UNSUPPORTED_PROFILE);
2680                     }
2681
2682                     if(coded_buffer_segment->codec == CODEC_VP9) {
2683                         /* it is already handled */
2684                     } else
2685                     if(coded_buffer_segment->codec == CODEC_JPEG) {
2686                         for(i = 0; i <  obj_buffer->size_element - header_offset - 1 - 0x1000; i++) {
2687                             if( (buffer[i] == 0xFF) && (buffer[i + 1] == 0xD9)) {
2688                                 break;
2689                             }
2690                         }
2691                         coded_buffer_segment->base.size = i + 2;
2692                     } else if (coded_buffer_segment->codec != CODEC_VP8) {
2693                         /* vp8 coded buffer size can be told by vp8 internal statistics buffer,
2694                            so it don't need to traversal the coded buffer */
2695                         for (i = 0; i < obj_buffer->size_element - header_offset - 3 - 0x1000; i++) {
2696                             if ((buffer[i] == delimiter0) &&
2697                                 (buffer[i + 1] == delimiter1) &&
2698                                 (buffer[i + 2] == delimiter2) &&
2699                                 (buffer[i + 3] == delimiter3) &&
2700                                 (buffer[i + 4] == delimiter4))
2701                                 break;
2702                         }
2703
2704                         if (i == obj_buffer->size_element - header_offset - 3 - 0x1000) {
2705                             coded_buffer_segment->base.status |= VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK;
2706                         }
2707                         coded_buffer_segment->base.size = i;
2708                     }
2709
2710                     if (coded_buffer_segment->base.size >= obj_buffer->size_element - header_offset - 0x1000) {
2711                         coded_buffer_segment->base.status |= VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK;
2712                     }
2713
2714                     vaStatus = VA_STATUS_SUCCESS;
2715                 }
2716
2717                 coded_buffer_segment->mapped = 1;
2718             } else {
2719                 assert(coded_buffer_segment->base.buf);
2720                 vaStatus = VA_STATUS_SUCCESS;
2721             }
2722         }
2723     } else if (NULL != obj_buffer->buffer_store->buffer) {
2724         *pbuf = obj_buffer->buffer_store->buffer;
2725         vaStatus = VA_STATUS_SUCCESS;
2726     }
2727
2728     return vaStatus;
2729 }
2730
2731 VAStatus 
2732 i965_UnmapBuffer(VADriverContextP ctx, VABufferID buf_id)
2733 {
2734     struct i965_driver_data *i965 = i965_driver_data(ctx);
2735     struct object_buffer *obj_buffer = BUFFER(buf_id);
2736     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
2737
2738     if ((buf_id & OBJECT_HEAP_OFFSET_MASK) != BUFFER_ID_OFFSET)
2739         return VA_STATUS_ERROR_INVALID_BUFFER;
2740
2741     ASSERT_RET(obj_buffer && obj_buffer->buffer_store, VA_STATUS_ERROR_INVALID_BUFFER);
2742     /* When the wrapper_buffer exists, it will wrapper to the
2743      * buffer allocated from backend driver.
2744      */
2745     if ((obj_buffer->wrapper_buffer != VA_INVALID_ID) &&
2746         i965->wrapper_pdrvctx) {
2747         VADriverContextP pdrvctx = i965->wrapper_pdrvctx;
2748
2749         CALL_VTABLE(pdrvctx, vaStatus,
2750                     vaUnmapBuffer(pdrvctx, obj_buffer->wrapper_buffer));
2751         return vaStatus;
2752     }
2753
2754     ASSERT_RET(obj_buffer->buffer_store->bo || obj_buffer->buffer_store->buffer, VA_STATUS_ERROR_OPERATION_FAILED);
2755     ASSERT_RET(!(obj_buffer->buffer_store->bo && obj_buffer->buffer_store->buffer), VA_STATUS_ERROR_OPERATION_FAILED);
2756
2757     if (NULL != obj_buffer->buffer_store->bo) {
2758         unsigned int tiling, swizzle;
2759
2760         dri_bo_get_tiling(obj_buffer->buffer_store->bo, &tiling, &swizzle);
2761
2762         if (tiling != I915_TILING_NONE)
2763             drm_intel_gem_bo_unmap_gtt(obj_buffer->buffer_store->bo);
2764         else
2765             dri_bo_unmap(obj_buffer->buffer_store->bo);
2766
2767         vaStatus = VA_STATUS_SUCCESS;
2768     } else if (NULL != obj_buffer->buffer_store->buffer) {
2769         /* Do nothing */
2770         vaStatus = VA_STATUS_SUCCESS;
2771     }
2772
2773     return vaStatus;    
2774 }
2775
2776 VAStatus 
2777 i965_DestroyBuffer(VADriverContextP ctx, VABufferID buffer_id)
2778 {
2779     struct i965_driver_data *i965 = i965_driver_data(ctx);
2780     struct object_buffer *obj_buffer = BUFFER(buffer_id);
2781     VAStatus va_status = VA_STATUS_SUCCESS;
2782
2783     ASSERT_RET(obj_buffer, VA_STATUS_ERROR_INVALID_BUFFER);
2784
2785     if ((obj_buffer->wrapper_buffer != VA_INVALID_ID) &&
2786         i965->wrapper_pdrvctx) {
2787         CALL_VTABLE(i965->wrapper_pdrvctx, va_status,
2788                     vaDestroyBuffer(i965->wrapper_pdrvctx,
2789                                     obj_buffer->wrapper_buffer));
2790         obj_buffer->wrapper_buffer = VA_INVALID_ID;
2791     }
2792
2793     i965_destroy_buffer(&i965->buffer_heap, (struct object_base *)obj_buffer);
2794
2795     return va_status;
2796 }
2797
2798 VAStatus 
2799 i965_BeginPicture(VADriverContextP ctx,
2800                   VAContextID context,
2801                   VASurfaceID render_target)
2802 {
2803     struct i965_driver_data *i965 = i965_driver_data(ctx); 
2804     struct object_context *obj_context = CONTEXT(context);
2805     struct object_surface *obj_surface = SURFACE(render_target);
2806     struct object_config *obj_config;
2807     VAStatus vaStatus = VA_STATUS_SUCCESS;
2808     int i;
2809
2810     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
2811     ASSERT_RET(obj_surface, VA_STATUS_ERROR_INVALID_SURFACE);
2812     obj_config = obj_context->obj_config;
2813     ASSERT_RET(obj_config, VA_STATUS_ERROR_INVALID_CONFIG);
2814
2815     if (is_surface_busy(i965, obj_surface))
2816         return VA_STATUS_ERROR_SURFACE_BUSY;
2817
2818     if (obj_context->codec_type == CODEC_PROC) {
2819         obj_context->codec_state.proc.current_render_target = render_target;
2820     } else if (obj_context->codec_type == CODEC_ENC) {
2821         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param);
2822
2823         for (i = 0; i < obj_context->codec_state.encode.num_slice_params; i++) {
2824             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params[i]);
2825         }
2826
2827         obj_context->codec_state.encode.num_slice_params = 0;
2828
2829         /* ext */
2830         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param_ext);
2831
2832         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_param); i++)
2833             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_param[i]);
2834
2835         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_data); i++)
2836             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data[i]);
2837
2838         for (i = 0; i < obj_context->codec_state.encode.num_slice_params_ext; i++)
2839             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params_ext[i]);
2840
2841         obj_context->codec_state.encode.num_slice_params_ext = 0;
2842         obj_context->codec_state.encode.current_render_target = render_target;     /*This is input new frame*/
2843         obj_context->codec_state.encode.last_packed_header_type = 0;
2844         memset(obj_context->codec_state.encode.slice_rawdata_index, 0,
2845                sizeof(int) * obj_context->codec_state.encode.max_slice_num);
2846         memset(obj_context->codec_state.encode.slice_rawdata_count, 0,
2847                sizeof(int) * obj_context->codec_state.encode.max_slice_num);
2848         memset(obj_context->codec_state.encode.slice_header_index, 0,
2849                sizeof(int) * obj_context->codec_state.encode.max_slice_num);
2850
2851         for (i = 0; i < obj_context->codec_state.encode.num_packed_header_params_ext; i++)
2852             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_params_ext[i]);
2853         for (i = 0; i < obj_context->codec_state.encode.num_packed_header_data_ext; i++)
2854             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data_ext[i]);
2855         obj_context->codec_state.encode.num_packed_header_params_ext = 0;
2856         obj_context->codec_state.encode.num_packed_header_data_ext = 0;
2857         obj_context->codec_state.encode.slice_index = 0;
2858         obj_context->codec_state.encode.vps_sps_seq_index = 0;
2859         i965_release_buffer_store(&obj_context->codec_state.encode.encmb_map);
2860
2861         if (obj_config->profile == VAProfileVP9Profile0) {
2862             for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.misc_param); i++)
2863                 i965_release_buffer_store(&obj_context->codec_state.encode.misc_param[i]);
2864
2865             i965_release_buffer_store(&obj_context->codec_state.encode.seq_param_ext);
2866         }
2867     } else {
2868         obj_context->codec_state.decode.current_render_target = render_target;
2869         i965_release_buffer_store(&obj_context->codec_state.decode.pic_param);
2870         i965_release_buffer_store(&obj_context->codec_state.decode.iq_matrix);
2871         i965_release_buffer_store(&obj_context->codec_state.decode.bit_plane);
2872         i965_release_buffer_store(&obj_context->codec_state.decode.huffman_table);
2873
2874         for (i = 0; i < obj_context->codec_state.decode.num_slice_params; i++) {
2875             i965_release_buffer_store(&obj_context->codec_state.decode.slice_params[i]);
2876             i965_release_buffer_store(&obj_context->codec_state.decode.slice_datas[i]);
2877         }
2878
2879         obj_context->codec_state.decode.num_slice_params = 0;
2880         obj_context->codec_state.decode.num_slice_datas = 0;
2881
2882         if ((obj_context->wrapper_context != VA_INVALID_ID) &&
2883             i965->wrapper_pdrvctx) {
2884             if (obj_surface->wrapper_surface == VA_INVALID_ID)
2885                 vaStatus = i965_surface_wrapper(ctx, render_target);
2886
2887             if (vaStatus != VA_STATUS_SUCCESS)
2888                 return vaStatus;
2889
2890             CALL_VTABLE(i965->wrapper_pdrvctx, vaStatus,
2891                         vaBeginPicture(i965->wrapper_pdrvctx,
2892                                        obj_context->wrapper_context,
2893                                        obj_surface->wrapper_surface));
2894         }
2895     }
2896
2897     return vaStatus;
2898 }
2899
2900 #define I965_RENDER_BUFFER(category, name) i965_render_##category##_##name##_buffer(ctx, obj_context, obj_buffer)
2901
2902 #define DEF_RENDER_SINGLE_BUFFER_FUNC(category, name, member)           \
2903     static VAStatus                                                     \
2904     i965_render_##category##_##name##_buffer(VADriverContextP ctx,      \
2905                                              struct object_context *obj_context, \
2906                                              struct object_buffer *obj_buffer) \
2907     {                                                                   \
2908         struct category##_state *category = &obj_context->codec_state.category; \
2909         i965_release_buffer_store(&category->member);                   \
2910         i965_reference_buffer_store(&category->member, obj_buffer->buffer_store); \
2911         return VA_STATUS_SUCCESS;                                       \
2912     }
2913
2914 #define DEF_RENDER_MULTI_BUFFER_FUNC(category, name, member)            \
2915     static VAStatus                                                     \
2916     i965_render_##category##_##name##_buffer(VADriverContextP ctx,      \
2917                                              struct object_context *obj_context, \
2918                                              struct object_buffer *obj_buffer) \
2919     {                                                                   \
2920         struct category##_state *category = &obj_context->codec_state.category; \
2921         if (category->num_##member == category->max_##member) {         \
2922             category->member = realloc(category->member, (category->max_##member + NUM_SLICES) * sizeof(*category->member)); \
2923             memset(category->member + category->max_##member, 0, NUM_SLICES * sizeof(*category->member)); \
2924             category->max_##member += NUM_SLICES;                       \
2925         }                                                               \
2926         i965_release_buffer_store(&category->member[category->num_##member]); \
2927         i965_reference_buffer_store(&category->member[category->num_##member], obj_buffer->buffer_store); \
2928         category->num_##member++;                                       \
2929         return VA_STATUS_SUCCESS;                                       \
2930     }
2931
2932 #define I965_RENDER_DECODE_BUFFER(name) I965_RENDER_BUFFER(decode, name)
2933
2934 #define DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(decode, name, member)
2935 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(picture_parameter, pic_param)
2936 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(iq_matrix, iq_matrix)
2937 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(bit_plane, bit_plane)
2938 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(huffman_table, huffman_table)
2939 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(probability_data, probability_data)
2940
2941 #define DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(name, member) DEF_RENDER_MULTI_BUFFER_FUNC(decode, name, member)
2942 DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(slice_parameter, slice_params)
2943 DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(slice_data, slice_datas)
2944
2945
2946 static VAStatus
2947 i965_decoder_vp9_wrapper_picture(VADriverContextP ctx,
2948                              VABufferID *buffers,
2949                              int num_buffers)
2950 {
2951     struct i965_driver_data *i965 = i965_driver_data(ctx);
2952     VAStatus vaStatus = VA_STATUS_SUCCESS;
2953     int i;
2954     VADecPictureParameterBufferVP9 *pVp9PicParams;
2955     VADriverContextP pdrvctx;
2956     struct object_buffer *obj_buffer;
2957
2958     pdrvctx = i965->wrapper_pdrvctx;
2959     /* do the conversion of VADecPictureParameterBufferVP9 */
2960     for (i = 0; i < num_buffers; i++) {
2961         obj_buffer = BUFFER(buffers[i]);
2962
2963         if (!obj_buffer)
2964             continue;
2965
2966         if (obj_buffer->wrapper_buffer == VA_INVALID_ID)
2967             continue;
2968
2969         if (obj_buffer->type == VAPictureParameterBufferType) {
2970             int j;
2971             VASurfaceID surface_id;
2972             struct object_surface *obj_surface;
2973
2974             pdrvctx = i965->wrapper_pdrvctx;
2975
2976             CALL_VTABLE(pdrvctx, vaStatus,
2977                         vaMapBuffer(pdrvctx, obj_buffer->wrapper_buffer,
2978                                     (void **)(&pVp9PicParams)));
2979
2980             if (vaStatus != VA_STATUS_SUCCESS)
2981                 return vaStatus;
2982
2983             for (j = 0; j < 8; j++) {
2984                 surface_id = pVp9PicParams->reference_frames[j];
2985                 obj_surface = SURFACE(surface_id);
2986
2987                 if (!obj_surface)
2988                     continue;
2989
2990                 if (obj_surface->wrapper_surface == VA_INVALID_ID) {
2991                     vaStatus = i965_surface_wrapper(ctx, surface_id);
2992                     if (vaStatus != VA_STATUS_SUCCESS) {
2993                         pdrvctx->vtable->vaUnmapBuffer(pdrvctx,
2994                                     obj_buffer->wrapper_buffer);
2995                         goto fail_out;
2996                     }
2997                 }
2998
2999                 pVp9PicParams->reference_frames[j] = obj_surface->wrapper_surface;
3000             }
3001             CALL_VTABLE(pdrvctx, vaStatus,
3002                         vaUnmapBuffer(pdrvctx, obj_buffer->wrapper_buffer));
3003             break;
3004         }
3005     }
3006
3007     return VA_STATUS_SUCCESS;
3008
3009 fail_out:
3010     return vaStatus;
3011 }
3012
3013 static VAStatus
3014 i965_decoder_wrapper_picture(VADriverContextP ctx,
3015                              VAContextID context,
3016                              VABufferID *buffers,
3017                              int num_buffers)
3018 {
3019     struct i965_driver_data *i965 = i965_driver_data(ctx);
3020     struct object_context *obj_context = CONTEXT(context);
3021     VAStatus vaStatus = VA_STATUS_SUCCESS;
3022     int i;
3023     VADriverContextP pdrvctx;
3024     struct object_buffer *obj_buffer;
3025
3026     if (obj_context == NULL)
3027         return VA_STATUS_ERROR_INVALID_CONTEXT;
3028
3029     /* When it is not wrapped context, continue the normal flowchart */
3030     if (obj_context->wrapper_context == VA_INVALID_ID)
3031         return vaStatus;
3032
3033     if (obj_context->obj_config &&
3034         (obj_context->obj_config->profile == VAProfileVP9Profile0)) {
3035         vaStatus = i965_decoder_vp9_wrapper_picture(ctx, buffers, num_buffers);
3036     } else
3037         return VA_STATUS_ERROR_INVALID_PARAMETER;
3038
3039     pdrvctx = i965->wrapper_pdrvctx;
3040
3041     for (i = 0; i < num_buffers && vaStatus == VA_STATUS_SUCCESS; i++) {
3042         obj_buffer = BUFFER(buffers[i]);
3043
3044         if (!obj_buffer)
3045             continue;
3046
3047         if (obj_buffer->wrapper_buffer == VA_INVALID_ID) {
3048             vaStatus = VA_STATUS_ERROR_INVALID_BUFFER;
3049             break;
3050         }
3051
3052         CALL_VTABLE(pdrvctx, vaStatus,
3053                     vaRenderPicture(pdrvctx, obj_context->wrapper_context,
3054                                     &(obj_buffer->wrapper_buffer), 1));
3055     }
3056     return vaStatus;
3057 }
3058
3059 static VAStatus 
3060 i965_decoder_render_picture(VADriverContextP ctx,
3061                             VAContextID context,
3062                             VABufferID *buffers,
3063                             int num_buffers)
3064 {
3065     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3066     struct object_context *obj_context = CONTEXT(context);
3067     VAStatus vaStatus = VA_STATUS_SUCCESS;
3068     int i;
3069     
3070     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
3071
3072     for (i = 0; i < num_buffers && vaStatus == VA_STATUS_SUCCESS; i++) {
3073         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
3074
3075         if (!obj_buffer)
3076             return VA_STATUS_ERROR_INVALID_BUFFER;
3077
3078         switch (obj_buffer->type) {
3079         case VAPictureParameterBufferType:
3080             vaStatus = I965_RENDER_DECODE_BUFFER(picture_parameter);
3081             break;
3082             
3083         case VAIQMatrixBufferType:
3084             vaStatus = I965_RENDER_DECODE_BUFFER(iq_matrix);
3085             break;
3086
3087         case VABitPlaneBufferType:
3088             vaStatus = I965_RENDER_DECODE_BUFFER(bit_plane);
3089             break;
3090
3091         case VASliceParameterBufferType:
3092             vaStatus = I965_RENDER_DECODE_BUFFER(slice_parameter);
3093             break;
3094
3095         case VASliceDataBufferType:
3096             vaStatus = I965_RENDER_DECODE_BUFFER(slice_data);
3097             break;
3098
3099         case VAHuffmanTableBufferType:
3100             vaStatus = I965_RENDER_DECODE_BUFFER(huffman_table);
3101             break;
3102
3103         case VAProbabilityBufferType:
3104             vaStatus = I965_RENDER_DECODE_BUFFER(probability_data);
3105             break;
3106
3107         default:
3108             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
3109             break;
3110         }
3111     }
3112
3113     if ((vaStatus == VA_STATUS_SUCCESS) &&
3114         (obj_context->wrapper_context != VA_INVALID_ID))
3115         vaStatus = i965_decoder_wrapper_picture(ctx, context, buffers, num_buffers);
3116
3117     return vaStatus;
3118 }
3119
3120 #define I965_RENDER_ENCODE_BUFFER(name) I965_RENDER_BUFFER(encode, name)
3121
3122 #define DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(encode, name, member)
3123 // DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(sequence_parameter, seq_param)    
3124 // DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_parameter, pic_param)
3125 // DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_control, pic_control)
3126 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(qmatrix, q_matrix)
3127 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(iqmatrix, iq_matrix)
3128 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(huffman_table, huffman_table)
3129 /* extended buffer */
3130 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(sequence_parameter_ext, seq_param_ext)
3131 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_parameter_ext, pic_param_ext)
3132 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(encmb_map, encmb_map)
3133
3134 #define DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(name, member) DEF_RENDER_MULTI_BUFFER_FUNC(encode, name, member)
3135 // DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(slice_parameter, slice_params)
3136 DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(slice_parameter_ext, slice_params_ext)
3137
3138 DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(packed_header_params_ext, packed_header_params_ext)
3139 DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(packed_header_data_ext, packed_header_data_ext)
3140
3141 static VAStatus
3142 i965_encoder_render_packed_header_parameter_buffer(VADriverContextP ctx,
3143                                                    struct object_context *obj_context,
3144                                                    struct object_buffer *obj_buffer,
3145                                                    int type_index)
3146 {
3147     struct encode_state *encode = &obj_context->codec_state.encode;
3148
3149     ASSERT_RET(obj_buffer->buffer_store->bo == NULL, VA_STATUS_ERROR_INVALID_BUFFER);
3150     ASSERT_RET(obj_buffer->buffer_store->buffer, VA_STATUS_ERROR_INVALID_BUFFER);
3151     i965_release_buffer_store(&encode->packed_header_param[type_index]);
3152     i965_reference_buffer_store(&encode->packed_header_param[type_index], obj_buffer->buffer_store);
3153
3154     return VA_STATUS_SUCCESS;
3155 }
3156
3157 static VAStatus
3158 i965_encoder_render_packed_header_data_buffer(VADriverContextP ctx,
3159                                               struct object_context *obj_context,
3160                                               struct object_buffer *obj_buffer,
3161                                               int type_index)
3162 {
3163     struct encode_state *encode = &obj_context->codec_state.encode;
3164
3165     ASSERT_RET(obj_buffer->buffer_store->bo == NULL, VA_STATUS_ERROR_INVALID_BUFFER);
3166     ASSERT_RET(obj_buffer->buffer_store->buffer, VA_STATUS_ERROR_INVALID_BUFFER);
3167     i965_release_buffer_store(&encode->packed_header_data[type_index]);
3168     i965_reference_buffer_store(&encode->packed_header_data[type_index], obj_buffer->buffer_store);
3169
3170     return VA_STATUS_SUCCESS;
3171 }
3172
3173 static VAStatus
3174 i965_encoder_render_misc_parameter_buffer(VADriverContextP ctx,
3175                                           struct object_context *obj_context,
3176                                           struct object_buffer *obj_buffer)
3177 {
3178     struct encode_state *encode = &obj_context->codec_state.encode;
3179     VAEncMiscParameterBuffer *param = NULL;
3180
3181     ASSERT_RET(obj_buffer->buffer_store->bo == NULL, VA_STATUS_ERROR_INVALID_BUFFER);
3182     ASSERT_RET(obj_buffer->buffer_store->buffer, VA_STATUS_ERROR_INVALID_BUFFER);
3183
3184     param = (VAEncMiscParameterBuffer *)obj_buffer->buffer_store->buffer;
3185
3186     if (param->type >= ARRAY_ELEMS(encode->misc_param))
3187         return VA_STATUS_ERROR_INVALID_PARAMETER;
3188
3189     i965_release_buffer_store(&encode->misc_param[param->type]);
3190     i965_reference_buffer_store(&encode->misc_param[param->type], obj_buffer->buffer_store);
3191
3192     return VA_STATUS_SUCCESS;
3193 }
3194
3195 static VAStatus 
3196 i965_encoder_render_picture(VADriverContextP ctx,
3197                             VAContextID context,
3198                             VABufferID *buffers,
3199                             int num_buffers)
3200 {
3201     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3202     struct object_context *obj_context = CONTEXT(context);
3203     struct object_config *obj_config;
3204     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
3205     struct encode_state *encode;
3206     int i;
3207
3208     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
3209     obj_config = obj_context->obj_config;
3210     ASSERT_RET(obj_config, VA_STATUS_ERROR_INVALID_CONFIG);
3211
3212     encode = &obj_context->codec_state.encode;
3213     for (i = 0; i < num_buffers; i++) {  
3214         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
3215
3216         if (!obj_buffer)
3217             return VA_STATUS_ERROR_INVALID_BUFFER;
3218
3219         switch (obj_buffer->type) {
3220         case VAQMatrixBufferType:
3221             vaStatus = I965_RENDER_ENCODE_BUFFER(qmatrix);
3222             break;
3223
3224         case VAIQMatrixBufferType:
3225             vaStatus = I965_RENDER_ENCODE_BUFFER(iqmatrix);
3226             break;
3227
3228         case VAEncSequenceParameterBufferType:
3229             vaStatus = I965_RENDER_ENCODE_BUFFER(sequence_parameter_ext);
3230             break;
3231
3232         case VAEncPictureParameterBufferType:
3233             vaStatus = I965_RENDER_ENCODE_BUFFER(picture_parameter_ext);
3234             break;
3235
3236         case VAHuffmanTableBufferType:
3237             vaStatus = I965_RENDER_ENCODE_BUFFER(huffman_table);
3238             break;
3239
3240         case VAEncSliceParameterBufferType:
3241             vaStatus = I965_RENDER_ENCODE_BUFFER(slice_parameter_ext);
3242             if (vaStatus == VA_STATUS_SUCCESS) {
3243                 /* When the max number of slices is updated, it also needs
3244                  * to reallocate the arrays that is used to store
3245                  * the packed data index/count for the slice
3246                  */
3247                 if (!(encode->packed_header_flag & VA_ENC_PACKED_HEADER_SLICE)) {
3248                    encode->slice_index++;
3249                 }
3250                 if (encode->slice_index == encode->max_slice_num) {
3251                     int slice_num = encode->max_slice_num;
3252                     encode->slice_rawdata_index = realloc(encode->slice_rawdata_index,
3253                                                           (slice_num + NUM_SLICES) * sizeof(int));
3254                     encode->slice_rawdata_count = realloc(encode->slice_rawdata_count,
3255                                                           (slice_num + NUM_SLICES) * sizeof(int));
3256                     encode->slice_header_index = realloc(encode->slice_header_index,
3257                                                           (slice_num + NUM_SLICES) * sizeof(int));
3258                     memset(encode->slice_rawdata_index + slice_num, 0,
3259                         sizeof(int) * NUM_SLICES);
3260                     memset(encode->slice_rawdata_count + slice_num, 0,
3261                         sizeof(int) * NUM_SLICES);
3262                     memset(encode->slice_header_index + slice_num, 0,
3263                         sizeof(int) * NUM_SLICES);
3264
3265                     encode->max_slice_num += NUM_SLICES;
3266                     if ((encode->slice_rawdata_index == NULL) ||
3267                         (encode->slice_header_index == NULL)  ||
3268                         (encode->slice_rawdata_count == NULL)) {
3269                         vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
3270                         return vaStatus;
3271                     }
3272                 }
3273             }
3274             break;
3275
3276         case VAEncPackedHeaderParameterBufferType:
3277         {
3278             VAEncPackedHeaderParameterBuffer *param = (VAEncPackedHeaderParameterBuffer *)obj_buffer->buffer_store->buffer;
3279             encode->last_packed_header_type = param->type;
3280
3281             if ((param->type == VAEncPackedHeaderRawData) ||
3282                 (param->type == VAEncPackedHeaderSlice)) {
3283                 vaStatus = I965_RENDER_ENCODE_BUFFER(packed_header_params_ext);
3284             } else if((obj_config->profile == VAProfileHEVCMain) &&
3285                 (encode->last_packed_header_type == VAEncPackedHeaderSequence)) {
3286                 vaStatus = i965_encoder_render_packed_header_parameter_buffer(ctx,
3287                                                                           obj_context,
3288                                                                           obj_buffer,
3289                                                                           va_enc_packed_type_to_idx(encode->last_packed_header_type) + encode->vps_sps_seq_index);
3290             } else {
3291                 vaStatus = i965_encoder_render_packed_header_parameter_buffer(ctx,
3292                                                                           obj_context,
3293                                                                           obj_buffer,
3294                                                                           va_enc_packed_type_to_idx(encode->last_packed_header_type));
3295             }
3296             break;
3297         }
3298
3299         case VAEncPackedHeaderDataBufferType:
3300         {
3301             if (encode->last_packed_header_type == 0) {
3302                 WARN_ONCE("the packed header data is passed without type!\n");
3303                 vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
3304                 return vaStatus;
3305             }
3306
3307             if (encode->last_packed_header_type == VAEncPackedHeaderRawData ||
3308                 encode->last_packed_header_type == VAEncPackedHeaderSlice) {
3309                 vaStatus = I965_RENDER_ENCODE_BUFFER(packed_header_data_ext);
3310
3311                 if (obj_config->profile == VAProfileVP9Profile0)
3312                     break;
3313
3314                 /* When the PACKED_SLICE_HEADER flag is passed, it will use
3315                  * the packed_slice_header as the delimeter to decide how
3316                  * the packed rawdata is inserted for the given slice.
3317                  * Otherwise it will use the VAEncSequenceParameterBuffer
3318                  * as the delimeter
3319                  */
3320                 if (encode->packed_header_flag & VA_ENC_PACKED_HEADER_SLICE) {
3321                     /* store the first index of the packed header data for current slice */
3322                     if (encode->slice_rawdata_index[encode->slice_index] == 0) {
3323                         encode->slice_rawdata_index[encode->slice_index] =
3324                             SLICE_PACKED_DATA_INDEX_TYPE | (encode->num_packed_header_data_ext - 1);
3325                     }
3326                     encode->slice_rawdata_count[encode->slice_index]++;
3327                     if (encode->last_packed_header_type == VAEncPackedHeaderSlice) {
3328                         /* find one packed slice_header delimeter. And the following
3329                          * packed data is for the next slice
3330                          */
3331                         encode->slice_header_index[encode->slice_index] =
3332                             SLICE_PACKED_DATA_INDEX_TYPE | (encode->num_packed_header_data_ext - 1);
3333                         encode->slice_index++;
3334                         /* Reallocate the buffer to record the index/count of
3335                          * packed_data for one slice.
3336                          */
3337                         if (encode->slice_index == encode->max_slice_num) {
3338                             int slice_num = encode->max_slice_num;
3339
3340                             encode->slice_rawdata_index = realloc(encode->slice_rawdata_index,
3341                                                           (slice_num + NUM_SLICES) * sizeof(int));
3342                             encode->slice_rawdata_count = realloc(encode->slice_rawdata_count,
3343                                                           (slice_num + NUM_SLICES) * sizeof(int));
3344                             encode->slice_header_index = realloc(encode->slice_header_index,
3345                                                           (slice_num + NUM_SLICES) * sizeof(int));
3346                             memset(encode->slice_rawdata_index + slice_num, 0,
3347                                    sizeof(int) * NUM_SLICES);
3348                             memset(encode->slice_rawdata_count + slice_num, 0,
3349                                    sizeof(int) * NUM_SLICES);
3350                             memset(encode->slice_header_index + slice_num, 0,
3351                                    sizeof(int) * NUM_SLICES);
3352                             encode->max_slice_num += NUM_SLICES;
3353                         }
3354                     }
3355                 } else {
3356                     if (vaStatus == VA_STATUS_SUCCESS) {
3357                         /* store the first index of the packed header data for current slice */
3358                         if (encode->slice_rawdata_index[encode->slice_index] == 0) {
3359                             encode->slice_rawdata_index[encode->slice_index] =
3360                                 SLICE_PACKED_DATA_INDEX_TYPE | (encode->num_packed_header_data_ext - 1);
3361                         }
3362                         encode->slice_rawdata_count[encode->slice_index]++;
3363                         if (encode->last_packed_header_type == VAEncPackedHeaderSlice) {
3364                             if (encode->slice_header_index[encode->slice_index] == 0) {
3365                                 encode->slice_header_index[encode->slice_index] =
3366                                     SLICE_PACKED_DATA_INDEX_TYPE | (encode->num_packed_header_data_ext - 1);
3367                             } else {
3368                                 WARN_ONCE("Multi slice header data is passed for"
3369                                       " slice %d!\n", encode->slice_index);
3370                             }
3371                         }
3372                     }
3373                 }
3374             } else {
3375                 ASSERT_RET(encode->last_packed_header_type == VAEncPackedHeaderSequence ||
3376                     encode->last_packed_header_type == VAEncPackedHeaderPicture ||
3377                     encode->last_packed_header_type == VAEncPackedHeaderSlice ||
3378                    (((encode->last_packed_header_type & VAEncPackedHeaderMiscMask) == VAEncPackedHeaderMiscMask) &&
3379                     ((encode->last_packed_header_type & (~VAEncPackedHeaderMiscMask)) != 0)),
3380                     VA_STATUS_ERROR_ENCODING_ERROR);
3381
3382                 if((obj_config->profile == VAProfileHEVCMain) &&
3383                     (encode->last_packed_header_type == VAEncPackedHeaderSequence)) {
3384
3385                         vaStatus = i965_encoder_render_packed_header_data_buffer(ctx,
3386                             obj_context,
3387                             obj_buffer,
3388                             va_enc_packed_type_to_idx(encode->last_packed_header_type) + encode->vps_sps_seq_index);
3389                         encode->vps_sps_seq_index = (encode->vps_sps_seq_index + 1) % I965_SEQ_PACKED_HEADER_END;
3390                 }else{
3391                     vaStatus = i965_encoder_render_packed_header_data_buffer(ctx,
3392                         obj_context,
3393                         obj_buffer,
3394                         va_enc_packed_type_to_idx(encode->last_packed_header_type));
3395
3396                 }
3397             }
3398             encode->last_packed_header_type = 0;
3399             break;       
3400         }
3401
3402         case VAEncMiscParameterBufferType:
3403             vaStatus = i965_encoder_render_misc_parameter_buffer(ctx,
3404                                                                  obj_context,
3405                                                                  obj_buffer);
3406             break;
3407             
3408         case VAEncMacroblockMapBufferType:
3409             vaStatus = I965_RENDER_ENCODE_BUFFER(encmb_map);
3410             break;
3411
3412         default:
3413             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
3414             break;
3415         }
3416     }   
3417
3418     return vaStatus;
3419 }
3420
3421 #define I965_RENDER_PROC_BUFFER(name) I965_RENDER_BUFFER(proc, name)
3422
3423 #define DEF_RENDER_PROC_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(proc, name, member)
3424 DEF_RENDER_PROC_SINGLE_BUFFER_FUNC(pipeline_parameter, pipeline_param)    
3425
3426 static VAStatus 
3427 i965_proc_render_picture(VADriverContextP ctx,
3428                          VAContextID context,
3429                          VABufferID *buffers,
3430                          int num_buffers)
3431 {
3432     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3433     struct object_context *obj_context = CONTEXT(context);
3434     VAStatus vaStatus = VA_STATUS_SUCCESS;
3435     int i;
3436
3437     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
3438
3439     for (i = 0; i < num_buffers && vaStatus == VA_STATUS_SUCCESS; i++) {
3440         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
3441
3442         if (!obj_buffer)
3443             return VA_STATUS_ERROR_INVALID_BUFFER;
3444
3445         switch (obj_buffer->type) {
3446         case VAProcPipelineParameterBufferType:
3447             vaStatus = I965_RENDER_PROC_BUFFER(pipeline_parameter);
3448             break;
3449
3450         default:
3451             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
3452             break;
3453         }
3454     }
3455
3456     return vaStatus;
3457 }
3458
3459 VAStatus 
3460 i965_RenderPicture(VADriverContextP ctx,
3461                    VAContextID context,
3462                    VABufferID *buffers,
3463                    int num_buffers)
3464 {
3465     struct i965_driver_data *i965 = i965_driver_data(ctx);
3466     struct object_context *obj_context;
3467     struct object_config *obj_config;
3468     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
3469
3470     obj_context = CONTEXT(context);
3471     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
3472
3473     if (num_buffers <= 0)
3474         return VA_STATUS_ERROR_INVALID_PARAMETER;
3475
3476     obj_config = obj_context->obj_config;
3477     ASSERT_RET(obj_config, VA_STATUS_ERROR_INVALID_CONFIG);
3478
3479     if (VAEntrypointVideoProc == obj_config->entrypoint) {
3480         vaStatus = i965_proc_render_picture(ctx, context, buffers, num_buffers);
3481     } else if ((VAEntrypointEncSlice == obj_config->entrypoint ) || 
3482                (VAEntrypointEncPicture == obj_config->entrypoint) ||
3483                (VAEntrypointEncSliceLP == obj_config->entrypoint)) {
3484         vaStatus = i965_encoder_render_picture(ctx, context, buffers, num_buffers);
3485     } else {
3486         vaStatus = i965_decoder_render_picture(ctx, context, buffers, num_buffers);
3487     }
3488
3489     return vaStatus;
3490 }
3491
3492 VAStatus 
3493 i965_EndPicture(VADriverContextP ctx, VAContextID context)
3494 {
3495     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3496     struct object_context *obj_context = CONTEXT(context);
3497     struct object_config *obj_config;
3498
3499     ASSERT_RET(obj_context, VA_STATUS_ERROR_INVALID_CONTEXT);
3500     obj_config = obj_context->obj_config;
3501     ASSERT_RET(obj_config, VA_STATUS_ERROR_INVALID_CONFIG);
3502
3503     if (obj_context->codec_type == CODEC_PROC) {
3504         ASSERT_RET(VAEntrypointVideoProc == obj_config->entrypoint, VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT);
3505     } else if (obj_context->codec_type == CODEC_ENC) {
3506         ASSERT_RET(((VAEntrypointEncSlice == obj_config->entrypoint) ||
3507                     (VAEntrypointEncPicture == obj_config->entrypoint) ||
3508                     (VAEntrypointEncSliceLP == obj_config->entrypoint)),
3509                    VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT);
3510
3511         if (obj_context->codec_state.encode.num_packed_header_params_ext !=
3512                obj_context->codec_state.encode.num_packed_header_data_ext) {
3513             WARN_ONCE("the packed header/data is not paired for encoding!\n");
3514             return VA_STATUS_ERROR_INVALID_PARAMETER;
3515         }
3516         if (!(obj_context->codec_state.encode.pic_param ||
3517                 obj_context->codec_state.encode.pic_param_ext)) {
3518             return VA_STATUS_ERROR_INVALID_PARAMETER;
3519         }
3520         if (!(obj_context->codec_state.encode.seq_param ||
3521                 obj_context->codec_state.encode.seq_param_ext) &&
3522                 (VAEntrypointEncPicture != obj_config->entrypoint)) {
3523             /* The seq_param is not mandatory for VP9 encoding */
3524             if (obj_config->profile != VAProfileVP9Profile0)
3525                 return VA_STATUS_ERROR_INVALID_PARAMETER;
3526         }
3527         if ((obj_context->codec_state.encode.num_slice_params <=0) &&
3528                 (obj_context->codec_state.encode.num_slice_params_ext <=0) &&
3529                 ((obj_config->profile != VAProfileVP8Version0_3) &&
3530                  (obj_config->profile != VAProfileVP9Profile0))) {
3531             return VA_STATUS_ERROR_INVALID_PARAMETER;
3532         }
3533
3534         if ((obj_context->codec_state.encode.packed_header_flag & VA_ENC_PACKED_HEADER_SLICE) &&
3535             (obj_context->codec_state.encode.num_slice_params_ext !=
3536              obj_context->codec_state.encode.slice_index)) {
3537             WARN_ONCE("packed slice_header data is missing for some slice"
3538                       " under packed SLICE_HEADER mode\n");
3539             return VA_STATUS_ERROR_INVALID_PARAMETER;
3540         }
3541     } else {
3542         if (obj_context->codec_state.decode.pic_param == NULL) {
3543             return VA_STATUS_ERROR_INVALID_PARAMETER;
3544         }
3545         if (obj_context->codec_state.decode.num_slice_params <=0) {
3546             return VA_STATUS_ERROR_INVALID_PARAMETER;
3547         }
3548         if (obj_context->codec_state.decode.num_slice_datas <=0) {
3549             return VA_STATUS_ERROR_INVALID_PARAMETER;
3550         }
3551
3552         if (obj_context->codec_state.decode.num_slice_params !=
3553                 obj_context->codec_state.decode.num_slice_datas) {
3554             return VA_STATUS_ERROR_INVALID_PARAMETER;
3555         }
3556
3557         if (obj_context->wrapper_context != VA_INVALID_ID) {
3558             /* call the vaEndPicture of wrapped driver */
3559             VADriverContextP pdrvctx;
3560             VAStatus va_status;
3561
3562             pdrvctx = i965->wrapper_pdrvctx;
3563             CALL_VTABLE(pdrvctx, va_status,
3564                         vaEndPicture(pdrvctx, obj_context->wrapper_context));
3565
3566             return va_status;
3567         }
3568     }
3569
3570     ASSERT_RET(obj_context->hw_context->run, VA_STATUS_ERROR_OPERATION_FAILED);
3571     return obj_context->hw_context->run(ctx, obj_config->profile, &obj_context->codec_state, obj_context->hw_context);
3572 }
3573
3574 VAStatus 
3575 i965_SyncSurface(VADriverContextP ctx,
3576                  VASurfaceID render_target)
3577 {
3578     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3579     struct object_surface *obj_surface = SURFACE(render_target);
3580
3581     ASSERT_RET(obj_surface, VA_STATUS_ERROR_INVALID_SURFACE);
3582
3583     if(obj_surface->bo)
3584         drm_intel_bo_wait_rendering(obj_surface->bo);
3585
3586     return VA_STATUS_SUCCESS;
3587 }
3588
3589 VAStatus 
3590 i965_QuerySurfaceStatus(VADriverContextP ctx,
3591                         VASurfaceID render_target,
3592                         VASurfaceStatus *status)        /* out */
3593 {
3594     struct i965_driver_data *i965 = i965_driver_data(ctx); 
3595     struct object_surface *obj_surface = SURFACE(render_target);
3596
3597     ASSERT_RET(obj_surface, VA_STATUS_ERROR_INVALID_SURFACE);
3598
3599     if (obj_surface->bo) {
3600         if (drm_intel_bo_busy(obj_surface->bo)){
3601             *status = VASurfaceRendering;
3602         }
3603         else {
3604             *status = VASurfaceReady;
3605         }
3606     } else {
3607         *status = VASurfaceReady;
3608     }
3609
3610     return VA_STATUS_SUCCESS;
3611 }
3612
3613 static VADisplayAttribute *
3614 get_display_attribute(VADriverContextP ctx, VADisplayAttribType type)
3615 {
3616     struct i965_driver_data * const i965 = i965_driver_data(ctx);
3617     unsigned int i;
3618
3619     if (!i965->display_attributes)
3620         return NULL;
3621
3622     for (i = 0; i < i965->num_display_attributes; i++) {
3623         if (i965->display_attributes[i].type == type)
3624             return &i965->display_attributes[i];
3625     }
3626     return NULL;
3627 }
3628
3629 static void
3630 i965_display_attributes_terminate(VADriverContextP ctx)
3631 {
3632     struct i965_driver_data * const i965 = i965_driver_data(ctx);
3633
3634     if (i965->display_attributes) {
3635         free(i965->display_attributes);
3636         i965->display_attributes = NULL;
3637         i965->num_display_attributes = 0;
3638     }
3639 }
3640
3641 static bool
3642 i965_display_attributes_init(VADriverContextP ctx)
3643 {
3644     struct i965_driver_data * const i965 = i965_driver_data(ctx);
3645
3646     i965->num_display_attributes = ARRAY_ELEMS(i965_display_attributes);
3647     i965->display_attributes = malloc(
3648         i965->num_display_attributes * sizeof(i965->display_attributes[0]));
3649     if (!i965->display_attributes)
3650         goto error;
3651
3652     memcpy(
3653         i965->display_attributes,
3654         i965_display_attributes,
3655         sizeof(i965_display_attributes)
3656     );
3657
3658     i965->rotation_attrib = get_display_attribute(ctx, VADisplayAttribRotation);
3659     i965->brightness_attrib = get_display_attribute(ctx, VADisplayAttribBrightness);
3660     i965->contrast_attrib = get_display_attribute(ctx, VADisplayAttribContrast);
3661     i965->hue_attrib = get_display_attribute(ctx, VADisplayAttribHue);
3662     i965->saturation_attrib = get_display_attribute(ctx, VADisplayAttribSaturation);
3663
3664     if (!i965->rotation_attrib ||
3665         !i965->brightness_attrib ||
3666         !i965->contrast_attrib ||
3667         !i965->hue_attrib ||
3668         !i965->saturation_attrib) {
3669         goto error;
3670     }
3671     return true;
3672
3673 error:
3674     i965_display_attributes_terminate(ctx);
3675     return false;
3676 }
3677
3678 /* 
3679  * Query display attributes 
3680  * The caller must provide a "attr_list" array that can hold at
3681  * least vaMaxNumDisplayAttributes() entries. The actual number of attributes
3682  * returned in "attr_list" is returned in "num_attributes".
3683  */
3684 VAStatus 
3685 i965_QueryDisplayAttributes(
3686     VADriverContextP    ctx,
3687     VADisplayAttribute *attribs,        /* out */
3688     int                *num_attribs_ptr /* out */
3689 )
3690 {
3691     const int num_attribs = ARRAY_ELEMS(i965_display_attributes);
3692
3693     if (attribs && num_attribs > 0)
3694         memcpy(attribs, i965_display_attributes, sizeof(i965_display_attributes));
3695
3696     if (num_attribs_ptr)
3697         *num_attribs_ptr = num_attribs;
3698
3699     return VA_STATUS_SUCCESS;
3700 }
3701
3702 /* 
3703  * Get display attributes 
3704  * This function returns the current attribute values in "attr_list".
3705  * Only attributes returned with VA_DISPLAY_ATTRIB_GETTABLE set in the "flags" field
3706  * from vaQueryDisplayAttributes() can have their values retrieved.  
3707  */
3708 VAStatus 
3709 i965_GetDisplayAttributes(
3710     VADriverContextP    ctx,
3711     VADisplayAttribute *attribs,        /* inout */
3712     int                 num_attribs     /* in */
3713 )
3714 {
3715     int i;
3716
3717     for (i = 0; i < num_attribs; i++) {
3718         VADisplayAttribute *src_attrib, * const dst_attrib = &attribs[i];
3719
3720         src_attrib = get_display_attribute(ctx, dst_attrib->type);
3721         if (src_attrib && (src_attrib->flags & VA_DISPLAY_ATTRIB_GETTABLE)) {
3722             dst_attrib->min_value = src_attrib->min_value;
3723             dst_attrib->max_value = src_attrib->max_value;
3724             dst_attrib->value     = src_attrib->value;
3725         }
3726         else
3727             dst_attrib->flags = VA_DISPLAY_ATTRIB_NOT_SUPPORTED;
3728     }
3729     return VA_STATUS_SUCCESS;
3730 }
3731
3732 /* 
3733  * Set display attributes 
3734  * Only attributes returned with VA_DISPLAY_ATTRIB_SETTABLE set in the "flags" field
3735  * from vaQueryDisplayAttributes() can be set.  If the attribute is not settable or 
3736  * the value is out of range, the function returns VA_STATUS_ERROR_ATTR_NOT_SUPPORTED
3737  */
3738 VAStatus 
3739 i965_SetDisplayAttributes(
3740     VADriverContextP    ctx,
3741     VADisplayAttribute *attribs,        /* in */
3742     int                 num_attribs     /* in */
3743 )
3744 {
3745     int i;
3746
3747     for (i = 0; i < num_attribs; i++) {
3748         VADisplayAttribute *dst_attrib, * const src_attrib = &attribs[i];
3749
3750         dst_attrib = get_display_attribute(ctx, src_attrib->type);
3751         if (!dst_attrib)
3752             return VA_STATUS_ERROR_ATTR_NOT_SUPPORTED;
3753
3754         if (!(dst_attrib->flags & VA_DISPLAY_ATTRIB_SETTABLE))
3755             continue;
3756
3757         if (src_attrib->value < dst_attrib->min_value ||
3758             src_attrib->value > dst_attrib->max_value)
3759             return VA_STATUS_ERROR_INVALID_PARAMETER;
3760
3761         dst_attrib->value = src_attrib->value;
3762         /* XXX: track modified attributes through timestamps */
3763     }
3764     return VA_STATUS_SUCCESS;
3765 }
3766
3767 VAStatus 
3768 i965_DbgCopySurfaceToBuffer(VADriverContextP ctx,
3769                             VASurfaceID surface,
3770                             void **buffer,              /* out */
3771                             unsigned int *stride)       /* out */
3772 {
3773     /* TODO */
3774     return VA_STATUS_ERROR_UNIMPLEMENTED;
3775 }
3776
3777 static void
3778 i965_destroy_heap(struct object_heap *heap, 
3779                   void (*func)(struct object_heap *heap, struct object_base *object))
3780 {
3781     struct object_base *object;
3782     object_heap_iterator iter;    
3783
3784     object = object_heap_first(heap, &iter);
3785
3786     while (object) {
3787         if (func)
3788             func(heap, object);
3789
3790         object = object_heap_next(heap, &iter);
3791     }
3792
3793     object_heap_destroy(heap);
3794 }
3795
3796
3797 VAStatus 
3798 i965_DestroyImage(VADriverContextP ctx, VAImageID image);
3799
3800 VAStatus 
3801 i965_CreateImage(VADriverContextP ctx,
3802                  VAImageFormat *format,
3803                  int width,
3804                  int height,
3805                  VAImage *out_image)        /* out */
3806 {
3807     struct i965_driver_data *i965 = i965_driver_data(ctx);
3808     struct object_image *obj_image;
3809     VAStatus va_status = VA_STATUS_ERROR_OPERATION_FAILED;
3810     VAImageID image_id;
3811     unsigned int size2, size, awidth, aheight;
3812
3813     out_image->image_id = VA_INVALID_ID;
3814     out_image->buf      = VA_INVALID_ID;
3815
3816     image_id = NEW_IMAGE_ID();
3817     if (image_id == VA_INVALID_ID)
3818         return VA_STATUS_ERROR_ALLOCATION_FAILED;
3819
3820     obj_image = IMAGE(image_id);
3821     if (!obj_image)
3822         return VA_STATUS_ERROR_ALLOCATION_FAILED;
3823     obj_image->bo         = NULL;
3824     obj_image->palette    = NULL;
3825     obj_image->derived_surface = VA_INVALID_ID;
3826
3827     VAImage * const image = &obj_image->image;
3828     image->image_id       = image_id;
3829     image->buf            = VA_INVALID_ID;
3830
3831     awidth = ALIGN(width, i965->codec_info->min_linear_wpitch);
3832
3833     if ((format->fourcc == VA_FOURCC_YV12) ||
3834         (format->fourcc == VA_FOURCC_I420)) {
3835             if (awidth % 128 != 0) {
3836                 awidth = ALIGN(width, 128);     
3837             }
3838     }
3839
3840     aheight = ALIGN(height, i965->codec_info->min_linear_hpitch);
3841     size    = awidth * aheight;
3842     size2    = (awidth / 2) * (aheight / 2);
3843
3844     image->num_palette_entries = 0;
3845     image->entry_bytes         = 0;
3846     memset(image->component_order, 0, sizeof(image->component_order));
3847
3848     switch (format->fourcc) {
3849     case VA_FOURCC_IA44:
3850     case VA_FOURCC_AI44:
3851         image->num_planes = 1;
3852         image->pitches[0] = awidth;
3853         image->offsets[0] = 0;
3854         image->data_size  = image->offsets[0] + image->pitches[0] * aheight;
3855         image->num_palette_entries = 16;
3856         image->entry_bytes         = 3;
3857         image->component_order[0]  = 'R';
3858         image->component_order[1]  = 'G';
3859         image->component_order[2]  = 'B';
3860         break;
3861     case VA_FOURCC_IA88:
3862     case VA_FOURCC_AI88:
3863         image->num_planes = 1;
3864         image->pitches[0] = awidth * 2;
3865         image->offsets[0] = 0;
3866         image->data_size  = image->offsets[0] + image->pitches[0] * aheight;
3867         image->num_palette_entries = 256;
3868         image->entry_bytes         = 3;
3869         image->component_order[0]  = 'R';
3870         image->component_order[1]  = 'G';
3871         image->component_order[2]  = 'B';
3872         break;
3873     case VA_FOURCC_ARGB:
3874     case VA_FOURCC_ABGR:
3875     case VA_FOURCC_BGRA:
3876     case VA_FOURCC_RGBA:
3877     case VA_FOURCC_BGRX:
3878     case VA_FOURCC_RGBX:
3879         image->num_planes = 1;
3880         image->pitches[0] = awidth * 4;
3881         image->offsets[0] = 0;
3882         image->data_size  = image->offsets[0] + image->pitches[0] * aheight;
3883         break;
3884     case VA_FOURCC_YV12:
3885         image->num_planes = 3;
3886         image->pitches[0] = awidth;
3887         image->offsets[0] = 0;
3888         image->pitches[1] = awidth / 2;
3889         image->offsets[1] = size;
3890         image->pitches[2] = awidth / 2;
3891         image->offsets[2] = size + size2;
3892         image->data_size  = size + 2 * size2;
3893         break;
3894     case VA_FOURCC_I420:
3895         image->num_planes = 3;
3896         image->pitches[0] = awidth;
3897         image->offsets[0] = 0;
3898         image->pitches[1] = awidth / 2;
3899         image->offsets[1] = size;
3900         image->pitches[2] = awidth / 2;
3901         image->offsets[2] = size + size2;
3902         image->data_size  = size + 2 * size2;
3903         break;
3904     case VA_FOURCC_422H:
3905         image->num_planes = 3;
3906         image->pitches[0] = awidth;
3907         image->offsets[0] = 0;
3908         image->pitches[1] = awidth / 2;
3909         image->offsets[1] = size;
3910         image->pitches[2] = awidth / 2;
3911         image->offsets[2] = size + (awidth / 2) * aheight;
3912         image->data_size  = size + 2 * ((awidth / 2) * aheight);
3913         break;
3914     case VA_FOURCC_NV12:
3915         image->num_planes = 2;
3916         image->pitches[0] = awidth;
3917         image->offsets[0] = 0;
3918         image->pitches[1] = awidth;
3919         image->offsets[1] = size;
3920         image->data_size  = size + 2 * size2;
3921         break;
3922     case VA_FOURCC_YUY2:
3923     case VA_FOURCC_UYVY:
3924         image->num_planes = 1;
3925         image->pitches[0] = awidth * 2;
3926         image->offsets[0] = 0;
3927         image->data_size  = size * 2;
3928         break;
3929     case VA_FOURCC_P010:
3930         image->num_planes = 2;
3931         image->pitches[0] = awidth * 2;
3932         image->offsets[0] = 0;
3933         image->pitches[1] = awidth * 2;
3934         image->offsets[1] = size * 2;
3935         image->data_size  = size * 2 + 2 * size2 * 2;
3936         break;
3937     default:
3938         goto error;
3939     }
3940
3941     va_status = i965_CreateBuffer(ctx, 0, VAImageBufferType,
3942                                   image->data_size, 1, NULL, &image->buf);
3943     if (va_status != VA_STATUS_SUCCESS)
3944         goto error;
3945
3946     struct object_buffer *obj_buffer = BUFFER(image->buf);
3947
3948     if (!obj_buffer ||
3949         !obj_buffer->buffer_store ||
3950         !obj_buffer->buffer_store->bo)
3951         return VA_STATUS_ERROR_ALLOCATION_FAILED;
3952
3953     obj_image->bo = obj_buffer->buffer_store->bo;
3954     dri_bo_reference(obj_image->bo);
3955
3956     if (image->num_palette_entries > 0 && image->entry_bytes > 0) {
3957         obj_image->palette = malloc(image->num_palette_entries * sizeof(*obj_image->palette));
3958         if (!obj_image->palette)
3959             goto error;
3960     }
3961
3962     image->image_id             = image_id;
3963     image->format               = *format;
3964     image->width                = width;
3965     image->height               = height;
3966
3967     *out_image                  = *image;
3968     return VA_STATUS_SUCCESS;
3969
3970  error:
3971     i965_DestroyImage(ctx, image_id);
3972     return va_status;
3973 }
3974
3975 VAStatus
3976 i965_check_alloc_surface_bo(VADriverContextP ctx,
3977                             struct object_surface *obj_surface,
3978                             int tiled,
3979                             unsigned int fourcc,
3980                             unsigned int subsampling)
3981 {
3982     struct i965_driver_data *i965 = i965_driver_data(ctx);
3983     int region_width, region_height;
3984
3985     if (obj_surface->bo) {
3986         ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
3987         ASSERT_RET(obj_surface->fourcc == fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
3988         ASSERT_RET(obj_surface->subsampling == subsampling, VA_STATUS_ERROR_INVALID_SURFACE);
3989         return VA_STATUS_SUCCESS;
3990     }
3991
3992     obj_surface->x_cb_offset = 0; /* X offset is always 0 */
3993     obj_surface->x_cr_offset = 0;
3994
3995     int bpp_1stplane = bpp_1stplane_by_fourcc(fourcc);
3996
3997     if ((tiled && !obj_surface->user_disable_tiling)) {
3998         ASSERT_RET(fourcc != VA_FOURCC_I420 &&
3999                fourcc != VA_FOURCC_IYUV &&
4000                fourcc != VA_FOURCC_YV12,
4001                VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT);
4002
4003         if (obj_surface->user_h_stride_set) {
4004            ASSERT_RET(IS_ALIGNED(obj_surface->width, 128), VA_STATUS_ERROR_INVALID_PARAMETER);
4005         } else
4006           obj_surface->width = ALIGN(obj_surface->orig_width * bpp_1stplane, 128);
4007
4008         if (obj_surface->user_v_stride_set) {
4009           ASSERT_RET(IS_ALIGNED(obj_surface->height, 32), VA_STATUS_ERROR_INVALID_PARAMETER);
4010         }else
4011           obj_surface->height = ALIGN(obj_surface->orig_height, 32);
4012
4013         region_height = obj_surface->height;
4014
4015         switch (fourcc) {
4016         case VA_FOURCC_NV12:
4017         case VA_FOURCC_P010:
4018             assert(subsampling == SUBSAMPLE_YUV420);
4019             obj_surface->cb_cr_pitch = obj_surface->width;
4020             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4021             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4022             obj_surface->y_cb_offset = obj_surface->height;
4023             obj_surface->y_cr_offset = obj_surface->height;
4024             region_width = obj_surface->width;
4025             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32);
4026             
4027             break;
4028
4029         case VA_FOURCC_IMC1:
4030             assert(subsampling == SUBSAMPLE_YUV420);
4031             obj_surface->cb_cr_pitch = obj_surface->width;
4032             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4033             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4034             obj_surface->y_cr_offset = obj_surface->height;
4035             obj_surface->y_cb_offset = obj_surface->y_cr_offset + ALIGN(obj_surface->cb_cr_height, 32);
4036             region_width = obj_surface->width;
4037             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4038
4039             break;
4040
4041         case VA_FOURCC_IMC3:
4042             assert(subsampling == SUBSAMPLE_YUV420);
4043             obj_surface->cb_cr_pitch = obj_surface->width;
4044             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4045             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4046             obj_surface->y_cb_offset = obj_surface->height;
4047             obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
4048             region_width = obj_surface->width;
4049             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4050             
4051             break;
4052
4053         case VA_FOURCC_422H:
4054             assert(subsampling == SUBSAMPLE_YUV422H);
4055             obj_surface->cb_cr_pitch = obj_surface->width;
4056             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4057             obj_surface->cb_cr_height = obj_surface->orig_height;
4058             obj_surface->y_cb_offset = obj_surface->height;
4059             obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
4060             region_width = obj_surface->width;
4061             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4062
4063             break;
4064
4065         case VA_FOURCC_422V:
4066             assert(subsampling == SUBSAMPLE_YUV422V);
4067             obj_surface->cb_cr_pitch = obj_surface->width;
4068             obj_surface->cb_cr_width = obj_surface->orig_width;
4069             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4070             obj_surface->y_cb_offset = obj_surface->height;
4071             obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
4072             region_width = obj_surface->width;
4073             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4074
4075             break;
4076
4077         case VA_FOURCC_411P:
4078             assert(subsampling == SUBSAMPLE_YUV411);
4079             obj_surface->cb_cr_pitch = obj_surface->width;
4080             obj_surface->cb_cr_width = obj_surface->orig_width / 4;
4081             obj_surface->cb_cr_height = obj_surface->orig_height;
4082             obj_surface->y_cb_offset = obj_surface->height;
4083             obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
4084             region_width = obj_surface->width;
4085             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4086
4087             break;
4088
4089         case VA_FOURCC_444P:
4090             assert(subsampling == SUBSAMPLE_YUV444);
4091             obj_surface->cb_cr_pitch = obj_surface->width;
4092             obj_surface->cb_cr_width = obj_surface->orig_width;
4093             obj_surface->cb_cr_height = obj_surface->orig_height;
4094             obj_surface->y_cb_offset = obj_surface->height;
4095             obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
4096             region_width = obj_surface->width;
4097             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
4098
4099             break;
4100
4101         case VA_FOURCC_Y800:
4102             assert(subsampling == SUBSAMPLE_YUV400);
4103             obj_surface->cb_cr_pitch = 0;
4104             obj_surface->cb_cr_width = 0;
4105             obj_surface->cb_cr_height = 0;
4106             obj_surface->y_cb_offset = 0;
4107             obj_surface->y_cr_offset = 0;
4108             region_width = obj_surface->width;
4109             region_height = obj_surface->height;
4110
4111             break;
4112
4113         case VA_FOURCC_YUY2:
4114         case VA_FOURCC_UYVY:
4115             assert(subsampling == SUBSAMPLE_YUV422H);
4116             obj_surface->width = ALIGN(obj_surface->orig_width * 2, 128);
4117             obj_surface->cb_cr_pitch = obj_surface->width;
4118             obj_surface->y_cb_offset = 0; 
4119             obj_surface->y_cr_offset = 0; 
4120             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4121             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4122             region_width = obj_surface->width;
4123             region_height = obj_surface->height;
4124             
4125             break;
4126
4127         case VA_FOURCC_RGBA:
4128         case VA_FOURCC_RGBX:
4129         case VA_FOURCC_BGRA:
4130         case VA_FOURCC_BGRX:
4131             assert(subsampling == SUBSAMPLE_RGBX);
4132
4133             obj_surface->width = ALIGN(obj_surface->orig_width * 4, 128);
4134             region_width = obj_surface->width;
4135             region_height = obj_surface->height;
4136             break;
4137
4138         default:
4139             /* Never get here */
4140             ASSERT_RET(0, VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT);
4141             break;
4142         }
4143     } else {
4144         assert(subsampling == SUBSAMPLE_YUV420 || 
4145                subsampling == SUBSAMPLE_YUV422H || 
4146                subsampling == SUBSAMPLE_YUV422V ||
4147                subsampling == SUBSAMPLE_RGBX);
4148
4149         region_width = obj_surface->width;
4150         region_height = obj_surface->height;
4151
4152         switch (fourcc) {
4153         case VA_FOURCC_NV12:
4154         case VA_FOURCC_P010:
4155             obj_surface->y_cb_offset = obj_surface->height;
4156             obj_surface->y_cr_offset = obj_surface->height;
4157             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4158             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4159             obj_surface->cb_cr_pitch = obj_surface->width;
4160             region_height = obj_surface->height + obj_surface->height / 2;
4161             break;
4162
4163         case VA_FOURCC_YV16:
4164             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4165             obj_surface->cb_cr_height = obj_surface->orig_height;
4166             obj_surface->y_cr_offset = obj_surface->height;
4167             obj_surface->y_cb_offset = obj_surface->y_cr_offset + ALIGN(obj_surface->cb_cr_height, 32) / 2;
4168             obj_surface->cb_cr_pitch = obj_surface->width / 2;
4169             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32);
4170             break;
4171
4172         case VA_FOURCC_YV12:
4173         case VA_FOURCC_I420:
4174             if (fourcc == VA_FOURCC_YV12) {
4175                 obj_surface->y_cr_offset = obj_surface->height;
4176                 obj_surface->y_cb_offset = obj_surface->height + obj_surface->height / 4;
4177             } else {
4178                 obj_surface->y_cb_offset = obj_surface->height;
4179                 obj_surface->y_cr_offset = obj_surface->height + obj_surface->height / 4;
4180             }
4181
4182             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4183             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
4184             obj_surface->cb_cr_pitch = obj_surface->width / 2;
4185             region_height = obj_surface->height + obj_surface->height / 2;
4186             break;
4187
4188         case VA_FOURCC_YUY2:
4189         case VA_FOURCC_UYVY:
4190             obj_surface->width = ALIGN(obj_surface->orig_width * 2, i965->codec_info->min_linear_wpitch);
4191             obj_surface->y_cb_offset = 0;
4192             obj_surface->y_cr_offset = 0;
4193             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
4194             obj_surface->cb_cr_height = obj_surface->orig_height;
4195             obj_surface->cb_cr_pitch = obj_surface->width;
4196             region_width = obj_surface->width;
4197             region_height = obj_surface->height;
4198             break;
4199         case VA_FOURCC_RGBA:
4200         case VA_FOURCC_RGBX:
4201         case VA_FOURCC_BGRA:
4202         case VA_FOURCC_BGRX:
4203             obj_surface->width = ALIGN(obj_surface->orig_width * 4, i965->codec_info->min_linear_wpitch);
4204             region_width = obj_surface->width;
4205             region_height = obj_surface->height;
4206             break;
4207
4208         default:
4209             /* Never get here */
4210             ASSERT_RET(0, VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT);
4211             break;
4212         }
4213     }
4214
4215     obj_surface->size = ALIGN(region_width * region_height, 0x1000);
4216
4217     if ((tiled && !obj_surface->user_disable_tiling)) {
4218         uint32_t tiling_mode = I915_TILING_Y; /* always uses Y-tiled format */
4219         unsigned long pitch;
4220
4221         obj_surface->bo = drm_intel_bo_alloc_tiled(i965->intel.bufmgr, 
4222                                                    "vaapi surface",
4223                                                    region_width,
4224                                                    region_height,
4225                                                    1,
4226                                                    &tiling_mode,
4227                                                    &pitch,
4228                                                    0);
4229         assert(tiling_mode == I915_TILING_Y);
4230         assert(pitch == obj_surface->width);
4231     } else {
4232         obj_surface->bo = dri_bo_alloc(i965->intel.bufmgr,
4233                                        "vaapi surface",
4234                                        obj_surface->size,
4235                                        0x1000);
4236     }
4237
4238     obj_surface->fourcc = fourcc;
4239     obj_surface->subsampling = subsampling;
4240     assert(obj_surface->bo);
4241     return VA_STATUS_SUCCESS;
4242 }
4243
4244 VAStatus i965_DeriveImage(VADriverContextP ctx,
4245                           VASurfaceID surface,
4246                           VAImage *out_image)        /* out */
4247 {
4248     struct i965_driver_data *i965 = i965_driver_data(ctx);
4249     struct object_image *obj_image;
4250     struct object_surface *obj_surface; 
4251     VAImageID image_id;
4252     unsigned int w_pitch;
4253     VAStatus va_status = VA_STATUS_ERROR_OPERATION_FAILED;
4254
4255     out_image->image_id = VA_INVALID_ID;
4256     obj_surface = SURFACE(surface);
4257
4258     if (!obj_surface)
4259         return VA_STATUS_ERROR_INVALID_SURFACE;
4260
4261     if (!obj_surface->bo) {
4262         unsigned int is_tiled = 0;
4263         unsigned int fourcc = VA_FOURCC_YV12;
4264         i965_guess_surface_format(ctx, surface, &fourcc, &is_tiled);
4265         int sampling = get_sampling_from_fourcc(fourcc);
4266         va_status = i965_check_alloc_surface_bo(ctx, obj_surface, is_tiled, fourcc, sampling);
4267         if (va_status != VA_STATUS_SUCCESS)
4268             return va_status;
4269     }
4270
4271     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
4272
4273     w_pitch = obj_surface->width;
4274
4275     image_id = NEW_IMAGE_ID();
4276
4277     if (image_id == VA_INVALID_ID)
4278         return VA_STATUS_ERROR_ALLOCATION_FAILED;
4279
4280     obj_image = IMAGE(image_id);
4281     
4282     if (!obj_image)
4283         return VA_STATUS_ERROR_ALLOCATION_FAILED;
4284
4285     obj_image->bo = NULL;
4286     obj_image->palette = NULL;
4287     obj_image->derived_surface = VA_INVALID_ID;
4288
4289     VAImage * const image = &obj_image->image;
4290     
4291     memset(image, 0, sizeof(*image));
4292     image->image_id = image_id;
4293     image->buf = VA_INVALID_ID;
4294     image->num_palette_entries = 0;
4295     image->entry_bytes = 0;
4296     image->width = obj_surface->orig_width;
4297     image->height = obj_surface->orig_height;
4298     image->data_size = obj_surface->size;
4299
4300     image->format.fourcc = obj_surface->fourcc;
4301     image->format.byte_order = VA_LSB_FIRST;
4302     image->format.bits_per_pixel = get_bpp_from_fourcc(obj_surface->fourcc);
4303
4304     if (!image->format.bits_per_pixel)
4305         goto error;
4306
4307     switch (image->format.fourcc) {
4308     case VA_FOURCC_YV12:
4309         image->num_planes = 3;
4310         image->pitches[0] = w_pitch; /* Y */
4311         image->offsets[0] = 0;
4312         image->pitches[1] = obj_surface->cb_cr_pitch; /* V */
4313         image->offsets[1] = w_pitch * obj_surface->y_cr_offset;
4314         image->pitches[2] = obj_surface->cb_cr_pitch; /* U */
4315         image->offsets[2] = w_pitch * obj_surface->y_cb_offset;
4316         break;
4317
4318     case VA_FOURCC_YV16:
4319         image->num_planes = 3;
4320         image->pitches[0] = w_pitch; /* Y */
4321         image->offsets[0] = 0;
4322         image->pitches[1] = obj_surface->cb_cr_pitch; /* V */
4323         image->offsets[1] = w_pitch * obj_surface->y_cr_offset;
4324         image->pitches[2] = obj_surface->cb_cr_pitch; /* U */
4325         image->offsets[2] = w_pitch * obj_surface->y_cb_offset;
4326         break;
4327
4328     case VA_FOURCC_NV12:
4329     case VA_FOURCC_P010:
4330         image->num_planes = 2;
4331         image->pitches[0] = w_pitch; /* Y */
4332         image->offsets[0] = 0;
4333         image->pitches[1] = obj_surface->cb_cr_pitch; /* UV */
4334         image->offsets[1] = w_pitch * obj_surface->y_cb_offset;
4335         break;
4336
4337     case VA_FOURCC_I420:
4338     case VA_FOURCC_422H:
4339     case VA_FOURCC_IMC3:
4340     case VA_FOURCC_444P:
4341     case VA_FOURCC_422V:
4342     case VA_FOURCC_411P:
4343         image->num_planes = 3;
4344         image->pitches[0] = w_pitch; /* Y */
4345         image->offsets[0] = 0;
4346         image->pitches[1] = obj_surface->cb_cr_pitch; /* U */
4347         image->offsets[1] = w_pitch * obj_surface->y_cb_offset;
4348         image->pitches[2] = obj_surface->cb_cr_pitch; /* V */
4349         image->offsets[2] = w_pitch * obj_surface->y_cr_offset;
4350         break;
4351
4352     case VA_FOURCC_YUY2:
4353     case VA_FOURCC_UYVY:
4354     case VA_FOURCC_Y800:
4355         image->num_planes = 1;
4356         image->pitches[0] = obj_surface->width; /* Y, width is aligned already */
4357         image->offsets[0] = 0;
4358         break;
4359     case VA_FOURCC_RGBA:
4360     case VA_FOURCC_RGBX:
4361     case VA_FOURCC_BGRA:
4362     case VA_FOURCC_BGRX:
4363         image->num_planes = 1;
4364         image->pitches[0] = obj_surface->width;
4365
4366         switch (image->format.fourcc) {
4367         case VA_FOURCC_RGBA:
4368         case VA_FOURCC_RGBX:
4369             image->format.red_mask = 0x000000ff;
4370             image->format.green_mask = 0x0000ff00;
4371             image->format.blue_mask = 0x00ff0000;
4372             break;
4373         case VA_FOURCC_BGRA:
4374         case VA_FOURCC_BGRX:
4375             image->format.red_mask = 0x00ff0000;
4376             image->format.green_mask = 0x0000ff00;
4377             image->format.blue_mask = 0x000000ff;
4378             break;
4379         default:
4380             goto error;
4381         }
4382
4383         switch (image->format.fourcc) {
4384         case VA_FOURCC_RGBA:
4385         case VA_FOURCC_BGRA:
4386             image->format.alpha_mask = 0xff000000;
4387             image->format.depth = 32;
4388             break;
4389         case VA_FOURCC_RGBX:
4390         case VA_FOURCC_BGRX:
4391             image->format.alpha_mask = 0x00000000;
4392             image->format.depth = 24;
4393             break;
4394         default:
4395             goto error;
4396         }
4397
4398         break;
4399     default:
4400         goto error;
4401     }
4402
4403     va_status = i965_create_buffer_internal(ctx, 0, VAImageBufferType,
4404                                             obj_surface->size, 1, NULL, obj_surface->bo, &image->buf);
4405     if (va_status != VA_STATUS_SUCCESS)
4406         goto error;
4407
4408     struct object_buffer *obj_buffer = BUFFER(image->buf);
4409
4410     if (!obj_buffer ||
4411         !obj_buffer->buffer_store ||
4412         !obj_buffer->buffer_store->bo)
4413         return VA_STATUS_ERROR_ALLOCATION_FAILED;
4414
4415     obj_image->bo = obj_buffer->buffer_store->bo;
4416     dri_bo_reference(obj_image->bo);
4417
4418     if (image->num_palette_entries > 0 && image->entry_bytes > 0) {
4419         obj_image->palette = malloc(image->num_palette_entries * sizeof(*obj_image->palette));
4420         if (!obj_image->palette) {
4421             va_status = VA_STATUS_ERROR_ALLOCATION_FAILED;
4422             goto error;
4423         }
4424     }
4425
4426     *out_image = *image;
4427     obj_surface->flags |= SURFACE_DERIVED;
4428     obj_surface->derived_image_id = image_id;
4429     obj_image->derived_surface = surface;
4430
4431     return VA_STATUS_SUCCESS;
4432
4433  error:
4434     i965_DestroyImage(ctx, image_id);
4435     return va_status;
4436 }
4437
4438 static void 
4439 i965_destroy_image(struct object_heap *heap, struct object_base *obj)
4440 {
4441     object_heap_free(heap, obj);
4442 }
4443
4444
4445 VAStatus 
4446 i965_DestroyImage(VADriverContextP ctx, VAImageID image)
4447 {
4448     struct i965_driver_data *i965 = i965_driver_data(ctx);
4449     struct object_image *obj_image = IMAGE(image); 
4450     struct object_surface *obj_surface; 
4451
4452     if (!obj_image)
4453         return VA_STATUS_SUCCESS;
4454
4455     dri_bo_unreference(obj_image->bo);
4456     obj_image->bo = NULL;
4457
4458     if (obj_image->image.buf != VA_INVALID_ID) {
4459         i965_DestroyBuffer(ctx, obj_image->image.buf);
4460         obj_image->image.buf = VA_INVALID_ID;
4461     }
4462
4463     if (obj_image->palette) {
4464         free(obj_image->palette);
4465         obj_image->palette = NULL;
4466     }
4467
4468     obj_surface = SURFACE(obj_image->derived_surface);
4469
4470     if (obj_surface) {
4471         obj_surface->flags &= ~SURFACE_DERIVED;
4472         obj_surface->derived_image_id = VA_INVALID_ID;
4473     }
4474
4475     i965_destroy_image(&i965->image_heap, (struct object_base *)obj_image);
4476
4477     return VA_STATUS_SUCCESS;
4478 }
4479
4480 /*
4481  * pointer to an array holding the palette data.  The size of the array is
4482  * num_palette_entries * entry_bytes in size.  The order of the components
4483  * in the palette is described by the component_order in VASubpicture struct
4484  */
4485 VAStatus 
4486 i965_SetImagePalette(VADriverContextP ctx,
4487                      VAImageID image,
4488                      unsigned char *palette)
4489 {
4490     struct i965_driver_data *i965 = i965_driver_data(ctx);
4491     unsigned int i;
4492
4493     struct object_image *obj_image = IMAGE(image);
4494     if (!obj_image)
4495         return VA_STATUS_ERROR_INVALID_IMAGE;
4496
4497     if (!obj_image->palette)
4498         return VA_STATUS_ERROR_ALLOCATION_FAILED; /* XXX: unpaletted/error */
4499
4500     for (i = 0; i < obj_image->image.num_palette_entries; i++)
4501         obj_image->palette[i] = (((unsigned int)palette[3*i + 0] << 16) |
4502                                  ((unsigned int)palette[3*i + 1] <<  8) |
4503                                  (unsigned int)palette[3*i + 2]);
4504     return VA_STATUS_SUCCESS;
4505 }
4506
4507 static int 
4508 get_sampling_from_fourcc(unsigned int fourcc)
4509 {
4510     const i965_fourcc_info *info = get_fourcc_info(fourcc);
4511
4512     if (info && (info->flag & I_S))
4513         return info->subsampling;
4514     else
4515         return -1;
4516 }
4517
4518 static inline void
4519 memcpy_pic(uint8_t *dst, unsigned int dst_stride,
4520            const uint8_t *src, unsigned int src_stride,
4521            unsigned int len, unsigned int height)
4522 {
4523     unsigned int i;
4524
4525     for (i = 0; i < height; i++) {
4526         memcpy(dst, src, len);
4527         dst += dst_stride;
4528         src += src_stride;
4529     }
4530 }
4531
4532 static VAStatus
4533 get_image_i420(struct object_image *obj_image, uint8_t *image_data,
4534                struct object_surface *obj_surface,
4535                const VARectangle *rect)
4536 {
4537     uint8_t *dst[3], *src[3];
4538     const int Y = 0;
4539     const int U = obj_image->image.format.fourcc == obj_surface->fourcc ? 1 : 2;
4540     const int V = obj_image->image.format.fourcc == obj_surface->fourcc ? 2 : 1;
4541     unsigned int tiling, swizzle;
4542     VAStatus va_status = VA_STATUS_SUCCESS;
4543
4544     if (!obj_surface->bo)
4545         return VA_STATUS_ERROR_INVALID_SURFACE;
4546
4547     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
4548     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4549
4550     if (tiling != I915_TILING_NONE)
4551         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4552     else
4553         dri_bo_map(obj_surface->bo, 0);
4554
4555     if (!obj_surface->bo->virtual)
4556         return VA_STATUS_ERROR_INVALID_SURFACE;
4557
4558     /* Dest VA image has either I420 or YV12 format.
4559        Source VA surface alway has I420 format */
4560     dst[Y] = image_data + obj_image->image.offsets[Y];
4561     src[0] = (uint8_t *)obj_surface->bo->virtual;
4562     dst[U] = image_data + obj_image->image.offsets[U];
4563     src[1] = src[0] + obj_surface->width * obj_surface->height;
4564     dst[V] = image_data + obj_image->image.offsets[V];
4565     src[2] = src[1] + (obj_surface->width / 2) * (obj_surface->height / 2);
4566
4567     /* Y plane */
4568     dst[Y] += rect->y * obj_image->image.pitches[Y] + rect->x;
4569     src[0] += rect->y * obj_surface->width + rect->x;
4570     memcpy_pic(dst[Y], obj_image->image.pitches[Y],
4571                src[0], obj_surface->width,
4572                rect->width, rect->height);
4573
4574     /* U plane */
4575     dst[U] += (rect->y / 2) * obj_image->image.pitches[U] + rect->x / 2;
4576     src[1] += (rect->y / 2) * obj_surface->width / 2 + rect->x / 2;
4577     memcpy_pic(dst[U], obj_image->image.pitches[U],
4578                src[1], obj_surface->width / 2,
4579                rect->width / 2, rect->height / 2);
4580
4581     /* V plane */
4582     dst[V] += (rect->y / 2) * obj_image->image.pitches[V] + rect->x / 2;
4583     src[2] += (rect->y / 2) * obj_surface->width / 2 + rect->x / 2;
4584     memcpy_pic(dst[V], obj_image->image.pitches[V],
4585                src[2], obj_surface->width / 2,
4586                rect->width / 2, rect->height / 2);
4587
4588     if (tiling != I915_TILING_NONE)
4589         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4590     else
4591         dri_bo_unmap(obj_surface->bo);
4592
4593     return va_status;
4594 }
4595
4596 static VAStatus
4597 get_image_nv12(struct object_image *obj_image, uint8_t *image_data,
4598                struct object_surface *obj_surface,
4599                const VARectangle *rect)
4600 {
4601     uint8_t *dst[2], *src[2];
4602     unsigned int tiling, swizzle;
4603     VAStatus va_status = VA_STATUS_SUCCESS;
4604
4605     if (!obj_surface->bo)
4606         return VA_STATUS_ERROR_INVALID_SURFACE;
4607
4608     assert(obj_surface->fourcc);
4609     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4610
4611     if (tiling != I915_TILING_NONE)
4612         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4613     else
4614         dri_bo_map(obj_surface->bo, 0);
4615
4616     if (!obj_surface->bo->virtual)
4617         return VA_STATUS_ERROR_INVALID_SURFACE;
4618
4619     /* Both dest VA image and source surface have NV12 format */
4620     dst[0] = image_data + obj_image->image.offsets[0];
4621     src[0] = (uint8_t *)obj_surface->bo->virtual;
4622     dst[1] = image_data + obj_image->image.offsets[1];
4623     src[1] = src[0] + obj_surface->width * obj_surface->height;
4624
4625     /* Y plane */
4626     dst[0] += rect->y * obj_image->image.pitches[0] + rect->x;
4627     src[0] += rect->y * obj_surface->width + rect->x;
4628     memcpy_pic(dst[0], obj_image->image.pitches[0],
4629                src[0], obj_surface->width,
4630                rect->width, rect->height);
4631
4632     /* UV plane */
4633     dst[1] += (rect->y / 2) * obj_image->image.pitches[1] + (rect->x & -2);
4634     src[1] += (rect->y / 2) * obj_surface->width + (rect->x & -2);
4635     memcpy_pic(dst[1], obj_image->image.pitches[1],
4636                src[1], obj_surface->width,
4637                rect->width, rect->height / 2);
4638
4639     if (tiling != I915_TILING_NONE)
4640         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4641     else
4642         dri_bo_unmap(obj_surface->bo);
4643
4644     return va_status;
4645 }
4646
4647 static VAStatus
4648 get_image_yuy2(struct object_image *obj_image, uint8_t *image_data,
4649                struct object_surface *obj_surface,
4650                const VARectangle *rect)
4651 {
4652     uint8_t *dst, *src;
4653     unsigned int tiling, swizzle;
4654     VAStatus va_status = VA_STATUS_SUCCESS;
4655
4656     if (!obj_surface->bo)
4657         return VA_STATUS_ERROR_INVALID_SURFACE;
4658
4659     assert(obj_surface->fourcc);
4660     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4661
4662     if (tiling != I915_TILING_NONE)
4663         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4664     else
4665         dri_bo_map(obj_surface->bo, 0);
4666
4667     if (!obj_surface->bo->virtual)
4668         return VA_STATUS_ERROR_INVALID_SURFACE;
4669
4670     /* Both dest VA image and source surface have YUYV format */
4671     dst = image_data + obj_image->image.offsets[0];
4672     src = (uint8_t *)obj_surface->bo->virtual;
4673
4674     /* Y plane */
4675     dst += rect->y * obj_image->image.pitches[0] + rect->x*2;
4676     src += rect->y * obj_surface->width + rect->x*2;
4677     memcpy_pic(dst, obj_image->image.pitches[0],
4678                src, obj_surface->width*2,
4679                rect->width*2, rect->height);
4680
4681     if (tiling != I915_TILING_NONE)
4682         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4683     else
4684         dri_bo_unmap(obj_surface->bo);
4685
4686     return va_status;
4687 }
4688
4689 static VAStatus 
4690 i965_sw_getimage(VADriverContextP ctx,
4691     struct object_surface *obj_surface, struct object_image *obj_image,
4692     const VARectangle *rect)
4693 {
4694     void *image_data = NULL;
4695     VAStatus va_status;
4696
4697     if (obj_surface->fourcc != obj_image->image.format.fourcc)
4698         return VA_STATUS_ERROR_INVALID_IMAGE_FORMAT;
4699
4700     va_status = i965_MapBuffer(ctx, obj_image->image.buf, &image_data);
4701     if (va_status != VA_STATUS_SUCCESS)
4702         return va_status;
4703
4704     switch (obj_image->image.format.fourcc) {
4705     case VA_FOURCC_YV12:
4706     case VA_FOURCC_I420:
4707         get_image_i420(obj_image, image_data, obj_surface, rect);
4708         break;
4709     case VA_FOURCC_NV12:
4710         get_image_nv12(obj_image, image_data, obj_surface, rect);
4711         break;
4712     case VA_FOURCC_YUY2:
4713         /* YUY2 is the format supported by overlay plane */
4714         get_image_yuy2(obj_image, image_data, obj_surface, rect);
4715         break;
4716     default:
4717         va_status = VA_STATUS_ERROR_OPERATION_FAILED;
4718         break;
4719     }
4720     if (va_status != VA_STATUS_SUCCESS)
4721         return va_status;
4722
4723     va_status = i965_UnmapBuffer(ctx, obj_image->image.buf);
4724     return va_status;
4725 }
4726
4727 static VAStatus 
4728 i965_hw_getimage(VADriverContextP ctx,
4729     struct object_surface *obj_surface, struct object_image *obj_image,
4730     const VARectangle *rect)
4731 {
4732     struct i965_surface src_surface;
4733     struct i965_surface dst_surface;
4734
4735     src_surface.base = (struct object_base *)obj_surface;
4736     src_surface.type = I965_SURFACE_TYPE_SURFACE;
4737     src_surface.flags = I965_SURFACE_FLAG_FRAME;
4738
4739     dst_surface.base = (struct object_base *)obj_image;
4740     dst_surface.type = I965_SURFACE_TYPE_IMAGE;
4741     dst_surface.flags = I965_SURFACE_FLAG_FRAME;
4742
4743     return i965_image_processing(ctx, &src_surface, rect, &dst_surface, rect);
4744 }
4745
4746 VAStatus 
4747 i965_GetImage(VADriverContextP ctx,
4748               VASurfaceID surface,
4749               int x,   /* coordinates of the upper left source pixel */
4750               int y,
4751               unsigned int width,      /* width and height of the region */
4752               unsigned int height,
4753               VAImageID image)
4754 {
4755     struct i965_driver_data * const i965 = i965_driver_data(ctx);
4756     struct object_surface * const obj_surface = SURFACE(surface);
4757     struct object_image * const obj_image = IMAGE(image);
4758     VARectangle rect;
4759     VAStatus va_status;
4760
4761     if (!obj_surface)
4762         return VA_STATUS_ERROR_INVALID_SURFACE;
4763     if (!obj_surface->bo) /* don't get anything, keep previous data */
4764         return VA_STATUS_SUCCESS;
4765     if (is_surface_busy(i965, obj_surface))
4766         return VA_STATUS_ERROR_SURFACE_BUSY;
4767
4768     if (!obj_image || !obj_image->bo)
4769         return VA_STATUS_ERROR_INVALID_IMAGE;
4770     if (is_image_busy(i965, obj_image, surface))
4771         return VA_STATUS_ERROR_SURFACE_BUSY;
4772
4773     if (x < 0 || y < 0)
4774         return VA_STATUS_ERROR_INVALID_PARAMETER;
4775     if (x + width > obj_surface->orig_width ||
4776         y + height > obj_surface->orig_height)
4777         return VA_STATUS_ERROR_INVALID_PARAMETER;
4778     if (x + width > obj_image->image.width ||
4779         y + height > obj_image->image.height)
4780         return VA_STATUS_ERROR_INVALID_PARAMETER;
4781
4782     rect.x = x;
4783     rect.y = y;
4784     rect.width = width;
4785     rect.height = height;
4786
4787     if (HAS_ACCELERATED_GETIMAGE(i965))
4788         va_status = i965_hw_getimage(ctx, obj_surface, obj_image, &rect);
4789     else
4790         va_status = i965_sw_getimage(ctx, obj_surface, obj_image, &rect);
4791
4792     return va_status;
4793 }
4794
4795 static VAStatus
4796 put_image_i420(struct object_surface *obj_surface,
4797                const VARectangle *dst_rect,
4798                struct object_image *obj_image, uint8_t *image_data,
4799                const VARectangle *src_rect)
4800 {
4801     uint8_t *dst[3], *src[3];
4802     const int Y = 0;
4803     const int U = obj_image->image.format.fourcc == obj_surface->fourcc ? 1 : 2;
4804     const int V = obj_image->image.format.fourcc == obj_surface->fourcc ? 2 : 1;
4805     unsigned int tiling, swizzle;
4806     VAStatus va_status = VA_STATUS_SUCCESS;
4807
4808     ASSERT_RET(obj_surface->bo, VA_STATUS_ERROR_INVALID_SURFACE);
4809
4810     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
4811     ASSERT_RET(dst_rect->width == src_rect->width, VA_STATUS_ERROR_UNIMPLEMENTED);
4812     ASSERT_RET(dst_rect->height == src_rect->height, VA_STATUS_ERROR_UNIMPLEMENTED);
4813     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4814
4815     if (tiling != I915_TILING_NONE)
4816         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4817     else
4818         dri_bo_map(obj_surface->bo, 0);
4819
4820     if (!obj_surface->bo->virtual)
4821         return VA_STATUS_ERROR_INVALID_SURFACE;
4822
4823     /* Dest VA image has either I420 or YV12 format.
4824        Source VA surface alway has I420 format */
4825     dst[0] = (uint8_t *)obj_surface->bo->virtual;
4826     src[Y] = image_data + obj_image->image.offsets[Y];
4827     dst[1] = dst[0] + obj_surface->width * obj_surface->height;
4828     src[U] = image_data + obj_image->image.offsets[U];
4829     dst[2] = dst[1] + (obj_surface->width / 2) * (obj_surface->height / 2);
4830     src[V] = image_data + obj_image->image.offsets[V];
4831
4832     /* Y plane */
4833     dst[0] += dst_rect->y * obj_surface->width + dst_rect->x;
4834     src[Y] += src_rect->y * obj_image->image.pitches[Y] + src_rect->x;
4835     memcpy_pic(dst[0], obj_surface->width,
4836                src[Y], obj_image->image.pitches[Y],
4837                src_rect->width, src_rect->height);
4838
4839     /* U plane */
4840     dst[1] += (dst_rect->y / 2) * obj_surface->width / 2 + dst_rect->x / 2;
4841     src[U] += (src_rect->y / 2) * obj_image->image.pitches[U] + src_rect->x / 2;
4842     memcpy_pic(dst[1], obj_surface->width / 2,
4843                src[U], obj_image->image.pitches[U],
4844                src_rect->width / 2, src_rect->height / 2);
4845
4846     /* V plane */
4847     dst[2] += (dst_rect->y / 2) * obj_surface->width / 2 + dst_rect->x / 2;
4848     src[V] += (src_rect->y / 2) * obj_image->image.pitches[V] + src_rect->x / 2;
4849     memcpy_pic(dst[2], obj_surface->width / 2,
4850                src[V], obj_image->image.pitches[V],
4851                src_rect->width / 2, src_rect->height / 2);
4852
4853     if (tiling != I915_TILING_NONE)
4854         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4855     else
4856         dri_bo_unmap(obj_surface->bo);
4857
4858     return va_status;
4859 }
4860
4861 static VAStatus
4862 put_image_nv12(struct object_surface *obj_surface,
4863                const VARectangle *dst_rect,
4864                struct object_image *obj_image, uint8_t *image_data,
4865                const VARectangle *src_rect)
4866 {
4867     uint8_t *dst[2], *src[2];
4868     unsigned int tiling, swizzle;
4869     VAStatus va_status = VA_STATUS_SUCCESS;
4870
4871     if (!obj_surface->bo)
4872         return VA_STATUS_ERROR_INVALID_SURFACE;
4873
4874     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
4875     ASSERT_RET(dst_rect->width == src_rect->width, VA_STATUS_ERROR_UNIMPLEMENTED);
4876     ASSERT_RET(dst_rect->height == src_rect->height, VA_STATUS_ERROR_UNIMPLEMENTED);
4877     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4878
4879     if (tiling != I915_TILING_NONE)
4880         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4881     else
4882         dri_bo_map(obj_surface->bo, 0);
4883
4884     if (!obj_surface->bo->virtual)
4885         return VA_STATUS_ERROR_INVALID_SURFACE;
4886
4887     /* Both dest VA image and source surface have NV12 format */
4888     dst[0] = (uint8_t *)obj_surface->bo->virtual;
4889     src[0] = image_data + obj_image->image.offsets[0];
4890     dst[1] = dst[0] + obj_surface->width * obj_surface->height;
4891     src[1] = image_data + obj_image->image.offsets[1];
4892
4893     /* Y plane */
4894     dst[0] += dst_rect->y * obj_surface->width + dst_rect->x;
4895     src[0] += src_rect->y * obj_image->image.pitches[0] + src_rect->x;
4896     memcpy_pic(dst[0], obj_surface->width,
4897                src[0], obj_image->image.pitches[0],
4898                src_rect->width, src_rect->height);
4899
4900     /* UV plane */
4901     dst[1] += (dst_rect->y / 2) * obj_surface->width + (dst_rect->x & -2);
4902     src[1] += (src_rect->y / 2) * obj_image->image.pitches[1] + (src_rect->x & -2);
4903     memcpy_pic(dst[1], obj_surface->width,
4904                src[1], obj_image->image.pitches[1],
4905                src_rect->width, src_rect->height / 2);
4906
4907     if (tiling != I915_TILING_NONE)
4908         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4909     else
4910         dri_bo_unmap(obj_surface->bo);
4911
4912     return va_status;
4913 }
4914
4915 static VAStatus
4916 put_image_yuy2(struct object_surface *obj_surface,
4917                const VARectangle *dst_rect,
4918                struct object_image *obj_image, uint8_t *image_data,
4919                const VARectangle *src_rect)
4920 {
4921     uint8_t *dst, *src;
4922     unsigned int tiling, swizzle;
4923     VAStatus va_status = VA_STATUS_SUCCESS;
4924
4925     ASSERT_RET(obj_surface->bo, VA_STATUS_ERROR_INVALID_SURFACE);
4926     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
4927     ASSERT_RET(dst_rect->width == src_rect->width, VA_STATUS_ERROR_UNIMPLEMENTED);
4928     ASSERT_RET(dst_rect->height == src_rect->height, VA_STATUS_ERROR_UNIMPLEMENTED);
4929     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
4930
4931     if (tiling != I915_TILING_NONE)
4932         drm_intel_gem_bo_map_gtt(obj_surface->bo);
4933     else
4934         dri_bo_map(obj_surface->bo, 0);
4935
4936     if (!obj_surface->bo->virtual)
4937         return VA_STATUS_ERROR_INVALID_SURFACE;
4938
4939     /* Both dest VA image and source surface have YUY2 format */
4940     dst = (uint8_t *)obj_surface->bo->virtual;
4941     src = image_data + obj_image->image.offsets[0];
4942
4943     /* YUYV packed plane */
4944     dst += dst_rect->y * obj_surface->width + dst_rect->x*2;
4945     src += src_rect->y * obj_image->image.pitches[0] + src_rect->x*2;
4946     memcpy_pic(dst, obj_surface->width*2,
4947                src, obj_image->image.pitches[0],
4948                src_rect->width*2, src_rect->height);
4949
4950     if (tiling != I915_TILING_NONE)
4951         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
4952     else
4953         dri_bo_unmap(obj_surface->bo);
4954
4955     return va_status;
4956 }
4957
4958 static VAStatus
4959 i965_sw_putimage(VADriverContextP ctx,
4960     struct object_surface *obj_surface, struct object_image *obj_image,
4961     const VARectangle *src_rect, const VARectangle *dst_rect)
4962 {
4963     VAStatus va_status = VA_STATUS_SUCCESS;
4964     void *image_data = NULL;
4965
4966     /* XXX: don't allow scaling */
4967     if (src_rect->width != dst_rect->width ||
4968         src_rect->height != dst_rect->height)
4969         return VA_STATUS_ERROR_INVALID_PARAMETER;
4970
4971     if (obj_surface->fourcc) {
4972         /* Don't allow format mismatch */
4973         if (obj_surface->fourcc != obj_image->image.format.fourcc)
4974             return VA_STATUS_ERROR_INVALID_IMAGE_FORMAT;
4975     }
4976
4977     else {
4978         /* VA is surface not used for decoding, use same VA image format */
4979         va_status = i965_check_alloc_surface_bo(
4980             ctx,
4981             obj_surface,
4982             0, /* XXX: don't use tiled surface */
4983             obj_image->image.format.fourcc,
4984             get_sampling_from_fourcc (obj_image->image.format.fourcc));
4985     }
4986
4987     if (va_status != VA_STATUS_SUCCESS)
4988         return va_status;
4989
4990     va_status = i965_MapBuffer(ctx, obj_image->image.buf, &image_data);
4991     if (va_status != VA_STATUS_SUCCESS)
4992         return va_status;
4993      
4994     switch (obj_image->image.format.fourcc) {
4995     case VA_FOURCC_YV12:
4996     case VA_FOURCC_I420:
4997         va_status = put_image_i420(obj_surface, dst_rect, obj_image, image_data, src_rect);
4998         break;
4999     case VA_FOURCC_NV12:
5000         va_status = put_image_nv12(obj_surface, dst_rect, obj_image, image_data, src_rect);
5001         break;
5002     case VA_FOURCC_YUY2:
5003         va_status = put_image_yuy2(obj_surface, dst_rect, obj_image, image_data, src_rect);
5004         break;
5005     default:
5006         va_status = VA_STATUS_ERROR_OPERATION_FAILED;
5007         break;
5008     }
5009     if (va_status != VA_STATUS_SUCCESS)
5010         return va_status;
5011
5012     va_status = i965_UnmapBuffer(ctx, obj_image->image.buf);
5013     return va_status;
5014 }
5015
5016 static VAStatus 
5017 i965_hw_putimage(VADriverContextP ctx,
5018     struct object_surface *obj_surface, struct object_image *obj_image,
5019     const VARectangle *src_rect, const VARectangle *dst_rect)
5020 {
5021     struct i965_surface src_surface, dst_surface;
5022     VAStatus va_status = VA_STATUS_SUCCESS;
5023
5024     if (!obj_surface->bo) {
5025         unsigned int tiling, swizzle;
5026         int surface_sampling = get_sampling_from_fourcc (obj_image->image.format.fourcc);;
5027         dri_bo_get_tiling(obj_image->bo, &tiling, &swizzle);
5028
5029         i965_check_alloc_surface_bo(ctx,
5030                                     obj_surface,
5031                                     !!tiling,
5032                                     obj_image->image.format.fourcc,
5033                                     surface_sampling);
5034     }
5035
5036     ASSERT_RET(obj_surface->fourcc, VA_STATUS_ERROR_INVALID_SURFACE);
5037
5038     src_surface.base = (struct object_base *)obj_image;
5039     src_surface.type = I965_SURFACE_TYPE_IMAGE;
5040     src_surface.flags = I965_SURFACE_FLAG_FRAME;
5041
5042     dst_surface.base = (struct object_base *)obj_surface;
5043     dst_surface.type = I965_SURFACE_TYPE_SURFACE;
5044     dst_surface.flags = I965_SURFACE_FLAG_FRAME;
5045
5046     va_status = i965_image_processing(ctx,
5047                                       &src_surface,
5048                                       src_rect,
5049                                       &dst_surface,
5050                                       dst_rect);
5051
5052     return  va_status;
5053 }
5054
5055 static VAStatus 
5056 i965_PutImage(VADriverContextP ctx,
5057               VASurfaceID surface,
5058               VAImageID image,
5059               int src_x,
5060               int src_y,
5061               unsigned int src_width,
5062               unsigned int src_height,
5063               int dest_x,
5064               int dest_y,
5065               unsigned int dest_width,
5066               unsigned int dest_height)
5067 {
5068     struct i965_driver_data * const i965 = i965_driver_data(ctx);
5069     struct object_surface * const obj_surface = SURFACE(surface);
5070     struct object_image * const obj_image = IMAGE(image);
5071     VARectangle src_rect, dst_rect;
5072     VAStatus va_status;
5073
5074     if (!obj_surface)
5075         return VA_STATUS_ERROR_INVALID_SURFACE;
5076     if (is_surface_busy(i965, obj_surface))
5077         return VA_STATUS_ERROR_SURFACE_BUSY;
5078
5079     if (!obj_image || !obj_image->bo)
5080         return VA_STATUS_ERROR_INVALID_IMAGE;
5081     if (is_image_busy(i965, obj_image, surface))
5082         return VA_STATUS_ERROR_SURFACE_BUSY;
5083
5084     if (src_x < 0 ||
5085         src_y < 0 ||
5086         src_x + src_width > obj_image->image.width ||
5087         src_y + src_height > obj_image->image.height)
5088         return VA_STATUS_ERROR_INVALID_PARAMETER;
5089
5090     src_rect.x       = src_x;
5091     src_rect.y       = src_y;
5092     src_rect.width   = src_width;
5093     src_rect.height  = src_height;
5094
5095     if (dest_x < 0 ||
5096         dest_y < 0 ||
5097         dest_x + dest_width > obj_surface->orig_width ||
5098         dest_y + dest_height > obj_surface->orig_height)
5099         return VA_STATUS_ERROR_INVALID_PARAMETER;
5100
5101     dst_rect.x      = dest_x;
5102     dst_rect.y      = dest_y;
5103     dst_rect.width  = dest_width;
5104     dst_rect.height = dest_height;
5105
5106     if (HAS_ACCELERATED_PUTIMAGE(i965))
5107         va_status = i965_hw_putimage(ctx, obj_surface, obj_image,
5108             &src_rect, &dst_rect);
5109     else 
5110         va_status = i965_sw_putimage(ctx, obj_surface, obj_image,
5111             &src_rect, &dst_rect);
5112
5113     return va_status;
5114 }
5115
5116 VAStatus 
5117 i965_PutSurface(VADriverContextP ctx,
5118                 VASurfaceID surface,
5119                 void *draw, /* X Drawable */
5120                 short srcx,
5121                 short srcy,
5122                 unsigned short srcw,
5123                 unsigned short srch,
5124                 short destx,
5125                 short desty,
5126                 unsigned short destw,
5127                 unsigned short desth,
5128                 VARectangle *cliprects, /* client supplied clip list */
5129                 unsigned int number_cliprects, /* number of clip rects in the clip list */
5130                 unsigned int flags) /* de-interlacing flags */
5131 {
5132 #ifdef HAVE_VA_X11
5133     if (IS_VA_X11(ctx)) {
5134         VARectangle src_rect, dst_rect;
5135
5136         src_rect.x      = srcx;
5137         src_rect.y      = srcy;
5138         src_rect.width  = srcw;
5139         src_rect.height = srch;
5140
5141         dst_rect.x      = destx;
5142         dst_rect.y      = desty;
5143         dst_rect.width  = destw;
5144         dst_rect.height = desth;
5145
5146         return i965_put_surface_dri(ctx, surface, draw, &src_rect, &dst_rect,
5147                                     cliprects, number_cliprects, flags);
5148     }
5149 #endif
5150     return VA_STATUS_ERROR_UNIMPLEMENTED;
5151 }
5152
5153 static VAStatus
5154 i965_BufferInfo(
5155     VADriverContextP ctx,       /* in */
5156     VABufferID buf_id,          /* in */
5157     VABufferType *type,         /* out */
5158     unsigned int *size,         /* out */
5159     unsigned int *num_elements  /* out */
5160 )
5161 {
5162     struct i965_driver_data *i965 = NULL;
5163     struct object_buffer *obj_buffer = NULL;
5164
5165     i965 = i965_driver_data(ctx);
5166     obj_buffer = BUFFER(buf_id);
5167
5168     ASSERT_RET(obj_buffer, VA_STATUS_ERROR_INVALID_BUFFER);
5169
5170     *type = obj_buffer->type;
5171     *size = obj_buffer->size_element;
5172     *num_elements = obj_buffer->num_elements;
5173
5174     return VA_STATUS_SUCCESS;
5175 }
5176
5177 static VAStatus
5178 i965_LockSurface(
5179     VADriverContextP ctx,           /* in */
5180     VASurfaceID surface,            /* in */
5181     unsigned int *fourcc,           /* out */
5182     unsigned int *luma_stride,      /* out */
5183     unsigned int *chroma_u_stride,  /* out */
5184     unsigned int *chroma_v_stride,  /* out */
5185     unsigned int *luma_offset,      /* out */
5186     unsigned int *chroma_u_offset,  /* out */
5187     unsigned int *chroma_v_offset,  /* out */
5188     unsigned int *buffer_name,      /* out */
5189     void **buffer                   /* out */
5190 )
5191 {
5192     VAStatus vaStatus = VA_STATUS_SUCCESS;
5193     struct i965_driver_data *i965 = i965_driver_data(ctx);
5194     struct object_surface *obj_surface = NULL;
5195     VAImage tmpImage;
5196
5197     ASSERT_RET(fourcc, VA_STATUS_ERROR_INVALID_PARAMETER);
5198     ASSERT_RET(luma_stride, VA_STATUS_ERROR_INVALID_PARAMETER);
5199     ASSERT_RET(chroma_u_stride, VA_STATUS_ERROR_INVALID_PARAMETER);
5200     ASSERT_RET(chroma_v_stride, VA_STATUS_ERROR_INVALID_PARAMETER);
5201     ASSERT_RET(luma_offset, VA_STATUS_ERROR_INVALID_PARAMETER);
5202     ASSERT_RET(chroma_u_offset, VA_STATUS_ERROR_INVALID_PARAMETER);
5203     ASSERT_RET(chroma_v_offset, VA_STATUS_ERROR_INVALID_PARAMETER);
5204     ASSERT_RET(buffer_name, VA_STATUS_ERROR_INVALID_PARAMETER);
5205     ASSERT_RET(buffer, VA_STATUS_ERROR_INVALID_PARAMETER);
5206
5207     tmpImage.image_id = VA_INVALID_ID;
5208
5209     obj_surface = SURFACE(surface);
5210     if (obj_surface == NULL) {
5211         // Surface is absent.
5212         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
5213         goto error;
5214     }
5215
5216     // Lock functionality is absent now.
5217     if (obj_surface->locked_image_id != VA_INVALID_ID) {
5218         // Surface is locked already.
5219         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
5220         goto error;
5221     }
5222
5223     vaStatus = i965_DeriveImage(
5224         ctx,
5225         surface,
5226         &tmpImage);
5227     if (vaStatus != VA_STATUS_SUCCESS) {
5228         goto error;
5229     }
5230
5231     obj_surface->locked_image_id = tmpImage.image_id;
5232
5233     vaStatus = i965_MapBuffer(
5234         ctx,
5235         tmpImage.buf,
5236         buffer);
5237     if (vaStatus != VA_STATUS_SUCCESS) {
5238         goto error;
5239     }
5240
5241     *fourcc = tmpImage.format.fourcc;
5242     *luma_offset = tmpImage.offsets[0];
5243     *luma_stride = tmpImage.pitches[0];
5244     *chroma_u_offset = tmpImage.offsets[1];
5245     *chroma_u_stride = tmpImage.pitches[1];
5246     *chroma_v_offset = tmpImage.offsets[2];
5247     *chroma_v_stride = tmpImage.pitches[2];
5248     *buffer_name = tmpImage.buf;
5249
5250 error:
5251     if (vaStatus != VA_STATUS_SUCCESS) {
5252         buffer = NULL;
5253     }
5254
5255     return vaStatus;
5256 }
5257
5258 static VAStatus
5259 i965_UnlockSurface(
5260     VADriverContextP ctx,   /* in */
5261     VASurfaceID surface     /* in */
5262 )
5263 {
5264     VAStatus vaStatus = VA_STATUS_SUCCESS;
5265     struct i965_driver_data *i965 = i965_driver_data(ctx);
5266     struct object_image *locked_img = NULL;
5267     struct object_surface *obj_surface = NULL;
5268
5269     obj_surface = SURFACE(surface);
5270
5271     if (obj_surface == NULL) {
5272         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;   // Surface is absent
5273         return vaStatus;
5274     }
5275     if (obj_surface->locked_image_id == VA_INVALID_ID) {
5276         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;   // Surface is not locked
5277         return vaStatus;
5278     }
5279
5280     locked_img = IMAGE(obj_surface->locked_image_id);
5281     if (locked_img == NULL || (locked_img->image.image_id == VA_INVALID_ID)) {
5282         // Work image was deallocated before i965_UnlockSurface()
5283         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
5284         goto error;
5285     }
5286
5287     vaStatus = i965_UnmapBuffer(
5288         ctx,
5289         locked_img->image.buf);
5290     if (vaStatus != VA_STATUS_SUCCESS) {
5291         goto error;
5292     }
5293
5294     vaStatus = i965_DestroyImage(
5295         ctx,
5296         locked_img->image.image_id);
5297     if (vaStatus != VA_STATUS_SUCCESS) {
5298         goto error;
5299     }
5300
5301     locked_img->image.image_id = VA_INVALID_ID;
5302
5303  error:
5304     obj_surface->locked_image_id = VA_INVALID_ID;
5305
5306     return vaStatus;
5307 }
5308
5309 static VAStatus
5310 i965_GetSurfaceAttributes(
5311     VADriverContextP ctx,
5312     VAConfigID config,
5313     VASurfaceAttrib *attrib_list,
5314     unsigned int num_attribs
5315     )
5316 {
5317     VAStatus vaStatus = VA_STATUS_SUCCESS;
5318     struct i965_driver_data *i965 = i965_driver_data(ctx);
5319     struct object_config *obj_config;
5320     int i;
5321
5322     if (config == VA_INVALID_ID)
5323         return VA_STATUS_ERROR_INVALID_CONFIG;
5324
5325     obj_config = CONFIG(config);
5326
5327     if (obj_config == NULL)
5328         return VA_STATUS_ERROR_INVALID_CONFIG;
5329     
5330     if (attrib_list == NULL || num_attribs == 0)
5331         return VA_STATUS_ERROR_INVALID_PARAMETER;
5332
5333     for (i = 0; i < num_attribs; i++) {
5334         switch (attrib_list[i].type) {
5335         case VASurfaceAttribPixelFormat:
5336             attrib_list[i].value.type = VAGenericValueTypeInteger;
5337             attrib_list[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5338
5339             if (attrib_list[i].value.value.i == 0) {
5340                 if (IS_G4X(i965->intel.device_info)) {
5341                     if (obj_config->profile == VAProfileMPEG2Simple ||
5342                         obj_config->profile == VAProfileMPEG2Main) {
5343                         attrib_list[i].value.value.i = VA_FOURCC_I420;
5344                     } else {
5345                         assert(0);
5346                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5347                     }
5348                 } else if (IS_IRONLAKE(i965->intel.device_info)) {
5349                     if (obj_config->profile == VAProfileMPEG2Simple ||
5350                         obj_config->profile == VAProfileMPEG2Main) {
5351                         attrib_list[i].value.value.i = VA_FOURCC_I420;
5352                     } else if (obj_config->profile == VAProfileH264ConstrainedBaseline ||
5353                                obj_config->profile == VAProfileH264Main ||
5354                                obj_config->profile == VAProfileH264High) {
5355                         attrib_list[i].value.value.i = VA_FOURCC_NV12;
5356                     } else if (obj_config->profile == VAProfileNone) {
5357                         attrib_list[i].value.value.i = VA_FOURCC_NV12;
5358                     } else {
5359                         assert(0);
5360                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5361                     }
5362                 } else if (IS_GEN6(i965->intel.device_info)) {
5363                     attrib_list[i].value.value.i = VA_FOURCC_NV12;
5364                 } else if (IS_GEN7(i965->intel.device_info) ||
5365                            IS_GEN8(i965->intel.device_info) ||
5366                            IS_GEN9(i965->intel.device_info)) {
5367                     if (obj_config->profile == VAProfileJPEGBaseline)
5368                         attrib_list[i].value.value.i = 0; /* internal format */
5369                     else
5370                         attrib_list[i].value.value.i = VA_FOURCC_NV12;
5371                 }
5372             } else {
5373                 if (IS_G4X(i965->intel.device_info)) {
5374                     if (obj_config->profile == VAProfileMPEG2Simple ||
5375                         obj_config->profile == VAProfileMPEG2Main) {
5376                         if (attrib_list[i].value.value.i != VA_FOURCC_I420) {
5377                             attrib_list[i].value.value.i = 0;
5378                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5379                         }
5380                     } else {
5381                         assert(0);
5382                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5383                     }
5384                 } else if (IS_IRONLAKE(i965->intel.device_info)) {
5385                     if (obj_config->profile == VAProfileMPEG2Simple ||
5386                         obj_config->profile == VAProfileMPEG2Main) {
5387                         if (attrib_list[i].value.value.i != VA_FOURCC_I420) {
5388                             attrib_list[i].value.value.i = 0;                            
5389                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5390                         }
5391                     } else if (obj_config->profile == VAProfileH264ConstrainedBaseline ||
5392                                obj_config->profile == VAProfileH264Main ||
5393                                obj_config->profile == VAProfileH264High) {
5394                         if (attrib_list[i].value.value.i != VA_FOURCC_NV12) {
5395                             attrib_list[i].value.value.i = 0;
5396                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5397                         }
5398                     } else if (obj_config->profile == VAProfileNone) {
5399                         switch (attrib_list[i].value.value.i) {
5400                         case VA_FOURCC_NV12:
5401                         case VA_FOURCC_I420:
5402                         case VA_FOURCC_YV12:
5403                         case VA_FOURCC_YUY2:
5404                         case VA_FOURCC_BGRA:
5405                         case VA_FOURCC_BGRX:
5406                         case VA_FOURCC_RGBX:
5407                         case VA_FOURCC_RGBA:
5408                             break;
5409                         default:
5410                             attrib_list[i].value.value.i = 0;                            
5411                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5412                             break;
5413                         }
5414                     } else {
5415                         assert(0);
5416                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5417                     }
5418                 } else if (IS_GEN6(i965->intel.device_info)) {
5419                     if (obj_config->entrypoint == VAEntrypointEncSlice ||
5420                         obj_config->entrypoint == VAEntrypointVideoProc) {
5421                         switch (attrib_list[i].value.value.i) {
5422                         case VA_FOURCC_NV12:
5423                         case VA_FOURCC_I420:
5424                         case VA_FOURCC_YV12:
5425                         case VA_FOURCC_YUY2:
5426                         case VA_FOURCC_BGRA:
5427                         case VA_FOURCC_BGRX:
5428                         case VA_FOURCC_RGBX:
5429                         case VA_FOURCC_RGBA:
5430                             break;
5431                         default:
5432                             attrib_list[i].value.value.i = 0;                            
5433                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5434                             break;
5435                         }
5436                     } else {
5437                         if (attrib_list[i].value.value.i != VA_FOURCC_NV12) {
5438                             attrib_list[i].value.value.i = 0;
5439                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5440                         }
5441                     }
5442                 } else if (IS_GEN7(i965->intel.device_info) ||
5443                            IS_GEN8(i965->intel.device_info) ||
5444                            IS_GEN9(i965->intel.device_info)) {
5445                     if (obj_config->entrypoint == VAEntrypointEncSlice ||
5446                         obj_config->entrypoint == VAEntrypointVideoProc ||
5447                         obj_config->entrypoint == VAEntrypointEncSliceLP) {
5448                         switch (attrib_list[i].value.value.i) {
5449                         case VA_FOURCC_NV12:
5450                         case VA_FOURCC_I420:
5451                         case VA_FOURCC_YV12:
5452                             break;
5453                         default:
5454                             attrib_list[i].value.value.i = 0;                            
5455                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5456                             break;
5457                         }
5458                     } else {
5459                         if (obj_config->profile == VAProfileJPEGBaseline) {
5460                             attrib_list[i].value.value.i = 0;   /* JPEG decoding always uses an internal format */
5461                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5462                         } else {
5463                             if (attrib_list[i].value.value.i != VA_FOURCC_NV12) {
5464                                 attrib_list[i].value.value.i = 0;
5465                                 attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
5466                             }
5467                         }
5468                     }
5469                 }
5470             }
5471
5472             break;
5473         case VASurfaceAttribMinWidth:
5474             /* FIXME: add support for it later */
5475             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5476             break;
5477         case VASurfaceAttribMaxWidth:
5478             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5479             break;
5480         case VASurfaceAttribMinHeight:
5481             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5482             break;
5483         case VASurfaceAttribMaxHeight:
5484             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5485             break;
5486         default:
5487             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
5488             break;
5489         }
5490     }
5491
5492     return vaStatus;
5493 }
5494
5495 static VAStatus
5496 i965_QuerySurfaceAttributes(VADriverContextP ctx,
5497                             VAConfigID config,
5498                             VASurfaceAttrib *attrib_list,
5499                             unsigned int *num_attribs)
5500 {
5501     VAStatus vaStatus = VA_STATUS_SUCCESS;
5502     struct i965_driver_data *i965 = i965_driver_data(ctx);
5503     struct object_config *obj_config;
5504     int i = 0;
5505     VASurfaceAttrib *attribs = NULL;
5506     int max_width;
5507     int max_height;
5508
5509     if (config == VA_INVALID_ID)
5510         return VA_STATUS_ERROR_INVALID_CONFIG;
5511
5512     obj_config = CONFIG(config);
5513
5514     if (obj_config == NULL)
5515         return VA_STATUS_ERROR_INVALID_CONFIG;
5516     
5517     if (!attrib_list && !num_attribs)
5518         return VA_STATUS_ERROR_INVALID_PARAMETER;
5519
5520     if (attrib_list == NULL) {
5521         *num_attribs = I965_MAX_SURFACE_ATTRIBUTES;
5522         return VA_STATUS_SUCCESS;
5523     }
5524
5525     attribs = malloc(I965_MAX_SURFACE_ATTRIBUTES *sizeof(*attribs));
5526     
5527     if (attribs == NULL)
5528         return VA_STATUS_ERROR_ALLOCATION_FAILED;
5529
5530     if (IS_G4X(i965->intel.device_info)) {
5531         if (obj_config->profile == VAProfileMPEG2Simple ||
5532             obj_config->profile == VAProfileMPEG2Main) {
5533             attribs[i].type = VASurfaceAttribPixelFormat;
5534             attribs[i].value.type = VAGenericValueTypeInteger;
5535             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5536             attribs[i].value.value.i = VA_FOURCC_I420;
5537             i++;
5538         }
5539     } else if (IS_IRONLAKE(i965->intel.device_info)) {
5540         switch (obj_config->profile) {
5541         case VAProfileMPEG2Simple:
5542         case VAProfileMPEG2Main:
5543             attribs[i].type = VASurfaceAttribPixelFormat;
5544             attribs[i].value.type = VAGenericValueTypeInteger;
5545             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5546             attribs[i].value.value.i = VA_FOURCC_I420;
5547             i++;
5548             
5549             break;
5550
5551         case VAProfileH264ConstrainedBaseline:
5552         case VAProfileH264Main:
5553         case VAProfileH264High:
5554             attribs[i].type = VASurfaceAttribPixelFormat;
5555             attribs[i].value.type = VAGenericValueTypeInteger;
5556             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5557             attribs[i].value.value.i = VA_FOURCC_NV12;
5558             i++;
5559
5560         case VAProfileNone:
5561             attribs[i].type = VASurfaceAttribPixelFormat;
5562             attribs[i].value.type = VAGenericValueTypeInteger;
5563             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5564             attribs[i].value.value.i = VA_FOURCC_NV12;
5565             i++;
5566
5567             attribs[i].type = VASurfaceAttribPixelFormat;
5568             attribs[i].value.type = VAGenericValueTypeInteger;
5569             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5570             attribs[i].value.value.i = VA_FOURCC_I420;
5571             i++;
5572
5573             break;
5574             
5575         default:
5576             break;
5577         }
5578     } else if (IS_GEN6(i965->intel.device_info)) {
5579         if (obj_config->entrypoint == VAEntrypointVLD) { /* decode */
5580             attribs[i].type = VASurfaceAttribPixelFormat;
5581             attribs[i].value.type = VAGenericValueTypeInteger;
5582             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5583             attribs[i].value.value.i = VA_FOURCC_NV12;
5584             i++;
5585         } else if (obj_config->entrypoint == VAEntrypointEncSlice ||  /* encode */
5586                    obj_config->entrypoint == VAEntrypointVideoProc) { /* vpp */ 
5587             attribs[i].type = VASurfaceAttribPixelFormat;
5588             attribs[i].value.type = VAGenericValueTypeInteger;
5589             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5590             attribs[i].value.value.i = VA_FOURCC_NV12;
5591             i++;
5592
5593             attribs[i].type = VASurfaceAttribPixelFormat;
5594             attribs[i].value.type = VAGenericValueTypeInteger;
5595             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5596             attribs[i].value.value.i = VA_FOURCC_I420;
5597             i++;
5598
5599             attribs[i].type = VASurfaceAttribPixelFormat;
5600             attribs[i].value.type = VAGenericValueTypeInteger;
5601             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5602             attribs[i].value.value.i = VA_FOURCC_YV12;
5603             i++;
5604
5605             if (obj_config->entrypoint == VAEntrypointVideoProc) {
5606                 attribs[i].type = VASurfaceAttribPixelFormat;
5607                 attribs[i].value.type = VAGenericValueTypeInteger;
5608                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5609                 attribs[i].value.value.i = VA_FOURCC_YUY2;
5610                 i++;
5611
5612                 attribs[i].type = VASurfaceAttribPixelFormat;
5613                 attribs[i].value.type = VAGenericValueTypeInteger;
5614                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5615                 attribs[i].value.value.i = VA_FOURCC_RGBA;
5616                 i++;
5617
5618                 attribs[i].type = VASurfaceAttribPixelFormat;
5619                 attribs[i].value.type = VAGenericValueTypeInteger;
5620                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5621                 attribs[i].value.value.i = VA_FOURCC_RGBX;
5622                 i++;
5623             }
5624         }
5625     } else if (IS_GEN7(i965->intel.device_info)) {
5626         if (obj_config->entrypoint == VAEntrypointVLD) { /* decode */
5627             if (obj_config->profile == VAProfileJPEGBaseline) {
5628                 attribs[i].type = VASurfaceAttribPixelFormat;
5629                 attribs[i].value.type = VAGenericValueTypeInteger;
5630                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5631                 attribs[i].value.value.i = VA_FOURCC_IMC3;
5632                 i++;
5633
5634                 attribs[i].type = VASurfaceAttribPixelFormat;
5635                 attribs[i].value.type = VAGenericValueTypeInteger;
5636                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5637                 attribs[i].value.value.i = VA_FOURCC_IMC1;
5638                 i++;
5639
5640                 attribs[i].type = VASurfaceAttribPixelFormat;
5641                 attribs[i].value.type = VAGenericValueTypeInteger;
5642                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5643                 attribs[i].value.value.i = VA_FOURCC_Y800;
5644                 i++;
5645
5646                 attribs[i].type = VASurfaceAttribPixelFormat;
5647                 attribs[i].value.type = VAGenericValueTypeInteger;
5648                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5649                 attribs[i].value.value.i = VA_FOURCC_411P;
5650                 i++;
5651
5652                 attribs[i].type = VASurfaceAttribPixelFormat;
5653                 attribs[i].value.type = VAGenericValueTypeInteger;
5654                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5655                 attribs[i].value.value.i = VA_FOURCC_422H;
5656                 i++;
5657
5658                 attribs[i].type = VASurfaceAttribPixelFormat;
5659                 attribs[i].value.type = VAGenericValueTypeInteger;
5660                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5661                 attribs[i].value.value.i = VA_FOURCC_422V;
5662                 i++;
5663
5664                 attribs[i].type = VASurfaceAttribPixelFormat;
5665                 attribs[i].value.type = VAGenericValueTypeInteger;
5666                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5667                 attribs[i].value.value.i = VA_FOURCC_444P;
5668                 i++;
5669             } else if (obj_config->profile == VAProfileHEVCMain10) {
5670                 attribs[i].type = VASurfaceAttribPixelFormat;
5671                 attribs[i].value.type = VAGenericValueTypeInteger;
5672                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5673                 attribs[i].value.value.i = VA_FOURCC_P010;
5674                 i++;
5675              } else {
5676                 attribs[i].type = VASurfaceAttribPixelFormat;
5677                 attribs[i].value.type = VAGenericValueTypeInteger;
5678                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5679                 attribs[i].value.value.i = VA_FOURCC_NV12;
5680                 i++;
5681             }
5682         } else if (obj_config->entrypoint == VAEntrypointEncSlice ||  /* encode */
5683                    obj_config->entrypoint == VAEntrypointVideoProc) { /* vpp */ 
5684             attribs[i].type = VASurfaceAttribPixelFormat;
5685             attribs[i].value.type = VAGenericValueTypeInteger;
5686             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5687             attribs[i].value.value.i = VA_FOURCC_NV12;
5688             i++;
5689
5690             attribs[i].type = VASurfaceAttribPixelFormat;
5691             attribs[i].value.type = VAGenericValueTypeInteger;
5692             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5693             attribs[i].value.value.i = VA_FOURCC_I420;
5694             i++;
5695
5696             attribs[i].type = VASurfaceAttribPixelFormat;
5697             attribs[i].value.type = VAGenericValueTypeInteger;
5698             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5699             attribs[i].value.value.i = VA_FOURCC_YV12;
5700             i++;
5701
5702             attribs[i].type = VASurfaceAttribPixelFormat;
5703             attribs[i].value.type = VAGenericValueTypeInteger;
5704             attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5705             attribs[i].value.value.i = VA_FOURCC_IMC3;
5706             i++;
5707
5708             if (obj_config->entrypoint == VAEntrypointVideoProc) {
5709                 attribs[i].type = VASurfaceAttribPixelFormat;
5710                 attribs[i].value.type = VAGenericValueTypeInteger;
5711                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5712                 attribs[i].value.value.i = VA_FOURCC_YUY2;
5713                 i++;
5714
5715                 attribs[i].type = VASurfaceAttribPixelFormat;
5716                 attribs[i].value.type = VAGenericValueTypeInteger;
5717                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5718                 attribs[i].value.value.i = VA_FOURCC_RGBA;
5719                 i++;
5720
5721                 attribs[i].type = VASurfaceAttribPixelFormat;
5722                 attribs[i].value.type = VAGenericValueTypeInteger;
5723                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5724                 attribs[i].value.value.i = VA_FOURCC_RGBX;
5725                 i++;
5726
5727                 attribs[i].type = VASurfaceAttribPixelFormat;
5728                 attribs[i].value.type = VAGenericValueTypeInteger;
5729                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5730                 attribs[i].value.value.i = VA_FOURCC_BGRA;
5731                 i++;
5732
5733                 attribs[i].type = VASurfaceAttribPixelFormat;
5734                 attribs[i].value.type = VAGenericValueTypeInteger;
5735                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5736                 attribs[i].value.value.i = VA_FOURCC_BGRX;
5737                 i++;
5738
5739                 attribs[i].type = VASurfaceAttribPixelFormat;
5740                 attribs[i].value.type = VAGenericValueTypeInteger;
5741                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5742                 attribs[i].value.value.i = VA_FOURCC_YV16;
5743                 i++;
5744             }
5745         }
5746     } else if (IS_GEN8(i965->intel.device_info) ||
5747                IS_GEN9(i965->intel.device_info)) {
5748         if (obj_config->entrypoint == VAEntrypointVLD) { /* decode */
5749             if (obj_config->profile == VAProfileJPEGBaseline) {
5750                 attribs[i].type = VASurfaceAttribPixelFormat;
5751                 attribs[i].value.type = VAGenericValueTypeInteger;
5752                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5753                 attribs[i].value.value.i = VA_FOURCC_IMC3;
5754                 i++;
5755
5756                 attribs[i].type = VASurfaceAttribPixelFormat;
5757                 attribs[i].value.type = VAGenericValueTypeInteger;
5758                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5759                 attribs[i].value.value.i = VA_FOURCC_IMC1;
5760                 i++;
5761
5762                 attribs[i].type = VASurfaceAttribPixelFormat;
5763                 attribs[i].value.type = VAGenericValueTypeInteger;
5764                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5765                 attribs[i].value.value.i = VA_FOURCC_Y800;
5766                 i++;
5767
5768                 attribs[i].type = VASurfaceAttribPixelFormat;
5769                 attribs[i].value.type = VAGenericValueTypeInteger;
5770                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5771                 attribs[i].value.value.i = VA_FOURCC_411P;
5772                 i++;
5773
5774                 attribs[i].type = VASurfaceAttribPixelFormat;
5775                 attribs[i].value.type = VAGenericValueTypeInteger;
5776                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5777                 attribs[i].value.value.i = VA_FOURCC_422H;
5778                 i++;
5779
5780                 attribs[i].type = VASurfaceAttribPixelFormat;
5781                 attribs[i].value.type = VAGenericValueTypeInteger;
5782                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5783                 attribs[i].value.value.i = VA_FOURCC_422V;
5784                 i++;
5785
5786                 attribs[i].type = VASurfaceAttribPixelFormat;
5787                 attribs[i].value.type = VAGenericValueTypeInteger;
5788                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5789                 attribs[i].value.value.i = VA_FOURCC_444P;
5790                 i++;
5791             } else {
5792                 attribs[i].type = VASurfaceAttribPixelFormat;
5793                 attribs[i].value.type = VAGenericValueTypeInteger;
5794                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5795                 attribs[i].value.value.i = VA_FOURCC_NV12;
5796                 i++;
5797             }
5798         } else if (obj_config->entrypoint == VAEntrypointEncSlice ||  /* encode */
5799                    obj_config->entrypoint == VAEntrypointVideoProc ||
5800                    obj_config->entrypoint == VAEntrypointEncSliceLP) {
5801
5802             if (obj_config->profile == VAProfileHEVCMain10) {
5803                 attribs[i].type = VASurfaceAttribPixelFormat;
5804                 attribs[i].value.type = VAGenericValueTypeInteger;
5805                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5806                 attribs[i].value.value.i = VA_FOURCC_P010;
5807                 i++;
5808             } else {
5809               attribs[i].type = VASurfaceAttribPixelFormat;
5810               attribs[i].value.type = VAGenericValueTypeInteger;
5811               attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5812               attribs[i].value.value.i = VA_FOURCC_NV12;
5813               i++;
5814
5815               attribs[i].type = VASurfaceAttribPixelFormat;
5816               attribs[i].value.type = VAGenericValueTypeInteger;
5817               attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5818               attribs[i].value.value.i = VA_FOURCC_I420;
5819               i++;
5820
5821               attribs[i].type = VASurfaceAttribPixelFormat;
5822               attribs[i].value.type = VAGenericValueTypeInteger;
5823               attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5824               attribs[i].value.value.i = VA_FOURCC_YV12;
5825               i++;
5826
5827               attribs[i].type = VASurfaceAttribPixelFormat;
5828               attribs[i].value.type = VAGenericValueTypeInteger;
5829               attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5830               attribs[i].value.value.i = VA_FOURCC_IMC3;
5831               i++;
5832             }
5833
5834             if (obj_config->entrypoint == VAEntrypointVideoProc) {
5835                 attribs[i].type = VASurfaceAttribPixelFormat;
5836                 attribs[i].value.type = VAGenericValueTypeInteger;
5837                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5838                 attribs[i].value.value.i = VA_FOURCC_YUY2;
5839                 i++;
5840
5841                 attribs[i].type = VASurfaceAttribPixelFormat;
5842                 attribs[i].value.type = VAGenericValueTypeInteger;
5843                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5844                 attribs[i].value.value.i = VA_FOURCC_RGBA;
5845                 i++;
5846
5847                 attribs[i].type = VASurfaceAttribPixelFormat;
5848                 attribs[i].value.type = VAGenericValueTypeInteger;
5849                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5850                 attribs[i].value.value.i = VA_FOURCC_RGBX;
5851                 i++;
5852
5853                 attribs[i].type = VASurfaceAttribPixelFormat;
5854                 attribs[i].value.type = VAGenericValueTypeInteger;
5855                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5856                 attribs[i].value.value.i = VA_FOURCC_BGRA;
5857                 i++;
5858
5859                 attribs[i].type = VASurfaceAttribPixelFormat;
5860                 attribs[i].value.type = VAGenericValueTypeInteger;
5861                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5862                 attribs[i].value.value.i = VA_FOURCC_BGRX;
5863                 i++;
5864
5865                 attribs[i].type = VASurfaceAttribPixelFormat;
5866                 attribs[i].value.type = VAGenericValueTypeInteger;
5867                 attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5868                 attribs[i].value.value.i = VA_FOURCC_YV16;
5869                 i++;
5870
5871                 if(HAS_VPP_P010(i965)) {
5872                   attribs[i].type = VASurfaceAttribPixelFormat;
5873                   attribs[i].value.type = VAGenericValueTypeInteger;
5874                   attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5875                   attribs[i].value.value.i = VA_FOURCC_P010;
5876                   i++;
5877                 }
5878             }
5879         }
5880     }
5881
5882     attribs[i].type = VASurfaceAttribMemoryType;
5883     attribs[i].value.type = VAGenericValueTypeInteger;
5884     attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
5885     attribs[i].value.value.i = VA_SURFACE_ATTRIB_MEM_TYPE_VA |
5886         VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM |
5887         VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME;
5888     i++;
5889
5890     attribs[i].type = VASurfaceAttribExternalBufferDescriptor;
5891     attribs[i].value.type = VAGenericValueTypePointer;
5892     attribs[i].flags = VA_SURFACE_ATTRIB_SETTABLE;
5893     attribs[i].value.value.p = NULL; /* ignore */
5894     i++;
5895
5896     max_resolution(i965, obj_config, &max_width, &max_height);
5897
5898     attribs[i].type = VASurfaceAttribMaxWidth;
5899     attribs[i].value.type = VAGenericValueTypeInteger;
5900     attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE;
5901     attribs[i].value.value.i = max_width;
5902     i++;
5903
5904     attribs[i].type = VASurfaceAttribMaxHeight;
5905     attribs[i].value.type = VAGenericValueTypeInteger;
5906     attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE;
5907     attribs[i].value.value.i = max_height;
5908     i++;
5909
5910     if (i > *num_attribs) {
5911         *num_attribs = i;
5912         free(attribs);
5913         return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
5914     }
5915
5916     *num_attribs = i;
5917     memcpy(attrib_list, attribs, i * sizeof(*attribs));
5918     free(attribs);
5919
5920     return vaStatus;
5921 }
5922
5923 /* Acquires buffer handle for external API usage (internal implementation) */
5924 static VAStatus
5925 i965_acquire_buffer_handle(struct object_buffer *obj_buffer,
5926     uint32_t mem_type, VABufferInfo *out_buf_info)
5927 {
5928     struct buffer_store *buffer_store;
5929
5930     buffer_store = obj_buffer->buffer_store;
5931     if (!buffer_store || !buffer_store->bo)
5932         return VA_STATUS_ERROR_INVALID_BUFFER;
5933
5934     /* Synchronization point */
5935     drm_intel_bo_wait_rendering(buffer_store->bo);
5936
5937     if (obj_buffer->export_refcount > 0) {
5938         if (obj_buffer->export_state.mem_type != mem_type)
5939             return VA_STATUS_ERROR_INVALID_PARAMETER;
5940     }
5941     else {
5942         VABufferInfo * const buf_info = &obj_buffer->export_state;
5943
5944         switch (mem_type) {
5945         case VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM: {
5946             uint32_t name;
5947             if (drm_intel_bo_flink(buffer_store->bo, &name) != 0)
5948                 return VA_STATUS_ERROR_INVALID_BUFFER;
5949             buf_info->handle = name;
5950             break;
5951         }
5952         case VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME: {
5953             int fd;
5954             if (drm_intel_bo_gem_export_to_prime(buffer_store->bo, &fd) != 0)
5955                 return VA_STATUS_ERROR_INVALID_BUFFER;
5956             buf_info->handle = (intptr_t)fd;
5957             break;
5958         }
5959         }
5960
5961         buf_info->type = obj_buffer->type;
5962         buf_info->mem_type = mem_type;
5963         buf_info->mem_size =
5964             obj_buffer->num_elements * obj_buffer->size_element;
5965     }
5966
5967     obj_buffer->export_refcount++;
5968     *out_buf_info = obj_buffer->export_state;
5969     return VA_STATUS_SUCCESS;
5970 }
5971
5972 /* Releases buffer handle after usage (internal implementation) */
5973 static VAStatus
5974 i965_release_buffer_handle(struct object_buffer *obj_buffer)
5975 {
5976     if (obj_buffer->export_refcount == 0)
5977         return VA_STATUS_ERROR_INVALID_BUFFER;
5978
5979     if (--obj_buffer->export_refcount == 0) {
5980         VABufferInfo * const buf_info = &obj_buffer->export_state;
5981
5982         switch (buf_info->mem_type) {
5983         case VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME: {
5984             close((intptr_t)buf_info->handle);
5985             break;
5986         }
5987         }
5988         buf_info->mem_type = 0;
5989     }
5990     return VA_STATUS_SUCCESS;
5991 }
5992
5993 /** Acquires buffer handle for external API usage */
5994 static VAStatus
5995 i965_AcquireBufferHandle(VADriverContextP ctx, VABufferID buf_id,
5996     VABufferInfo *buf_info)
5997 {
5998     struct i965_driver_data * const i965 = i965_driver_data(ctx);
5999     struct object_buffer * const obj_buffer = BUFFER(buf_id);
6000     uint32_t i, mem_type;
6001
6002     /* List of supported memory types, in preferred order */
6003     static const uint32_t mem_types[] = {
6004         VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME,
6005         VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM,
6006         0
6007     };
6008
6009     if (!obj_buffer)
6010         return VA_STATUS_ERROR_INVALID_BUFFER;
6011     /* XXX: only VA surface|image like buffers are supported for now */
6012     if (obj_buffer->type != VAImageBufferType)
6013         return VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
6014
6015     /*
6016      * As the allocated buffer by calling vaCreateBuffer is related with
6017      * the specific context, it is unnecessary to export it.
6018      * So it is not supported when the buffer is allocated from wrapped
6019      * backend dirver.
6020      */
6021     if (obj_buffer->wrapper_buffer != VA_INVALID_ID) {
6022         return VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
6023     }
6024
6025     if (!buf_info)
6026         return VA_STATUS_ERROR_INVALID_PARAMETER;
6027
6028     if (!buf_info->mem_type)
6029         mem_type = mem_types[0];
6030     else {
6031         mem_type = 0;
6032         for (i = 0; mem_types[i] != 0; i++) {
6033             if (buf_info->mem_type & mem_types[i]) {
6034                 mem_type = buf_info->mem_type;
6035                 break;
6036             }
6037         }
6038         if (!mem_type)
6039             return VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE;
6040     }
6041     return i965_acquire_buffer_handle(obj_buffer, mem_type, buf_info);
6042 }
6043
6044 /** Releases buffer handle after usage from external API */
6045 static VAStatus
6046 i965_ReleaseBufferHandle(VADriverContextP ctx, VABufferID buf_id)
6047 {
6048     struct i965_driver_data * const i965 = i965_driver_data(ctx);
6049     struct object_buffer * const obj_buffer = BUFFER(buf_id);
6050
6051     if (!obj_buffer)
6052         return VA_STATUS_ERROR_INVALID_BUFFER;
6053
6054     if (obj_buffer->wrapper_buffer != VA_INVALID_ID) {
6055         return VA_STATUS_ERROR_INVALID_BUFFER;
6056     }
6057
6058     return i965_release_buffer_handle(obj_buffer);
6059 }
6060
6061 static int
6062 i965_os_has_ring_support(VADriverContextP ctx,
6063                          int ring)
6064 {
6065     struct i965_driver_data *const i965 = i965_driver_data(ctx);
6066
6067     switch (ring) {
6068     case I965_RING_BSD:
6069         return i965->intel.has_bsd;
6070         
6071     case I965_RING_BLT:
6072         return i965->intel.has_blt;
6073         
6074     case I965_RING_VEBOX:
6075         return i965->intel.has_vebox;
6076
6077     case I965_RING_NULL:
6078         return 1; /* Always support */
6079
6080     default:
6081         /* should never get here */
6082         assert(0);
6083         break;
6084     }
6085
6086     return 0;
6087 }
6088                                 
6089 /* 
6090  * Query video processing pipeline 
6091  */
6092 VAStatus i965_QueryVideoProcFilters(
6093     VADriverContextP    ctx,
6094     VAContextID         context,
6095     VAProcFilterType   *filters,
6096     unsigned int       *num_filters
6097     )
6098 {
6099     struct i965_driver_data *const i965 = i965_driver_data(ctx);
6100     unsigned int i = 0, num = 0;
6101
6102     if (!num_filters  || !filters)
6103         return VA_STATUS_ERROR_INVALID_PARAMETER;
6104
6105     for (i = 0; i < i965->codec_info->num_filters; i++) {
6106         if (i965_os_has_ring_support(ctx, i965->codec_info->filters[i].ring)) {
6107             if (num == *num_filters) {
6108                 *num_filters = i965->codec_info->num_filters;
6109
6110                 return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
6111             }
6112          
6113             filters[num++] = i965->codec_info->filters[i].type;
6114         }
6115     }
6116
6117     *num_filters = num;
6118
6119     return VA_STATUS_SUCCESS;
6120 }
6121
6122 VAStatus i965_QueryVideoProcFilterCaps(
6123     VADriverContextP    ctx,
6124     VAContextID         context,
6125     VAProcFilterType    type,
6126     void               *filter_caps,
6127     unsigned int       *num_filter_caps
6128     )
6129 {
6130     unsigned int i = 0;
6131     struct i965_driver_data *const i965 = i965_driver_data(ctx);
6132
6133     if (!filter_caps || !num_filter_caps)
6134         return VA_STATUS_ERROR_INVALID_PARAMETER;
6135
6136     for (i = 0; i < i965->codec_info->num_filters; i++) {
6137         if (type == i965->codec_info->filters[i].type &&
6138             i965_os_has_ring_support(ctx, i965->codec_info->filters[i].ring))
6139             break;
6140     }
6141
6142     if (i == i965->codec_info->num_filters)
6143         return VA_STATUS_ERROR_UNSUPPORTED_FILTER;
6144
6145     i = 0;
6146
6147     switch (type) {
6148     case VAProcFilterNoiseReduction:
6149     case VAProcFilterSharpening:
6150         {
6151             VAProcFilterCap *cap = filter_caps;
6152
6153             if (*num_filter_caps < 1) {
6154                 *num_filter_caps = 1;
6155                 return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
6156             }
6157             
6158             cap->range.min_value = 0.0;
6159             cap->range.max_value = 1.0;
6160             cap->range.default_value = 0.5;
6161             cap->range.step = 0.03125; /* 1.0 / 32 */
6162             i++;
6163         }
6164
6165         break;
6166
6167     case VAProcFilterDeinterlacing:
6168         {
6169             VAProcFilterCapDeinterlacing *cap = filter_caps;
6170
6171             if (*num_filter_caps < VAProcDeinterlacingCount) {
6172                 *num_filter_caps = VAProcDeinterlacingCount;
6173                 return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
6174             }
6175         
6176             cap->type = VAProcDeinterlacingBob;
6177             i++;
6178             cap++;
6179
6180
6181             if (i965->codec_info->has_di_motion_adptive) {
6182                 cap->type = VAProcDeinterlacingMotionAdaptive;
6183                 i++;
6184                 cap++;
6185             }
6186
6187             if (i965->codec_info->has_di_motion_compensated) {
6188                 cap->type = VAProcDeinterlacingMotionCompensated;
6189                 i++;
6190                 cap++;
6191             }
6192        }
6193
6194         break;
6195
6196     case VAProcFilterColorBalance:
6197         {
6198             VAProcFilterCapColorBalance *cap = filter_caps;
6199
6200             if (*num_filter_caps < VAProcColorBalanceCount) {
6201                 *num_filter_caps = VAProcColorBalanceCount;
6202                 return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
6203             }
6204
6205             cap->type = VAProcColorBalanceHue;
6206             cap->range.min_value = -180.0;
6207             cap->range.max_value = 180.0;
6208             cap->range.default_value = 0.0;
6209             cap->range.step = 1.0; 
6210             i++;
6211             cap++; 
6212  
6213             cap->type = VAProcColorBalanceSaturation;
6214             cap->range.min_value = 0.0;
6215             cap->range.max_value = 10.0;
6216             cap->range.default_value = 1.0;
6217             cap->range.step = 0.1; 
6218             i++;
6219             cap++; 
6220  
6221             cap->type = VAProcColorBalanceBrightness;
6222             cap->range.min_value = -100.0;
6223             cap->range.max_value = 100.0;
6224             cap->range.default_value = 0.0;
6225             cap->range.step = 1.0; 
6226             i++;
6227             cap++; 
6228  
6229             cap->type = VAProcColorBalanceContrast;
6230             cap->range.min_value = 0.0;
6231             cap->range.max_value = 10.0;
6232             cap->range.default_value = 1.0;
6233             cap->range.step = 0.1; 
6234             i++;
6235             cap++; 
6236         }
6237
6238         break;
6239
6240     default:
6241         
6242         break;
6243     }
6244
6245     *num_filter_caps = i;
6246
6247     return VA_STATUS_SUCCESS;
6248 }
6249
6250 static VAProcColorStandardType vpp_input_color_standards[VAProcColorStandardCount] = {
6251     VAProcColorStandardBT601,
6252 };
6253
6254 static VAProcColorStandardType vpp_output_color_standards[VAProcColorStandardCount] = {
6255     VAProcColorStandardBT601,
6256 };
6257
6258 VAStatus i965_QueryVideoProcPipelineCaps(
6259     VADriverContextP ctx,
6260     VAContextID context,
6261     VABufferID *filters,
6262     unsigned int num_filters,
6263     VAProcPipelineCaps *pipeline_cap     /* out */
6264     )
6265 {
6266     struct i965_driver_data * const i965 = i965_driver_data(ctx);
6267     unsigned int i = 0;
6268
6269     pipeline_cap->pipeline_flags = 0;
6270     pipeline_cap->filter_flags = 0;
6271     pipeline_cap->num_forward_references = 0;
6272     pipeline_cap->num_backward_references = 0;
6273     pipeline_cap->num_input_color_standards = 1;
6274     pipeline_cap->input_color_standards = vpp_input_color_standards;
6275     pipeline_cap->num_output_color_standards = 1;
6276     pipeline_cap->output_color_standards = vpp_output_color_standards;
6277
6278     for (i = 0; i < num_filters; i++) {
6279         struct object_buffer *obj_buffer = BUFFER(filters[i]);
6280
6281         if (!obj_buffer ||
6282             !obj_buffer->buffer_store ||
6283             !obj_buffer->buffer_store->buffer)
6284             return VA_STATUS_ERROR_INVALID_BUFFER;
6285
6286         VAProcFilterParameterBufferBase *base = (VAProcFilterParameterBufferBase *)obj_buffer->buffer_store->buffer;
6287
6288         if (base->type == VAProcFilterNoiseReduction) {
6289             VAProcFilterParameterBuffer *denoise = (VAProcFilterParameterBuffer *)base;
6290             (void)denoise;
6291         } else if (base->type == VAProcFilterDeinterlacing) {
6292             VAProcFilterParameterBufferDeinterlacing *deint = (VAProcFilterParameterBufferDeinterlacing *)base;
6293
6294             ASSERT_RET(deint->algorithm == VAProcDeinterlacingBob ||
6295                    deint->algorithm == VAProcDeinterlacingMotionAdaptive ||
6296                    deint->algorithm == VAProcDeinterlacingMotionCompensated,
6297                    VA_STATUS_ERROR_INVALID_PARAMETER);
6298             
6299             if (deint->algorithm == VAProcDeinterlacingMotionAdaptive ||
6300                 deint->algorithm == VAProcDeinterlacingMotionCompensated)
6301                 pipeline_cap->num_forward_references++;
6302         } else if (base->type == VAProcFilterSkinToneEnhancement) {
6303                 VAProcFilterParameterBuffer *stde = (VAProcFilterParameterBuffer *)base;
6304                 (void)stde;
6305         }
6306     }
6307
6308     return VA_STATUS_SUCCESS;
6309 }
6310
6311 extern struct hw_codec_info *i965_get_codec_info(int devid);
6312
6313 static bool
6314 i965_driver_data_init(VADriverContextP ctx)
6315 {
6316     struct i965_driver_data *i965 = i965_driver_data(ctx); 
6317
6318     i965->codec_info = i965_get_codec_info(i965->intel.device_id);
6319
6320     if (!i965->codec_info)
6321         return false;
6322
6323     if (object_heap_init(&i965->config_heap,
6324                          sizeof(struct object_config),
6325                          CONFIG_ID_OFFSET))
6326         goto err_config_heap;
6327     if (object_heap_init(&i965->context_heap,
6328                          sizeof(struct object_context),
6329                          CONTEXT_ID_OFFSET))
6330         goto err_context_heap;
6331     
6332     if (object_heap_init(&i965->surface_heap,
6333                          sizeof(struct object_surface),
6334                          SURFACE_ID_OFFSET))
6335         goto err_surface_heap;
6336     if (object_heap_init(&i965->buffer_heap,
6337                          sizeof(struct object_buffer),
6338                          BUFFER_ID_OFFSET))
6339         goto err_buffer_heap;
6340     if (object_heap_init(&i965->image_heap,
6341                          sizeof(struct object_image),
6342                          IMAGE_ID_OFFSET))
6343         goto err_image_heap;
6344     if (object_heap_init(&i965->subpic_heap,
6345                          sizeof(struct object_subpic),
6346                          SUBPIC_ID_OFFSET))
6347         goto err_subpic_heap;
6348
6349     i965->batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_RENDER, 0);
6350     i965->pp_batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_RENDER, 0);
6351     _i965InitMutex(&i965->render_mutex);
6352     _i965InitMutex(&i965->pp_mutex);
6353
6354     return true;
6355
6356 err_subpic_heap:    
6357     object_heap_destroy(&i965->image_heap);
6358 err_image_heap:
6359     object_heap_destroy(&i965->buffer_heap);
6360 err_buffer_heap:
6361     object_heap_destroy(&i965->surface_heap);
6362 err_surface_heap:
6363     object_heap_destroy(&i965->context_heap);
6364 err_context_heap:
6365     object_heap_destroy(&i965->config_heap);
6366 err_config_heap:
6367
6368     return false;
6369 }
6370
6371 static void
6372 i965_driver_data_terminate(VADriverContextP ctx)
6373 {
6374     struct i965_driver_data *i965 = i965_driver_data(ctx); 
6375
6376     _i965DestroyMutex(&i965->pp_mutex);
6377     _i965DestroyMutex(&i965->render_mutex);
6378
6379     if (i965->batch)
6380         intel_batchbuffer_free(i965->batch);
6381
6382     if (i965->pp_batch)
6383         intel_batchbuffer_free(i965->pp_batch);
6384
6385     i965_destroy_heap(&i965->subpic_heap, i965_destroy_subpic);
6386     i965_destroy_heap(&i965->image_heap, i965_destroy_image);
6387     i965_destroy_heap(&i965->buffer_heap, i965_destroy_buffer);
6388     i965_destroy_heap(&i965->surface_heap, i965_destroy_surface);
6389     i965_destroy_heap(&i965->context_heap, i965_destroy_context);
6390     i965_destroy_heap(&i965->config_heap, i965_destroy_config);
6391 }
6392
6393 struct {
6394     bool (*init)(VADriverContextP ctx);
6395     void (*terminate)(VADriverContextP ctx);
6396     int display_type;
6397 } i965_sub_ops[] =  {
6398     {   
6399         intel_driver_init,
6400         intel_driver_terminate,
6401         0,
6402     },
6403
6404     {
6405         i965_driver_data_init,
6406         i965_driver_data_terminate,
6407         0,
6408     },
6409
6410     {
6411         i965_display_attributes_init,
6412         i965_display_attributes_terminate,
6413         0,
6414     },
6415
6416     {
6417         i965_post_processing_init,
6418         i965_post_processing_terminate,
6419         0,
6420     },
6421
6422     {
6423         i965_render_init,
6424         i965_render_terminate,
6425         0,
6426     },
6427
6428 #ifdef HAVE_VA_WAYLAND
6429     {
6430         i965_output_wayland_init,
6431         i965_output_wayland_terminate,
6432         VA_DISPLAY_WAYLAND,
6433     },
6434 #endif
6435
6436 #ifdef HAVE_VA_X11
6437     {
6438         i965_output_dri_init,
6439         i965_output_dri_terminate,
6440         VA_DISPLAY_X11,
6441     },
6442 #endif
6443 };
6444
6445 static bool
6446 ensure_vendor_string(struct i965_driver_data *i965, const char *chipset)
6447 {
6448     int ret, len;
6449
6450     if (i965->va_vendor[0] != '\0')
6451         return true;
6452
6453     len = 0;
6454     ret = snprintf(i965->va_vendor, sizeof(i965->va_vendor),
6455         "%s %s driver for %s - %d.%d.%d",
6456         INTEL_STR_DRIVER_VENDOR, INTEL_STR_DRIVER_NAME, chipset,
6457         INTEL_DRIVER_MAJOR_VERSION, INTEL_DRIVER_MINOR_VERSION,
6458         INTEL_DRIVER_MICRO_VERSION);
6459     if (ret < 0 || ret >= sizeof(i965->va_vendor))
6460         goto error;
6461     len = ret;
6462
6463     if (INTEL_DRIVER_PRE_VERSION > 0) {
6464         ret = snprintf(&i965->va_vendor[len], sizeof(i965->va_vendor) - len,
6465             ".pre%d", INTEL_DRIVER_PRE_VERSION);
6466         if (ret < 0 || ret >= sizeof(i965->va_vendor))
6467             goto error;
6468         len += ret;
6469
6470         ret = snprintf(&i965->va_vendor[len], sizeof(i965->va_vendor) - len,
6471             " (%s)", INTEL_DRIVER_GIT_VERSION);
6472         if (ret < 0 || ret >= sizeof(i965->va_vendor))
6473             goto error;
6474         len += ret;
6475     }
6476     return true;
6477
6478 error:
6479     i965->va_vendor[0] = '\0';
6480     ASSERT_RET(ret > 0 && len < sizeof(i965->va_vendor), false);
6481     return false;
6482 }
6483
6484 /* Only when the option of "enable-wrapper" is passed, it is possible
6485  * to initialize/load the wrapper context of backend driver.
6486  * Otherwise it is not loaded.
6487  */
6488 #if HAVE_HYBRID_CODEC
6489
6490 static VAStatus
6491 i965_initialize_wrapper(VADriverContextP ctx, const char *driver_name)
6492 {
6493 #define DRIVER_EXTENSION        "_drv_video.so"
6494
6495     struct i965_driver_data *i965 = i965_driver_data(ctx);
6496
6497     VADriverContextP wrapper_pdrvctx;
6498     struct VADriverVTable *vtable;
6499     char *search_path, *driver_dir;
6500     char *saveptr;
6501     char driver_path[256];
6502     void *handle = NULL;
6503     VAStatus va_status = VA_STATUS_SUCCESS;
6504     bool driver_loaded = false;
6505
6506     if (HAS_VP9_DECODING(i965)) {
6507         i965->wrapper_pdrvctx = NULL;
6508         return va_status;
6509     }
6510
6511     wrapper_pdrvctx = calloc(1, sizeof(*wrapper_pdrvctx));
6512     vtable = calloc(1, sizeof(*vtable));
6513
6514     if (!wrapper_pdrvctx || !vtable) {
6515         fprintf(stderr, "Failed to allocate memory for wrapper \n");
6516         free(wrapper_pdrvctx);
6517         free(vtable);
6518         return VA_STATUS_ERROR_ALLOCATION_FAILED;
6519     }
6520
6521     /* use the same drm_state with CTX */
6522     wrapper_pdrvctx->drm_state = ctx->drm_state;
6523     wrapper_pdrvctx->display_type = ctx->display_type;
6524     wrapper_pdrvctx->vtable = vtable;
6525
6526     search_path = VA_DRIVERS_PATH;
6527     search_path = strdup((const char *)search_path);
6528
6529     driver_dir = strtok_r(search_path, ":", &saveptr);
6530     while (driver_dir && !driver_loaded) {
6531         memset(driver_path, 0, sizeof(driver_path));
6532         sprintf(driver_path, "%s/%s%s", driver_dir, driver_name, DRIVER_EXTENSION);
6533
6534         handle = dlopen(driver_path, RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE);
6535         if (!handle) {
6536             fprintf(stderr, "failed to open %s\n", driver_path);
6537             driver_dir = strtok_r(NULL, ":", &saveptr);
6538             continue;
6539         }
6540         {
6541             VADriverInit init_func = NULL;
6542             char init_func_s[256];
6543             int i;
6544
6545             static const struct {
6546                 int major;
6547                 int minor;
6548             } compatible_versions[] = {
6549                 { VA_MAJOR_VERSION, VA_MINOR_VERSION },
6550                 { 0, 37 },
6551                 { 0, 36 },
6552                 { 0, 35 },
6553                 { 0, 34 },
6554                 { 0, 33 },
6555                 { 0, 32 },
6556                 { -1, }
6557             };
6558             for (i = 0; compatible_versions[i].major >= 0; i++) {
6559                 snprintf(init_func_s, sizeof(init_func_s),
6560                      "__vaDriverInit_%d_%d",
6561                      compatible_versions[i].major,
6562                      compatible_versions[i].minor);
6563                 init_func = (VADriverInit)dlsym(handle, init_func_s);
6564                 if (init_func) {
6565                     break;
6566                 }
6567             }
6568             if (compatible_versions[i].major < 0) {
6569                 dlclose(handle);
6570                 fprintf(stderr, "%s has no function %s\n",
6571                             driver_path, init_func_s);
6572                 driver_dir = strtok_r(NULL, ":", &saveptr);
6573                 continue;
6574             }
6575
6576             if (init_func)
6577                 va_status = (*init_func)(wrapper_pdrvctx);
6578
6579             if (va_status != VA_STATUS_SUCCESS) {
6580                 dlclose(handle);
6581                 fprintf(stderr, "%s init failed\n", driver_path);
6582                 driver_dir = strtok_r(NULL, ":", &saveptr);
6583                 continue;
6584             }
6585
6586             wrapper_pdrvctx->handle = handle;
6587             driver_loaded = true;
6588         }
6589     }
6590
6591     free(search_path);
6592
6593     if (driver_loaded) {
6594         i965->wrapper_pdrvctx = wrapper_pdrvctx;
6595         return VA_STATUS_SUCCESS;
6596     } else {
6597         fprintf(stderr, "Failed to wrapper %s%s\n", driver_name, DRIVER_EXTENSION);
6598         free(vtable);
6599         free(wrapper_pdrvctx);
6600         return VA_STATUS_ERROR_OPERATION_FAILED;
6601     }
6602 }
6603 #endif
6604
6605 static VAStatus 
6606 i965_Init(VADriverContextP ctx)
6607 {
6608     struct i965_driver_data *i965 = i965_driver_data(ctx); 
6609     int i;
6610     const char *chipset;
6611
6612     for (i = 0; i < ARRAY_ELEMS(i965_sub_ops); i++) {
6613         if ((i965_sub_ops[i].display_type == 0 ||
6614              i965_sub_ops[i].display_type == (ctx->display_type & VA_DISPLAY_MAJOR_MASK)) &&
6615             !i965_sub_ops[i].init(ctx))
6616             break;
6617     }
6618
6619     if (i == ARRAY_ELEMS(i965_sub_ops)) {
6620         switch (i965->intel.device_id) {
6621 #undef CHIPSET
6622 #define CHIPSET(id, family, dev, str) case id: chipset = str; break;
6623 #include "i965_pciids.h"
6624         default:
6625             chipset = "Unknown Intel Chipset";
6626             break;
6627         }
6628
6629         if (!ensure_vendor_string(i965, chipset))
6630             return VA_STATUS_ERROR_ALLOCATION_FAILED;
6631
6632         i965->current_context_id = VA_INVALID_ID;
6633
6634         if (i965->codec_info && i965->codec_info->preinit_hw_codec)
6635             i965->codec_info->preinit_hw_codec(ctx, i965->codec_info);
6636
6637 #if HAVE_HYBRID_CODEC
6638         i965_initialize_wrapper(ctx, "hybrid");
6639 #endif
6640
6641         return VA_STATUS_SUCCESS;
6642     } else {
6643         i--;
6644
6645         for (; i >= 0; i--) {
6646             if (i965_sub_ops[i].display_type == 0 ||
6647                 i965_sub_ops[i].display_type == (ctx->display_type & VA_DISPLAY_MAJOR_MASK)) {
6648                 i965_sub_ops[i].terminate(ctx);
6649             }
6650         }
6651
6652         return VA_STATUS_ERROR_UNKNOWN;
6653     }
6654 }
6655
6656 VAStatus 
6657 i965_Terminate(VADriverContextP ctx)
6658 {
6659     struct i965_driver_data *i965 = i965_driver_data(ctx);
6660     int i;
6661
6662     if (i965) {
6663         if (i965->wrapper_pdrvctx) {
6664             VADriverContextP pdrvctx;
6665             pdrvctx = i965->wrapper_pdrvctx;
6666             if (pdrvctx->handle) {
6667                 pdrvctx->vtable->vaTerminate(pdrvctx);
6668                 dlclose(pdrvctx->handle);
6669                 pdrvctx->handle = NULL;
6670             }
6671             free(pdrvctx->vtable);
6672             free(pdrvctx);
6673             i965->wrapper_pdrvctx = NULL;
6674         }
6675
6676         for (i = ARRAY_ELEMS(i965_sub_ops); i > 0; i--)
6677             if (i965_sub_ops[i - 1].display_type == 0 ||
6678                 i965_sub_ops[i - 1].display_type == (ctx->display_type & VA_DISPLAY_MAJOR_MASK)) {
6679                 i965_sub_ops[i - 1].terminate(ctx);
6680             }
6681
6682         free(i965);
6683         ctx->pDriverData = NULL;        
6684     }
6685
6686     return VA_STATUS_SUCCESS;
6687 }
6688
6689 VAStatus DLL_EXPORT
6690 VA_DRIVER_INIT_FUNC(VADriverContextP ctx);
6691
6692 VAStatus 
6693 VA_DRIVER_INIT_FUNC(  VADriverContextP ctx )
6694 {
6695     struct VADriverVTable * const vtable = ctx->vtable;
6696     struct VADriverVTableVPP * const vtable_vpp = ctx->vtable_vpp;
6697
6698     struct i965_driver_data *i965;
6699     VAStatus ret = VA_STATUS_ERROR_UNKNOWN;
6700
6701     ctx->version_major = VA_MAJOR_VERSION;
6702     ctx->version_minor = VA_MINOR_VERSION;
6703     ctx->max_profiles = I965_MAX_PROFILES;
6704     ctx->max_entrypoints = I965_MAX_ENTRYPOINTS;
6705     ctx->max_attributes = I965_MAX_CONFIG_ATTRIBUTES;
6706     ctx->max_image_formats = I965_MAX_IMAGE_FORMATS;
6707     ctx->max_subpic_formats = I965_MAX_SUBPIC_FORMATS;
6708     ctx->max_display_attributes = 1 + ARRAY_ELEMS(i965_display_attributes);
6709
6710     vtable->vaTerminate = i965_Terminate;
6711     vtable->vaQueryConfigEntrypoints = i965_QueryConfigEntrypoints;
6712     vtable->vaQueryConfigProfiles = i965_QueryConfigProfiles;
6713     vtable->vaQueryConfigAttributes = i965_QueryConfigAttributes;
6714     vtable->vaCreateConfig = i965_CreateConfig;
6715     vtable->vaDestroyConfig = i965_DestroyConfig;
6716     vtable->vaGetConfigAttributes = i965_GetConfigAttributes;
6717     vtable->vaCreateSurfaces = i965_CreateSurfaces;
6718     vtable->vaDestroySurfaces = i965_DestroySurfaces;
6719     vtable->vaCreateContext = i965_CreateContext;
6720     vtable->vaDestroyContext = i965_DestroyContext;
6721     vtable->vaCreateBuffer = i965_CreateBuffer;
6722     vtable->vaBufferSetNumElements = i965_BufferSetNumElements;
6723     vtable->vaMapBuffer = i965_MapBuffer;
6724     vtable->vaUnmapBuffer = i965_UnmapBuffer;
6725     vtable->vaDestroyBuffer = i965_DestroyBuffer;
6726     vtable->vaBeginPicture = i965_BeginPicture;
6727     vtable->vaRenderPicture = i965_RenderPicture;
6728     vtable->vaEndPicture = i965_EndPicture;
6729     vtable->vaSyncSurface = i965_SyncSurface;
6730     vtable->vaQuerySurfaceStatus = i965_QuerySurfaceStatus;
6731     vtable->vaPutSurface = i965_PutSurface;
6732     vtable->vaQueryImageFormats = i965_QueryImageFormats;
6733     vtable->vaCreateImage = i965_CreateImage;
6734     vtable->vaDeriveImage = i965_DeriveImage;
6735     vtable->vaDestroyImage = i965_DestroyImage;
6736     vtable->vaSetImagePalette = i965_SetImagePalette;
6737     vtable->vaGetImage = i965_GetImage;
6738     vtable->vaPutImage = i965_PutImage;
6739     vtable->vaQuerySubpictureFormats = i965_QuerySubpictureFormats;
6740     vtable->vaCreateSubpicture = i965_CreateSubpicture;
6741     vtable->vaDestroySubpicture = i965_DestroySubpicture;
6742     vtable->vaSetSubpictureImage = i965_SetSubpictureImage;
6743     vtable->vaSetSubpictureChromakey = i965_SetSubpictureChromakey;
6744     vtable->vaSetSubpictureGlobalAlpha = i965_SetSubpictureGlobalAlpha;
6745     vtable->vaAssociateSubpicture = i965_AssociateSubpicture;
6746     vtable->vaDeassociateSubpicture = i965_DeassociateSubpicture;
6747     vtable->vaQueryDisplayAttributes = i965_QueryDisplayAttributes;
6748     vtable->vaGetDisplayAttributes = i965_GetDisplayAttributes;
6749     vtable->vaSetDisplayAttributes = i965_SetDisplayAttributes;
6750     vtable->vaBufferInfo = i965_BufferInfo;
6751     vtable->vaLockSurface = i965_LockSurface;
6752     vtable->vaUnlockSurface = i965_UnlockSurface;
6753     vtable->vaGetSurfaceAttributes = i965_GetSurfaceAttributes;
6754     vtable->vaQuerySurfaceAttributes = i965_QuerySurfaceAttributes;
6755     vtable->vaCreateSurfaces2 = i965_CreateSurfaces2;
6756
6757     /* 0.36.0 */
6758     vtable->vaAcquireBufferHandle = i965_AcquireBufferHandle;
6759     vtable->vaReleaseBufferHandle = i965_ReleaseBufferHandle;
6760
6761     vtable_vpp->vaQueryVideoProcFilters = i965_QueryVideoProcFilters;
6762     vtable_vpp->vaQueryVideoProcFilterCaps = i965_QueryVideoProcFilterCaps;
6763     vtable_vpp->vaQueryVideoProcPipelineCaps = i965_QueryVideoProcPipelineCaps;
6764
6765     i965 = (struct i965_driver_data *)calloc(1, sizeof(*i965));
6766
6767     if (i965 == NULL) {
6768         ctx->pDriverData = NULL;
6769
6770         return VA_STATUS_ERROR_ALLOCATION_FAILED;
6771     }
6772
6773     i965->wrapper_pdrvctx = NULL;
6774     ctx->pDriverData = (void *)i965;
6775     ret = i965_Init(ctx);
6776
6777     if (ret == VA_STATUS_SUCCESS) {
6778         ctx->str_vendor = i965->va_vendor;
6779     } else {
6780         free(i965);
6781         ctx->pDriverData = NULL;
6782     }
6783
6784     return ret;
6785 }