OSDN Git Service

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