OSDN Git Service

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