5051f31a60fbc5c17b14b85878d4f735edc94ea9
[profile/ivi/vaapi-intel-driver.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 #ifdef ANDROID
30 #include "config_android.h"
31 #else
32 #include "config.h"
33 #endif
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <stdbool.h>
37 #include <string.h>
38 #include <assert.h>
39
40 #ifdef HAVE_VA_X11
41 # include "i965_output_dri.h"
42 #endif
43
44 #ifdef HAVE_VA_WAYLAND
45 # include "i965_output_wayland.h"
46 #endif
47
48 #include "intel_driver.h"
49 #include "intel_memman.h"
50 #include "intel_batchbuffer.h"
51 #include "i965_defines.h"
52 #include "i965_drv_video.h"
53 #include "i965_decoder.h"
54 #include "i965_encoder.h"
55
56 #define CONFIG_ID_OFFSET                0x01000000
57 #define CONTEXT_ID_OFFSET               0x02000000
58 #define SURFACE_ID_OFFSET               0x04000000
59 #define BUFFER_ID_OFFSET                0x08000000
60 #define IMAGE_ID_OFFSET                 0x0a000000
61 #define SUBPIC_ID_OFFSET                0x10000000
62
63 #define HAS_MPEG2_DECODING(ctx)  ((ctx)->codec_info->has_mpeg2_decoding && \
64                                   (ctx)->intel.has_bsd)
65
66 #define HAS_MPEG2_ENCODING(ctx)  ((ctx)->codec_info->has_mpeg2_encoding && \
67                                   (ctx)->intel.has_bsd)
68
69 #define HAS_H264_DECODING(ctx)  ((ctx)->codec_info->has_h264_decoding && \
70                                  (ctx)->intel.has_bsd)
71
72 #define HAS_H264_ENCODING(ctx)  ((ctx)->codec_info->has_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_VPP(ctx)    ((ctx)->codec_info->has_vpp)
82
83 #define HAS_ACCELERATED_GETIMAGE(ctx)   ((ctx)->codec_info->has_accelerated_getimage)
84
85 #define HAS_ACCELERATED_PUTIMAGE(ctx)   ((ctx)->codec_info->has_accelerated_putimage)
86
87 #define HAS_TILED_SURFACE(ctx) ((ctx)->codec_info->has_tiled_surface)
88
89 static int get_sampling_from_fourcc(unsigned int fourcc);
90
91 /* Check whether we are rendering to X11 (VA/X11 or VA/GLX API) */
92 #define IS_VA_X11(ctx) \
93     (((ctx)->display_type & VA_DISPLAY_MAJOR_MASK) == VA_DISPLAY_X11)
94
95 /* Check whether we are rendering to Wayland */
96 #define IS_VA_WAYLAND(ctx) \
97     (((ctx)->display_type & VA_DISPLAY_MAJOR_MASK) == VA_DISPLAY_WAYLAND)
98
99 enum {
100     I965_SURFACETYPE_RGBA = 1,
101     I965_SURFACETYPE_YUV,
102     I965_SURFACETYPE_INDEXED
103 };
104
105 /* List of supported display attributes */
106 static const VADisplayAttribute i965_display_attributes[] = {
107     {
108         VADisplayAttribRotation,
109         0, 3, VA_ROTATION_NONE,
110         VA_DISPLAY_ATTRIB_GETTABLE|VA_DISPLAY_ATTRIB_SETTABLE
111     },
112 };
113
114 /* List of supported image formats */
115 typedef struct {
116     unsigned int        type;
117     VAImageFormat       va_format;
118 } i965_image_format_map_t;
119
120 static const i965_image_format_map_t
121 i965_image_formats_map[I965_MAX_IMAGE_FORMATS + 1] = {
122     { I965_SURFACETYPE_YUV,
123       { VA_FOURCC('Y','V','1','2'), VA_LSB_FIRST, 12, } },
124     { I965_SURFACETYPE_YUV,
125       { VA_FOURCC('I','4','2','0'), VA_LSB_FIRST, 12, } },
126     { I965_SURFACETYPE_YUV,
127       { VA_FOURCC('N','V','1','2'), VA_LSB_FIRST, 12, } },
128     { I965_SURFACETYPE_YUV,
129       { VA_FOURCC('Y','U','Y','2'), VA_LSB_FIRST, 16, } },
130     { I965_SURFACETYPE_YUV,
131       { VA_FOURCC('U','Y','V','Y'), VA_LSB_FIRST, 16, } },
132     { I965_SURFACETYPE_RGBA,
133       { VA_FOURCC('R','G','B','X'), VA_LSB_FIRST, 32, 24, 0x000000ff, 0x0000ff00, 0x00ff0000 } },
134     { I965_SURFACETYPE_RGBA,
135       { VA_FOURCC('B','G','R','X'), VA_LSB_FIRST, 32, 24, 0x00ff0000, 0x0000ff00, 0x000000ff } },
136 };
137
138 /* List of supported subpicture formats */
139 typedef struct {
140     unsigned int        type;
141     unsigned int        format;
142     VAImageFormat       va_format;
143     unsigned int        va_flags;
144 } i965_subpic_format_map_t;
145
146 #define COMMON_SUBPICTURE_FLAGS                 \
147     (VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD| \
148      VA_SUBPICTURE_GLOBAL_ALPHA)
149
150 static const i965_subpic_format_map_t
151 i965_subpic_formats_map[I965_MAX_SUBPIC_FORMATS + 1] = {
152     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_P4A4_UNORM,
153       { VA_FOURCC('I','A','4','4'), VA_MSB_FIRST, 8, },
154       COMMON_SUBPICTURE_FLAGS },
155     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_A4P4_UNORM,
156       { VA_FOURCC('A','I','4','4'), VA_MSB_FIRST, 8, },
157       COMMON_SUBPICTURE_FLAGS },
158     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_P8A8_UNORM,
159       { VA_FOURCC('I','A','8','8'), VA_MSB_FIRST, 16, },
160       COMMON_SUBPICTURE_FLAGS },
161     { I965_SURFACETYPE_INDEXED, I965_SURFACEFORMAT_A8P8_UNORM,
162       { VA_FOURCC('A','I','8','8'), VA_MSB_FIRST, 16, },
163       COMMON_SUBPICTURE_FLAGS },
164      { I965_SURFACETYPE_RGBA, I965_SURFACEFORMAT_B8G8R8A8_UNORM,
165       { VA_FOURCC('B','G','R','A'), VA_LSB_FIRST, 32,
166         32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 },
167       COMMON_SUBPICTURE_FLAGS },
168     { I965_SURFACETYPE_RGBA, I965_SURFACEFORMAT_R8G8B8A8_UNORM,
169       { VA_FOURCC('R','G','B','A'), VA_LSB_FIRST, 32,
170         32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 },
171       COMMON_SUBPICTURE_FLAGS },
172 };
173
174 static const i965_subpic_format_map_t *
175 get_subpic_format(const VAImageFormat *va_format)
176 {
177     unsigned int i;
178     for (i = 0; i965_subpic_formats_map[i].type != 0; i++) {
179         const i965_subpic_format_map_t * const m = &i965_subpic_formats_map[i];
180         if (m->va_format.fourcc == va_format->fourcc &&
181             (m->type == I965_SURFACETYPE_RGBA ?
182              (m->va_format.byte_order == va_format->byte_order &&
183               m->va_format.red_mask   == va_format->red_mask   &&
184               m->va_format.green_mask == va_format->green_mask &&
185               m->va_format.blue_mask  == va_format->blue_mask  &&
186               m->va_format.alpha_mask == va_format->alpha_mask) : 1))
187             return m;
188     }
189     return NULL;
190 }
191
192 extern struct hw_context *i965_proc_context_init(VADriverContextP, struct object_config *);
193 extern struct hw_context *g4x_dec_hw_context_init(VADriverContextP, struct object_config *);
194 static struct hw_codec_info g4x_hw_codec_info = {
195     .dec_hw_context_init = g4x_dec_hw_context_init,
196     .enc_hw_context_init = NULL,
197     .proc_hw_context_init = NULL,
198     .max_width = 2048,
199     .max_height = 2048,
200
201     .has_mpeg2_decoding = 1,
202 };
203
204 extern struct hw_context *ironlake_dec_hw_context_init(VADriverContextP, struct object_config *);
205 static struct hw_codec_info ironlake_hw_codec_info = {
206     .dec_hw_context_init = ironlake_dec_hw_context_init,
207     .enc_hw_context_init = NULL,
208     .proc_hw_context_init = i965_proc_context_init,
209     .max_width = 2048,
210     .max_height = 2048,
211
212     .has_mpeg2_decoding = 1,
213     .has_h264_decoding = 1,
214     .has_vpp = 1,
215     .has_accelerated_putimage = 1,
216 };
217
218 extern struct hw_context *gen6_dec_hw_context_init(VADriverContextP, struct object_config *);
219 extern struct hw_context *gen6_enc_hw_context_init(VADriverContextP, struct object_config *);
220 static struct hw_codec_info gen6_hw_codec_info = {
221     .dec_hw_context_init = gen6_dec_hw_context_init,
222     .enc_hw_context_init = gen6_enc_hw_context_init,
223     .proc_hw_context_init = i965_proc_context_init,
224     .max_width = 2048,
225     .max_height = 2048,
226
227     .has_mpeg2_decoding = 1,
228     .has_h264_decoding = 1,
229     .has_h264_encoding = 1,
230     .has_vc1_decoding = 1,
231     .has_vpp = 1,
232     .has_accelerated_getimage = 1,
233     .has_accelerated_putimage = 1,
234     .has_tiled_surface = 1,
235 };
236
237 extern struct hw_context *gen7_dec_hw_context_init(VADriverContextP, struct object_config *);
238 extern struct hw_context *gen7_enc_hw_context_init(VADriverContextP, struct object_config *);
239 static struct hw_codec_info gen7_hw_codec_info = {
240     .dec_hw_context_init = gen7_dec_hw_context_init,
241     .enc_hw_context_init = gen7_enc_hw_context_init,
242     .proc_hw_context_init = i965_proc_context_init,
243     .max_width = 4096,
244     .max_height = 4096,
245
246     .has_mpeg2_decoding = 1,
247     .has_h264_decoding = 1,
248     .has_h264_encoding = 1,
249     .has_vc1_decoding = 1,
250     .has_jpeg_decoding = 1,
251     .has_vpp = 1,
252     .has_accelerated_getimage = 1,
253     .has_accelerated_putimage = 1,
254     .has_tiled_surface = 1,
255 };
256
257 extern struct hw_context *gen75_proc_context_init(VADriverContextP, struct object_config *);
258 static struct hw_codec_info gen75_hw_codec_info = {
259     .dec_hw_context_init = gen75_dec_hw_context_init,
260     .enc_hw_context_init = gen75_enc_hw_context_init,
261     .proc_hw_context_init = gen75_proc_context_init,
262     .max_width = 4096,
263     .max_height = 4096,
264
265     .has_mpeg2_decoding = 1,
266     .has_mpeg2_encoding = 1,
267     .has_h264_decoding = 1,
268     .has_h264_encoding = 1,
269     .has_vc1_decoding = 1,
270     .has_jpeg_decoding = 1,
271     .has_vpp = 1,
272     .has_accelerated_getimage = 1,
273     .has_accelerated_putimage = 1,
274     .has_tiled_surface = 1,
275 };
276
277 #define I965_PACKED_HEADER_BASE         0
278 #define I965_PACKED_MISC_HEADER_BASE    3
279
280 int
281 va_enc_packed_type_to_idx(int packed_type)
282 {
283     int idx = 0;
284
285     if (packed_type & VAEncPackedHeaderMiscMask) {
286         idx = I965_PACKED_MISC_HEADER_BASE;
287         packed_type = (~VAEncPackedHeaderMiscMask & packed_type);
288         assert(packed_type > 0);
289         idx += (packed_type - 1);
290     } else {
291         idx = I965_PACKED_HEADER_BASE;
292
293         switch (packed_type) {
294         case VAEncPackedHeaderSequence:
295             idx = I965_PACKED_HEADER_BASE + 0;
296             break;
297
298         case VAEncPackedHeaderPicture:
299             idx = I965_PACKED_HEADER_BASE + 1;
300             break;
301
302         case VAEncPackedHeaderSlice:
303             idx = I965_PACKED_HEADER_BASE + 2;
304             break;
305
306         default:
307             /* Should not get here */
308             assert(0);
309             break;
310         }
311     }
312
313     assert(idx < 4);
314     return idx;
315 }
316
317
318 VAStatus 
319 i965_QueryConfigProfiles(VADriverContextP ctx,
320                          VAProfile *profile_list,       /* out */
321                          int *num_profiles)             /* out */
322 {
323     struct i965_driver_data * const i965 = i965_driver_data(ctx);
324     int i = 0;
325
326     if (HAS_MPEG2_DECODING(i965) ||
327         HAS_MPEG2_ENCODING(i965)) {
328         profile_list[i++] = VAProfileMPEG2Simple;
329         profile_list[i++] = VAProfileMPEG2Main;
330     }
331
332     if (HAS_H264_DECODING(i965) ||
333         HAS_H264_ENCODING(i965)) {
334         profile_list[i++] = VAProfileH264Baseline;
335         profile_list[i++] = VAProfileH264Main;
336         profile_list[i++] = VAProfileH264High;
337     }
338
339     if (HAS_VC1_DECODING(i965)) {
340         profile_list[i++] = VAProfileVC1Simple;
341         profile_list[i++] = VAProfileVC1Main;
342         profile_list[i++] = VAProfileVC1Advanced;
343     }
344
345     if (HAS_VPP(i965)) {
346         profile_list[i++] = VAProfileNone;
347     }
348
349     if (HAS_JPEG_DECODING(i965)) {
350         profile_list[i++] = VAProfileJPEGBaseline;
351     }
352
353     /* If the assert fails then I965_MAX_PROFILES needs to be bigger */
354     assert(i <= I965_MAX_PROFILES);
355     *num_profiles = i;
356
357     return VA_STATUS_SUCCESS;
358 }
359
360 VAStatus 
361 i965_QueryConfigEntrypoints(VADriverContextP ctx,
362                             VAProfile profile,
363                             VAEntrypoint *entrypoint_list,      /* out */
364                             int *num_entrypoints)               /* out */
365 {
366     struct i965_driver_data * const i965 = i965_driver_data(ctx);
367     int n = 0;
368
369     switch (profile) {
370     case VAProfileMPEG2Simple:
371     case VAProfileMPEG2Main:
372         if (HAS_MPEG2_DECODING(i965))
373             entrypoint_list[n++] = VAEntrypointVLD;
374
375         if (HAS_MPEG2_ENCODING(i965))
376             entrypoint_list[n++] = VAEntrypointEncSlice;
377
378         break;
379
380     case VAProfileH264Baseline:
381     case VAProfileH264Main:
382     case VAProfileH264High:
383         if (HAS_H264_DECODING(i965))
384             entrypoint_list[n++] = VAEntrypointVLD;
385         
386         if (HAS_H264_ENCODING(i965))
387             entrypoint_list[n++] = VAEntrypointEncSlice;
388
389         break;
390
391     case VAProfileVC1Simple:
392     case VAProfileVC1Main:
393     case VAProfileVC1Advanced:
394         if (HAS_VC1_DECODING(i965))
395             entrypoint_list[n++] = VAEntrypointVLD;
396         break;
397
398     case VAProfileNone:
399         if (HAS_VPP(i965))
400             entrypoint_list[n++] = VAEntrypointVideoProc;
401         break;
402
403     case VAProfileJPEGBaseline:
404         if (HAS_JPEG_DECODING(i965))
405             entrypoint_list[n++] = VAEntrypointVLD;
406         break;
407
408     default:
409         break;
410     }
411
412     /* If the assert fails then I965_MAX_ENTRYPOINTS needs to be bigger */
413     assert(n <= I965_MAX_ENTRYPOINTS);
414     *num_entrypoints = n;
415     return n > 0 ? VA_STATUS_SUCCESS : VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
416 }
417
418 VAStatus 
419 i965_GetConfigAttributes(VADriverContextP ctx,
420                          VAProfile profile,
421                          VAEntrypoint entrypoint,
422                          VAConfigAttrib *attrib_list,  /* in/out */
423                          int num_attribs)
424 {
425     int i;
426
427     /* Other attributes don't seem to be defined */
428     /* What to do if we don't know the attribute? */
429     for (i = 0; i < num_attribs; i++) {
430         switch (attrib_list[i].type) {
431         case VAConfigAttribRTFormat:
432             attrib_list[i].value = VA_RT_FORMAT_YUV420;
433             break;
434
435         case VAConfigAttribRateControl:
436             if (entrypoint == VAEntrypointEncSlice) {
437                 attrib_list[i].value = VA_RC_CBR | VA_RC_CQP;
438                 break;
439             }
440
441         case VAConfigAttribEncPackedHeaders:
442             if (entrypoint == VAEntrypointEncSlice) {
443                 attrib_list[i].value = VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_MISC;
444                 break;
445             }
446
447         default:
448             /* Do nothing */
449             attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED;
450             break;
451         }
452     }
453
454     return VA_STATUS_SUCCESS;
455 }
456
457 static void 
458 i965_destroy_config(struct object_heap *heap, struct object_base *obj)
459 {
460     object_heap_free(heap, obj);
461 }
462
463 static VAStatus 
464 i965_update_attribute(struct object_config *obj_config, VAConfigAttrib *attrib)
465 {
466     int i;
467
468     /* Check existing attrbiutes */
469     for (i = 0; i < obj_config->num_attribs; i++) {
470         if (obj_config->attrib_list[i].type == attrib->type) {
471             /* Update existing attribute */
472             obj_config->attrib_list[i].value = attrib->value;
473             return VA_STATUS_SUCCESS;
474         }
475     }
476
477     if (obj_config->num_attribs < I965_MAX_CONFIG_ATTRIBUTES) {
478         i = obj_config->num_attribs;
479         obj_config->attrib_list[i].type = attrib->type;
480         obj_config->attrib_list[i].value = attrib->value;
481         obj_config->num_attribs++;
482         return VA_STATUS_SUCCESS;
483     }
484
485     return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
486 }
487
488 VAStatus 
489 i965_CreateConfig(VADriverContextP ctx,
490                   VAProfile profile,
491                   VAEntrypoint entrypoint,
492                   VAConfigAttrib *attrib_list,
493                   int num_attribs,
494                   VAConfigID *config_id)        /* out */
495 {
496     struct i965_driver_data * const i965 = i965_driver_data(ctx);
497     struct object_config *obj_config;
498     int configID;
499     int i;
500     VAStatus vaStatus;
501
502     /* Validate profile & entrypoint */
503     switch (profile) {
504     case VAProfileMPEG2Simple:
505     case VAProfileMPEG2Main:
506         if ((HAS_MPEG2_DECODING(i965) && VAEntrypointVLD == entrypoint) ||
507             (HAS_MPEG2_ENCODING(i965) && VAEntrypointEncSlice == entrypoint)) {
508             vaStatus = VA_STATUS_SUCCESS;
509         } else {
510             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
511         }
512         break;
513
514     case VAProfileH264Baseline:
515     case VAProfileH264Main:
516     case VAProfileH264High:
517         if ((HAS_H264_DECODING(i965) && VAEntrypointVLD == entrypoint) ||
518             (HAS_H264_ENCODING(i965) && VAEntrypointEncSlice == entrypoint)) {
519             vaStatus = VA_STATUS_SUCCESS;
520         } else {
521             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
522         }
523
524         break;
525
526     case VAProfileVC1Simple:
527     case VAProfileVC1Main:
528     case VAProfileVC1Advanced:
529         if (HAS_VC1_DECODING(i965) && VAEntrypointVLD == entrypoint) {
530             vaStatus = VA_STATUS_SUCCESS;
531         } else {
532             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
533         }
534
535         break;
536
537     case VAProfileNone:
538         if (HAS_VPP(i965) && VAEntrypointVideoProc == entrypoint) {
539             vaStatus = VA_STATUS_SUCCESS;
540         } else {
541             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
542         }
543
544         break;
545
546     case VAProfileJPEGBaseline:
547         if (HAS_JPEG_DECODING(i965) && VAEntrypointVLD == entrypoint) {
548             vaStatus = VA_STATUS_SUCCESS;
549         } else {
550             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT;
551         }
552
553         break;
554
555     default:
556         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
557         break;
558     }
559
560     if (VA_STATUS_SUCCESS != vaStatus) {
561         return vaStatus;
562     }
563
564     configID = NEW_CONFIG_ID();
565     obj_config = CONFIG(configID);
566
567     if (NULL == obj_config) {
568         vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
569         return vaStatus;
570     }
571
572     obj_config->profile = profile;
573     obj_config->entrypoint = entrypoint;
574     obj_config->attrib_list[0].type = VAConfigAttribRTFormat;
575     obj_config->attrib_list[0].value = VA_RT_FORMAT_YUV420;
576     obj_config->num_attribs = 1;
577
578     for(i = 0; i < num_attribs; i++) {
579         vaStatus = i965_update_attribute(obj_config, &(attrib_list[i]));
580
581         if (VA_STATUS_SUCCESS != vaStatus) {
582             break;
583         }
584     }
585
586     /* Error recovery */
587     if (VA_STATUS_SUCCESS != vaStatus) {
588         i965_destroy_config(&i965->config_heap, (struct object_base *)obj_config);
589     } else {
590         *config_id = configID;
591     }
592
593     return vaStatus;
594 }
595
596 VAStatus 
597 i965_DestroyConfig(VADriverContextP ctx, VAConfigID config_id)
598 {
599     struct i965_driver_data *i965 = i965_driver_data(ctx);
600     struct object_config *obj_config = CONFIG(config_id);
601     VAStatus vaStatus;
602
603     if (NULL == obj_config) {
604         vaStatus = VA_STATUS_ERROR_INVALID_CONFIG;
605         return vaStatus;
606     }
607
608     i965_destroy_config(&i965->config_heap, (struct object_base *)obj_config);
609     return VA_STATUS_SUCCESS;
610 }
611
612 VAStatus i965_QueryConfigAttributes(VADriverContextP ctx,
613                                     VAConfigID config_id,
614                                     VAProfile *profile,                 /* out */
615                                     VAEntrypoint *entrypoint,           /* out */
616                                     VAConfigAttrib *attrib_list,        /* out */
617                                     int *num_attribs)                   /* out */
618 {
619     struct i965_driver_data *i965 = i965_driver_data(ctx);
620     struct object_config *obj_config = CONFIG(config_id);
621     VAStatus vaStatus = VA_STATUS_SUCCESS;
622     int i;
623
624     assert(obj_config);
625     *profile = obj_config->profile;
626     *entrypoint = obj_config->entrypoint;
627     *num_attribs = obj_config->num_attribs;
628
629     for(i = 0; i < obj_config->num_attribs; i++) {
630         attrib_list[i] = obj_config->attrib_list[i];
631     }
632
633     return vaStatus;
634 }
635
636 static void 
637 i965_destroy_surface(struct object_heap *heap, struct object_base *obj)
638 {
639     struct object_surface *obj_surface = (struct object_surface *)obj;
640
641     dri_bo_unreference(obj_surface->bo);
642     obj_surface->bo = NULL;
643
644     if (obj_surface->free_private_data != NULL) {
645         obj_surface->free_private_data(&obj_surface->private_data);
646         obj_surface->private_data = NULL;
647     }
648
649     object_heap_free(heap, obj);
650 }
651
652 static VAStatus
653 i965_CreateSurfaces2(
654     VADriverContextP    ctx,
655     unsigned int        format,
656     unsigned int        width,
657     unsigned int        height,
658     VASurfaceID        *surfaces,
659     unsigned int        num_surfaces,
660     VASurfaceAttrib    *attrib_list,
661     unsigned int        num_attribs
662     )
663 {
664     struct i965_driver_data *i965 = i965_driver_data(ctx);
665     int i,j;
666     VAStatus vaStatus = VA_STATUS_SUCCESS;
667     int expected_fourcc = 0;
668
669     for (i = 0; i < num_attribs && attrib_list; i++) {
670         if ((attrib_list[i].type == VASurfaceAttribPixelFormat) &&
671             (attrib_list[i].flags & VA_SURFACE_ATTRIB_SETTABLE)) {
672             assert(attrib_list[i].value.type == VAGenericValueTypeInteger);
673             expected_fourcc = attrib_list[i].value.value.i;
674             break;
675         }
676     }
677
678     /* support 420 & 422 & RGB32 format, 422 and RGB32 are only used
679      * for post-processing (including color conversion) */
680     if (VA_RT_FORMAT_YUV420 != format &&
681         VA_RT_FORMAT_YUV422 != format &&
682         VA_RT_FORMAT_RGB32  != format) {
683         return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT;
684     }
685
686     for (i = 0; i < num_surfaces; i++) {
687         int surfaceID = NEW_SURFACE_ID();
688         struct object_surface *obj_surface = SURFACE(surfaceID);
689
690         if (NULL == obj_surface) {
691             vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
692             break;
693         }
694
695         surfaces[i] = surfaceID;
696         obj_surface->status = VASurfaceReady;
697         obj_surface->orig_width = width;
698         obj_surface->orig_height = height;
699
700         obj_surface->subpic_render_idx = 0;
701         for(j = 0; j < I965_MAX_SUBPIC_SUM; j++){
702            obj_surface->subpic[j] = VA_INVALID_ID;
703         }
704
705         obj_surface->width = ALIGN(width, 16);
706         obj_surface->height = ALIGN(height, 16);
707         obj_surface->flags = SURFACE_REFERENCED;
708         obj_surface->fourcc = 0;
709         obj_surface->bo = NULL;
710         obj_surface->locked_image_id = VA_INVALID_ID;
711         obj_surface->private_data = NULL;
712         obj_surface->free_private_data = NULL;
713         obj_surface->subsampling = SUBSAMPLE_YUV420;
714
715         if (expected_fourcc) {
716             int tiling = HAS_TILED_SURFACE(i965);
717
718             if (expected_fourcc != VA_FOURCC('N', 'V', '1', '2') &&
719                 expected_fourcc != VA_FOURCC('R', 'G', 'B', 'X') &&
720                 expected_fourcc != VA_FOURCC('R', 'G', 'B', 'A') )
721                 tiling = 0;
722             // todo, should we disable tiling for 422 format?
723                         
724             if (VA_RT_FORMAT_YUV420 == format) {
725                 obj_surface->subsampling = SUBSAMPLE_YUV420;
726             }
727             else if (VA_RT_FORMAT_YUV422 == format) {
728                 obj_surface->subsampling = SUBSAMPLE_YUV422H;
729             }
730             else if (VA_RT_FORMAT_RGB32 == format) {
731                 obj_surface->subsampling = SUBSAMPLE_RGBX;
732             }
733              else {
734                 assert(0);
735             }
736
737             i965_check_alloc_surface_bo(ctx, obj_surface, tiling, expected_fourcc, obj_surface->subsampling);
738         }
739     }
740
741     /* Error recovery */
742     if (VA_STATUS_SUCCESS != vaStatus) {
743         /* surfaces[i-1] was the last successful allocation */
744         for (; i--; ) {
745             struct object_surface *obj_surface = SURFACE(surfaces[i]);
746
747             surfaces[i] = VA_INVALID_SURFACE;
748             assert(obj_surface);
749             i965_destroy_surface(&i965->surface_heap, (struct object_base *)obj_surface);
750         }
751     }
752
753     return vaStatus;
754 }
755
756 VAStatus 
757 i965_CreateSurfaces(VADriverContextP ctx,
758                     int width,
759                     int height,
760                     int format,
761                     int num_surfaces,
762                     VASurfaceID *surfaces)      /* out */
763 {
764     return i965_CreateSurfaces2(ctx,
765                                 format,
766                                 width,
767                                 height,
768                                 surfaces,
769                                 num_surfaces,
770                                 NULL,
771                                 0);
772 }
773
774 VAStatus 
775 i965_DestroySurfaces(VADriverContextP ctx,
776                      VASurfaceID *surface_list,
777                      int num_surfaces)
778 {
779     struct i965_driver_data *i965 = i965_driver_data(ctx);
780     int i;
781
782     for (i = num_surfaces; i--; ) {
783         struct object_surface *obj_surface = SURFACE(surface_list[i]);
784
785         assert(obj_surface);
786         i965_destroy_surface(&i965->surface_heap, (struct object_base *)obj_surface);
787     }
788
789     return VA_STATUS_SUCCESS;
790 }
791
792 VAStatus 
793 i965_QueryImageFormats(VADriverContextP ctx,
794                        VAImageFormat *format_list,      /* out */
795                        int *num_formats)                /* out */
796 {
797     int n;
798
799     for (n = 0; i965_image_formats_map[n].va_format.fourcc != 0; n++) {
800         const i965_image_format_map_t * const m = &i965_image_formats_map[n];
801         if (format_list)
802             format_list[n] = m->va_format;
803     }
804
805     if (num_formats)
806         *num_formats = n;
807
808     return VA_STATUS_SUCCESS;
809 }
810
811 /*
812  * Guess the format when the usage of a VA surface is unknown
813  * 1. Without a valid context: YV12
814  * 2. The current context is valid:
815  *    a) always NV12 on GEN6 and later
816  *    b) I420 for MPEG-2 and NV12 for other codec on GEN4 & GEN5
817  */
818 static void
819 i965_guess_surface_format(VADriverContextP ctx,
820                           VASurfaceID surface,
821                           unsigned int *fourcc,
822                           unsigned int *is_tiled)
823 {
824     struct i965_driver_data *i965 = i965_driver_data(ctx);
825     struct object_context *obj_context = NULL;
826     struct object_config *obj_config = NULL;
827
828     *fourcc = VA_FOURCC('Y', 'V', '1', '2');
829     *is_tiled = 0;
830
831     if (i965->current_context_id == VA_INVALID_ID)
832         return;
833
834     obj_context = CONTEXT(i965->current_context_id);
835
836     if (!obj_context || obj_context->config_id == VA_INVALID_ID)
837         return;
838
839     obj_config = CONFIG(obj_context->config_id);
840
841     if (!obj_config)
842         return;
843
844     if (IS_GEN6(i965->intel.device_id) || IS_GEN7(i965->intel.device_id)) {
845         *fourcc = VA_FOURCC('N', 'V', '1', '2');
846         *is_tiled = 1;
847         return;
848     }
849
850     switch (obj_config->profile) {
851     case VAProfileMPEG2Simple:
852     case VAProfileMPEG2Main:
853         *fourcc = VA_FOURCC('I', '4', '2', '0');
854         *is_tiled = 0;
855         break;
856
857     default:
858         *fourcc = VA_FOURCC('N', 'V', '1', '2');
859         *is_tiled = 0;
860         break;
861     }
862 }
863
864 VAStatus 
865 i965_QuerySubpictureFormats(VADriverContextP ctx,
866                             VAImageFormat *format_list,         /* out */
867                             unsigned int *flags,                /* out */
868                             unsigned int *num_formats)          /* out */
869 {
870     int n;
871
872     for (n = 0; i965_subpic_formats_map[n].va_format.fourcc != 0; n++) {
873         const i965_subpic_format_map_t * const m = &i965_subpic_formats_map[n];
874         if (format_list)
875             format_list[n] = m->va_format;
876         if (flags)
877             flags[n] = m->va_flags;
878     }
879
880     if (num_formats)
881         *num_formats = n;
882
883     return VA_STATUS_SUCCESS;
884 }
885
886 static void 
887 i965_destroy_subpic(struct object_heap *heap, struct object_base *obj)
888 {
889     //    struct object_subpic *obj_subpic = (struct object_subpic *)obj;
890
891     object_heap_free(heap, obj);
892 }
893
894 VAStatus 
895 i965_CreateSubpicture(VADriverContextP ctx,
896                       VAImageID image,
897                       VASubpictureID *subpicture)         /* out */
898 {
899     struct i965_driver_data *i965 = i965_driver_data(ctx);
900     VASubpictureID subpicID = NEW_SUBPIC_ID()
901     struct object_subpic *obj_subpic = SUBPIC(subpicID);
902
903     if (!obj_subpic)
904         return VA_STATUS_ERROR_ALLOCATION_FAILED;
905
906     struct object_image *obj_image = IMAGE(image);
907     if (!obj_image)
908         return VA_STATUS_ERROR_INVALID_IMAGE;
909
910     const i965_subpic_format_map_t * const m = get_subpic_format(&obj_image->image.format);
911     if (!m)
912         return VA_STATUS_ERROR_UNKNOWN; /* XXX: VA_STATUS_ERROR_UNSUPPORTED_FORMAT? */
913
914     *subpicture = subpicID;
915     obj_subpic->image  = image;
916     obj_subpic->format = m->format;
917     obj_subpic->width  = obj_image->image.width;
918     obj_subpic->height = obj_image->image.height;
919     obj_subpic->pitch  = obj_image->image.pitches[0];
920     obj_subpic->bo     = obj_image->bo;
921     obj_subpic->global_alpha = 1.0;
922  
923     return VA_STATUS_SUCCESS;
924 }
925
926 VAStatus 
927 i965_DestroySubpicture(VADriverContextP ctx,
928                        VASubpictureID subpicture)
929 {
930     struct i965_driver_data *i965 = i965_driver_data(ctx);
931     struct object_subpic *obj_subpic = SUBPIC(subpicture);
932     i965_destroy_subpic(&i965->subpic_heap, (struct object_base *)obj_subpic);
933     return VA_STATUS_SUCCESS;
934 }
935
936 VAStatus 
937 i965_SetSubpictureImage(VADriverContextP ctx,
938                         VASubpictureID subpicture,
939                         VAImageID image)
940 {
941     /* TODO */
942     return VA_STATUS_ERROR_UNIMPLEMENTED;
943 }
944
945 VAStatus 
946 i965_SetSubpictureChromakey(VADriverContextP ctx,
947                             VASubpictureID subpicture,
948                             unsigned int chromakey_min,
949                             unsigned int chromakey_max,
950                             unsigned int chromakey_mask)
951 {
952     /* TODO */
953     return VA_STATUS_ERROR_UNIMPLEMENTED;
954 }
955
956 VAStatus 
957 i965_SetSubpictureGlobalAlpha(VADriverContextP ctx,
958                               VASubpictureID subpicture,
959                               float global_alpha)
960 {
961     struct i965_driver_data *i965 = i965_driver_data(ctx);
962     struct object_subpic *obj_subpic = SUBPIC(subpicture);
963
964     if(global_alpha > 1.0 || global_alpha < 0.0){
965        return VA_STATUS_ERROR_INVALID_PARAMETER;
966     }
967     obj_subpic->global_alpha  = global_alpha;
968
969     return VA_STATUS_SUCCESS;
970 }
971
972 VAStatus 
973 i965_AssociateSubpicture(VADriverContextP ctx,
974                          VASubpictureID subpicture,
975                          VASurfaceID *target_surfaces,
976                          int num_surfaces,
977                          short src_x, /* upper left offset in subpicture */
978                          short src_y,
979                          unsigned short src_width,
980                          unsigned short src_height,
981                          short dest_x, /* upper left offset in surface */
982                          short dest_y,
983                          unsigned short dest_width,
984                          unsigned short dest_height,
985                          /*
986                           * whether to enable chroma-keying or global-alpha
987                           * see VA_SUBPICTURE_XXX values
988                           */
989                          unsigned int flags)
990 {
991     struct i965_driver_data *i965 = i965_driver_data(ctx);
992     struct object_subpic *obj_subpic = SUBPIC(subpicture);
993     int i, j;
994
995     obj_subpic->src_rect.x      = src_x;
996     obj_subpic->src_rect.y      = src_y;
997     obj_subpic->src_rect.width  = src_width;
998     obj_subpic->src_rect.height = src_height;
999     obj_subpic->dst_rect.x      = dest_x;
1000     obj_subpic->dst_rect.y      = dest_y;
1001     obj_subpic->dst_rect.width  = dest_width;
1002     obj_subpic->dst_rect.height = dest_height;
1003     obj_subpic->flags           = flags;
1004
1005     for (i = 0; i < num_surfaces; i++) {
1006         struct object_surface *obj_surface = SURFACE(target_surfaces[i]);
1007         if (!obj_surface)
1008             return VA_STATUS_ERROR_INVALID_SURFACE;
1009
1010         for(j = 0; j < I965_MAX_SUBPIC_SUM; j ++){
1011             if(obj_surface->subpic[j] == VA_INVALID_ID){
1012                obj_surface->subpic[j] = subpicture;
1013                break;
1014             }
1015         }
1016         
1017         if(j == I965_MAX_SUBPIC_SUM){
1018             return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
1019         }
1020
1021     }
1022     return VA_STATUS_SUCCESS;
1023 }
1024
1025
1026 VAStatus 
1027 i965_DeassociateSubpicture(VADriverContextP ctx,
1028                            VASubpictureID subpicture,
1029                            VASurfaceID *target_surfaces,
1030                            int num_surfaces)
1031 {
1032     struct i965_driver_data *i965 = i965_driver_data(ctx);
1033     int i, j;
1034
1035     for (i = 0; i < num_surfaces; i++) {
1036         struct object_surface *obj_surface = SURFACE(target_surfaces[i]);
1037         if (!obj_surface)
1038             return VA_STATUS_ERROR_INVALID_SURFACE;
1039
1040         for(j = 0; j < I965_MAX_SUBPIC_SUM; j ++){
1041             if(obj_surface->subpic[j] == subpicture){
1042                obj_surface->subpic[j] = VA_INVALID_ID;
1043                break;
1044             }
1045         }
1046         
1047         if(j == I965_MAX_SUBPIC_SUM){
1048             return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
1049         }
1050     }
1051     return VA_STATUS_SUCCESS;
1052 }
1053
1054 void
1055 i965_reference_buffer_store(struct buffer_store **ptr, 
1056                             struct buffer_store *buffer_store)
1057 {
1058     assert(*ptr == NULL);
1059
1060     if (buffer_store) {
1061         buffer_store->ref_count++;
1062         *ptr = buffer_store;
1063     }
1064 }
1065
1066 void 
1067 i965_release_buffer_store(struct buffer_store **ptr)
1068 {
1069     struct buffer_store *buffer_store = *ptr;
1070
1071     if (buffer_store == NULL)
1072         return;
1073
1074     assert(buffer_store->bo || buffer_store->buffer);
1075     assert(!(buffer_store->bo && buffer_store->buffer));
1076     buffer_store->ref_count--;
1077     
1078     if (buffer_store->ref_count == 0) {
1079         dri_bo_unreference(buffer_store->bo);
1080         free(buffer_store->buffer);
1081         buffer_store->bo = NULL;
1082         buffer_store->buffer = NULL;
1083         free(buffer_store);
1084     }
1085
1086     *ptr = NULL;
1087 }
1088
1089 static void 
1090 i965_destroy_context(struct object_heap *heap, struct object_base *obj)
1091 {
1092     struct object_context *obj_context = (struct object_context *)obj;
1093     int i;
1094
1095     if (obj_context->hw_context) {
1096         obj_context->hw_context->destroy(obj_context->hw_context);
1097         obj_context->hw_context = NULL;
1098     }
1099
1100     if (obj_context->codec_type == CODEC_PROC) {
1101         i965_release_buffer_store(&obj_context->codec_state.proc.pipeline_param);
1102
1103     } else if (obj_context->codec_type == CODEC_ENC) {
1104         assert(obj_context->codec_state.encode.num_slice_params <= obj_context->codec_state.encode.max_slice_params);
1105         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param);
1106         i965_release_buffer_store(&obj_context->codec_state.encode.seq_param);
1107
1108         for (i = 0; i < obj_context->codec_state.encode.num_slice_params; i++)
1109             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params[i]);
1110
1111         free(obj_context->codec_state.encode.slice_params);
1112
1113         assert(obj_context->codec_state.encode.num_slice_params_ext <= obj_context->codec_state.encode.max_slice_params_ext);
1114         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param_ext);
1115         i965_release_buffer_store(&obj_context->codec_state.encode.seq_param_ext);
1116
1117         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_param); i++)
1118             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_param[i]);
1119
1120         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_data); i++)
1121             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data[i]);
1122
1123         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.misc_param); i++)
1124             i965_release_buffer_store(&obj_context->codec_state.encode.misc_param[i]);
1125
1126         for (i = 0; i < obj_context->codec_state.encode.num_slice_params_ext; i++)
1127             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params_ext[i]);
1128
1129         free(obj_context->codec_state.encode.slice_params_ext);
1130     } else {
1131         assert(obj_context->codec_state.decode.num_slice_params <= obj_context->codec_state.decode.max_slice_params);
1132         assert(obj_context->codec_state.decode.num_slice_datas <= obj_context->codec_state.decode.max_slice_datas);
1133
1134         i965_release_buffer_store(&obj_context->codec_state.decode.pic_param);
1135         i965_release_buffer_store(&obj_context->codec_state.decode.iq_matrix);
1136         i965_release_buffer_store(&obj_context->codec_state.decode.bit_plane);
1137
1138         for (i = 0; i < obj_context->codec_state.decode.num_slice_params; i++)
1139             i965_release_buffer_store(&obj_context->codec_state.decode.slice_params[i]);
1140
1141         for (i = 0; i < obj_context->codec_state.decode.num_slice_datas; i++)
1142             i965_release_buffer_store(&obj_context->codec_state.decode.slice_datas[i]);
1143
1144         free(obj_context->codec_state.decode.slice_params);
1145         free(obj_context->codec_state.decode.slice_datas);
1146     }
1147
1148     free(obj_context->render_targets);
1149     object_heap_free(heap, obj);
1150 }
1151
1152 VAStatus
1153 i965_CreateContext(VADriverContextP ctx,
1154                    VAConfigID config_id,
1155                    int picture_width,
1156                    int picture_height,
1157                    int flag,
1158                    VASurfaceID *render_targets,
1159                    int num_render_targets,
1160                    VAContextID *context)                /* out */
1161 {
1162     struct i965_driver_data *i965 = i965_driver_data(ctx);
1163     struct i965_render_state *render_state = &i965->render_state;
1164     struct object_config *obj_config = CONFIG(config_id);
1165     struct object_context *obj_context = NULL;
1166     VAStatus vaStatus = VA_STATUS_SUCCESS;
1167     int contextID;
1168     int i;
1169
1170     if (NULL == obj_config) {
1171         vaStatus = VA_STATUS_ERROR_INVALID_CONFIG;
1172         return vaStatus;
1173     }
1174
1175     if (picture_width > i965->codec_info->max_width ||
1176         picture_height > i965->codec_info->max_height) {
1177         vaStatus = VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED;
1178         return vaStatus;
1179     }
1180
1181     /* Validate flag */
1182     /* Validate picture dimensions */
1183     contextID = NEW_CONTEXT_ID();
1184     obj_context = CONTEXT(contextID);
1185
1186     if (NULL == obj_context) {
1187         vaStatus = VA_STATUS_ERROR_ALLOCATION_FAILED;
1188         return vaStatus;
1189     }
1190
1191     render_state->inited = 1;
1192
1193     switch (obj_config->profile) {
1194     case VAProfileH264Baseline:
1195     case VAProfileH264Main:
1196     case VAProfileH264High:
1197         if (!HAS_H264_DECODING(i965) &&
1198             !HAS_H264_ENCODING(i965))
1199             return VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1200         render_state->interleaved_uv = 1;
1201         break;
1202     default:
1203         render_state->interleaved_uv = !!(IS_GEN6(i965->intel.device_id) || IS_GEN7(i965->intel.device_id));
1204         break;
1205     }
1206
1207     *context = contextID;
1208     obj_context->flags = flag;
1209     obj_context->context_id = contextID;
1210     obj_context->config_id = config_id;
1211     obj_context->picture_width = picture_width;
1212     obj_context->picture_height = picture_height;
1213     obj_context->num_render_targets = num_render_targets;
1214     obj_context->render_targets = 
1215         (VASurfaceID *)calloc(num_render_targets, sizeof(VASurfaceID));
1216     obj_context->hw_context = NULL;
1217
1218     for(i = 0; i < num_render_targets; i++) {
1219         if (NULL == SURFACE(render_targets[i])) {
1220             vaStatus = VA_STATUS_ERROR_INVALID_SURFACE;
1221             break;
1222         }
1223
1224         obj_context->render_targets[i] = render_targets[i];
1225     }
1226
1227     if (VA_STATUS_SUCCESS == vaStatus) {
1228         if (VAEntrypointVideoProc == obj_config->entrypoint) {
1229             obj_context->codec_type = CODEC_PROC;
1230             memset(&obj_context->codec_state.proc, 0, sizeof(obj_context->codec_state.proc));
1231             obj_context->codec_state.proc.current_render_target = VA_INVALID_ID;
1232             assert(i965->codec_info->proc_hw_context_init);
1233             obj_context->hw_context = i965->codec_info->proc_hw_context_init(ctx, obj_config);
1234         } else if (VAEntrypointEncSlice == obj_config->entrypoint) { /*encode routin only*/
1235             obj_context->codec_type = CODEC_ENC;
1236             memset(&obj_context->codec_state.encode, 0, sizeof(obj_context->codec_state.encode));
1237             obj_context->codec_state.encode.current_render_target = VA_INVALID_ID;
1238             obj_context->codec_state.encode.max_slice_params = NUM_SLICES;
1239             obj_context->codec_state.encode.slice_params = calloc(obj_context->codec_state.encode.max_slice_params,
1240                                                                sizeof(*obj_context->codec_state.encode.slice_params));
1241             assert(i965->codec_info->enc_hw_context_init);
1242             obj_context->hw_context = i965->codec_info->enc_hw_context_init(ctx, obj_config);
1243         } else {
1244             obj_context->codec_type = CODEC_DEC;
1245             memset(&obj_context->codec_state.decode, 0, sizeof(obj_context->codec_state.decode));
1246             obj_context->codec_state.decode.current_render_target = -1;
1247             obj_context->codec_state.decode.max_slice_params = NUM_SLICES;
1248             obj_context->codec_state.decode.max_slice_datas = NUM_SLICES;
1249             obj_context->codec_state.decode.slice_params = calloc(obj_context->codec_state.decode.max_slice_params,
1250                                                                sizeof(*obj_context->codec_state.decode.slice_params));
1251             obj_context->codec_state.decode.slice_datas = calloc(obj_context->codec_state.decode.max_slice_datas,
1252                                                               sizeof(*obj_context->codec_state.decode.slice_datas));
1253
1254             assert(i965->codec_info->dec_hw_context_init);
1255             obj_context->hw_context = i965->codec_info->dec_hw_context_init(ctx, obj_config);
1256         }
1257     }
1258
1259     /* Error recovery */
1260     if (VA_STATUS_SUCCESS != vaStatus) {
1261         i965_destroy_context(&i965->context_heap, (struct object_base *)obj_context);
1262     }
1263
1264     i965->current_context_id = contextID;
1265
1266     return vaStatus;
1267 }
1268
1269 VAStatus 
1270 i965_DestroyContext(VADriverContextP ctx, VAContextID context)
1271 {
1272     struct i965_driver_data *i965 = i965_driver_data(ctx);
1273     struct object_context *obj_context = CONTEXT(context);
1274
1275     assert(obj_context);
1276
1277     if (i965->current_context_id == context)
1278         i965->current_context_id = VA_INVALID_ID;
1279
1280     i965_destroy_context(&i965->context_heap, (struct object_base *)obj_context);
1281
1282     return VA_STATUS_SUCCESS;
1283 }
1284
1285 static void 
1286 i965_destroy_buffer(struct object_heap *heap, struct object_base *obj)
1287 {
1288     struct object_buffer *obj_buffer = (struct object_buffer *)obj;
1289
1290     assert(obj_buffer->buffer_store);
1291     i965_release_buffer_store(&obj_buffer->buffer_store);
1292     object_heap_free(heap, obj);
1293 }
1294
1295 static VAStatus
1296 i965_create_buffer_internal(VADriverContextP ctx,
1297                             VAContextID context,
1298                             VABufferType type,
1299                             unsigned int size,
1300                             unsigned int num_elements,
1301                             void *data,
1302                             dri_bo *store_bo,
1303                             VABufferID *buf_id)
1304 {
1305     struct i965_driver_data *i965 = i965_driver_data(ctx);
1306     struct object_buffer *obj_buffer = NULL;
1307     struct buffer_store *buffer_store = NULL;
1308     int bufferID;
1309
1310     /* Validate type */
1311     switch (type) {
1312     case VAPictureParameterBufferType:
1313     case VAIQMatrixBufferType:
1314     case VAQMatrixBufferType:
1315     case VABitPlaneBufferType:
1316     case VASliceGroupMapBufferType:
1317     case VASliceParameterBufferType:
1318     case VASliceDataBufferType:
1319     case VAMacroblockParameterBufferType:
1320     case VAResidualDataBufferType:
1321     case VADeblockingParameterBufferType:
1322     case VAImageBufferType:
1323     case VAEncCodedBufferType:
1324     case VAEncSequenceParameterBufferType:
1325     case VAEncPictureParameterBufferType:
1326     case VAEncSliceParameterBufferType:
1327     case VAEncPackedHeaderParameterBufferType:
1328     case VAEncPackedHeaderDataBufferType:
1329     case VAEncMiscParameterBufferType:
1330     case VAProcPipelineParameterBufferType:
1331     case VAProcFilterParameterBufferType:
1332     case VAHuffmanTableBufferType:
1333         /* Ok */
1334         break;
1335
1336     default:
1337         return VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
1338     }
1339
1340     bufferID = NEW_BUFFER_ID();
1341     obj_buffer = BUFFER(bufferID);
1342
1343     if (NULL == obj_buffer) {
1344         return VA_STATUS_ERROR_ALLOCATION_FAILED;
1345     }
1346
1347     if (type == VAEncCodedBufferType) {
1348         size += I965_CODEDBUFFER_HEADER_SIZE;
1349         size += 0x1000; /* for upper bound check */
1350     }
1351
1352     obj_buffer->max_num_elements = num_elements;
1353     obj_buffer->num_elements = num_elements;
1354     obj_buffer->size_element = size;
1355     obj_buffer->type = type;
1356     obj_buffer->buffer_store = NULL;
1357     buffer_store = calloc(1, sizeof(struct buffer_store));
1358     assert(buffer_store);
1359     buffer_store->ref_count = 1;
1360
1361     if (store_bo != NULL) {
1362         buffer_store->bo = store_bo;
1363         dri_bo_reference(buffer_store->bo);
1364         
1365         if (data)
1366             dri_bo_subdata(buffer_store->bo, 0, size * num_elements, data);
1367     } else if (type == VASliceDataBufferType || 
1368                type == VAImageBufferType || 
1369                type == VAEncCodedBufferType) {
1370         buffer_store->bo = dri_bo_alloc(i965->intel.bufmgr, 
1371                                         "Buffer", 
1372                                         size * num_elements, 64);
1373         assert(buffer_store->bo);
1374
1375         if (type == VAEncCodedBufferType) {
1376             struct i965_coded_buffer_segment *coded_buffer_segment;
1377
1378             dri_bo_map(buffer_store->bo, 1);
1379             coded_buffer_segment = (struct i965_coded_buffer_segment *)buffer_store->bo->virtual;
1380             coded_buffer_segment->base.size = size - I965_CODEDBUFFER_HEADER_SIZE;
1381             coded_buffer_segment->base.bit_offset = 0;
1382             coded_buffer_segment->base.status = 0;
1383             coded_buffer_segment->base.buf = NULL;
1384             coded_buffer_segment->base.next = NULL;
1385             coded_buffer_segment->mapped = 0;
1386             coded_buffer_segment->codec = 0;
1387             dri_bo_unmap(buffer_store->bo);
1388         } else if (data) {
1389             dri_bo_subdata(buffer_store->bo, 0, size * num_elements, data);
1390         }
1391
1392     } else {
1393         int msize = size;
1394         
1395         if (type == VAEncPackedHeaderDataBufferType) {
1396             msize = ALIGN(size, 4);
1397         }
1398
1399         buffer_store->buffer = malloc(msize * num_elements);
1400         assert(buffer_store->buffer);
1401
1402         if (data)
1403             memcpy(buffer_store->buffer, data, size * num_elements);
1404     }
1405
1406     buffer_store->num_elements = obj_buffer->num_elements;
1407     i965_reference_buffer_store(&obj_buffer->buffer_store, buffer_store);
1408     i965_release_buffer_store(&buffer_store);
1409     *buf_id = bufferID;
1410
1411     return VA_STATUS_SUCCESS;
1412 }
1413
1414 VAStatus 
1415 i965_CreateBuffer(VADriverContextP ctx,
1416                   VAContextID context,          /* in */
1417                   VABufferType type,            /* in */
1418                   unsigned int size,            /* in */
1419                   unsigned int num_elements,    /* in */
1420                   void *data,                   /* in */
1421                   VABufferID *buf_id)           /* out */
1422 {
1423     return i965_create_buffer_internal(ctx, context, type, size, num_elements, data, NULL, buf_id);
1424 }
1425
1426
1427 VAStatus 
1428 i965_BufferSetNumElements(VADriverContextP ctx,
1429                           VABufferID buf_id,           /* in */
1430                           unsigned int num_elements)   /* in */
1431 {
1432     struct i965_driver_data *i965 = i965_driver_data(ctx);
1433     struct object_buffer *obj_buffer = BUFFER(buf_id);
1434     VAStatus vaStatus = VA_STATUS_SUCCESS;
1435
1436     assert(obj_buffer);
1437
1438     if ((num_elements < 0) || 
1439         (num_elements > obj_buffer->max_num_elements)) {
1440         vaStatus = VA_STATUS_ERROR_UNKNOWN;
1441     } else {
1442         obj_buffer->num_elements = num_elements;
1443         if (obj_buffer->buffer_store != NULL) {
1444             obj_buffer->buffer_store->num_elements = num_elements;
1445         }
1446     }
1447
1448     return vaStatus;
1449 }
1450
1451 VAStatus 
1452 i965_MapBuffer(VADriverContextP ctx,
1453                VABufferID buf_id,       /* in */
1454                void **pbuf)             /* out */
1455 {
1456     struct i965_driver_data *i965 = i965_driver_data(ctx);
1457     struct object_buffer *obj_buffer = BUFFER(buf_id);
1458     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1459
1460     assert(obj_buffer && obj_buffer->buffer_store);
1461     assert(obj_buffer->buffer_store->bo || obj_buffer->buffer_store->buffer);
1462     assert(!(obj_buffer->buffer_store->bo && obj_buffer->buffer_store->buffer));
1463
1464     if (NULL != obj_buffer->buffer_store->bo) {
1465         unsigned int tiling, swizzle;
1466
1467         dri_bo_get_tiling(obj_buffer->buffer_store->bo, &tiling, &swizzle);
1468
1469         if (tiling != I915_TILING_NONE)
1470             drm_intel_gem_bo_map_gtt(obj_buffer->buffer_store->bo);
1471         else
1472             dri_bo_map(obj_buffer->buffer_store->bo, 1);
1473
1474         assert(obj_buffer->buffer_store->bo->virtual);
1475         *pbuf = obj_buffer->buffer_store->bo->virtual;
1476
1477         if (obj_buffer->type == VAEncCodedBufferType) {
1478             int i;
1479             unsigned char *buffer = NULL;
1480             struct i965_coded_buffer_segment *coded_buffer_segment = (struct i965_coded_buffer_segment *)(obj_buffer->buffer_store->bo->virtual);
1481
1482             if (!coded_buffer_segment->mapped) {
1483                 unsigned char delimiter0, delimiter1, delimiter2, delimiter3, delimiter4;
1484
1485                 coded_buffer_segment->base.buf = buffer = (unsigned char *)(obj_buffer->buffer_store->bo->virtual) + I965_CODEDBUFFER_HEADER_SIZE;
1486
1487                 if (coded_buffer_segment->codec == CODED_H264) {
1488                     delimiter0 = H264_DELIMITER0;
1489                     delimiter1 = H264_DELIMITER1;
1490                     delimiter2 = H264_DELIMITER2;
1491                     delimiter3 = H264_DELIMITER3;
1492                     delimiter4 = H264_DELIMITER4;
1493                 } else if (coded_buffer_segment->codec == CODED_MPEG2) {
1494                     delimiter0 = MPEG2_DELIMITER0;
1495                     delimiter1 = MPEG2_DELIMITER1;
1496                     delimiter2 = MPEG2_DELIMITER2;
1497                     delimiter3 = MPEG2_DELIMITER3;
1498                     delimiter4 = MPEG2_DELIMITER4;
1499                 } else {
1500                     assert(0);
1501                 }
1502
1503                 for (i = 0; i < obj_buffer->size_element - I965_CODEDBUFFER_HEADER_SIZE - 3 - 0x1000; i++) {
1504                     if ((buffer[i] == delimiter0) &&
1505                         (buffer[i + 1] == delimiter1) &&
1506                         (buffer[i + 2] == delimiter2) &&
1507                         (buffer[i + 3] == delimiter3) &&
1508                         (buffer[i + 4] == delimiter4))
1509                         break;
1510                 }
1511
1512                 if (i == obj_buffer->size_element - I965_CODEDBUFFER_HEADER_SIZE - 3 - 0x1000) {
1513                     coded_buffer_segment->base.status |= VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK;
1514                 }
1515
1516                 coded_buffer_segment->base.size = i;
1517                 coded_buffer_segment->mapped = 1;
1518             } else {
1519                 assert(coded_buffer_segment->base.buf);
1520             }
1521         }
1522
1523         vaStatus = VA_STATUS_SUCCESS;
1524     } else if (NULL != obj_buffer->buffer_store->buffer) {
1525         *pbuf = obj_buffer->buffer_store->buffer;
1526         vaStatus = VA_STATUS_SUCCESS;
1527     }
1528
1529     return vaStatus;
1530 }
1531
1532 VAStatus 
1533 i965_UnmapBuffer(VADriverContextP ctx, VABufferID buf_id)
1534 {
1535     struct i965_driver_data *i965 = i965_driver_data(ctx);
1536     struct object_buffer *obj_buffer = BUFFER(buf_id);
1537     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1538
1539     assert(obj_buffer && obj_buffer->buffer_store);
1540     assert(obj_buffer->buffer_store->bo || obj_buffer->buffer_store->buffer);
1541     assert(!(obj_buffer->buffer_store->bo && obj_buffer->buffer_store->buffer));
1542
1543     if (NULL != obj_buffer->buffer_store->bo) {
1544         unsigned int tiling, swizzle;
1545
1546         dri_bo_get_tiling(obj_buffer->buffer_store->bo, &tiling, &swizzle);
1547
1548         if (tiling != I915_TILING_NONE)
1549             drm_intel_gem_bo_unmap_gtt(obj_buffer->buffer_store->bo);
1550         else
1551             dri_bo_unmap(obj_buffer->buffer_store->bo);
1552
1553         vaStatus = VA_STATUS_SUCCESS;
1554     } else if (NULL != obj_buffer->buffer_store->buffer) {
1555         /* Do nothing */
1556         vaStatus = VA_STATUS_SUCCESS;
1557     }
1558
1559     return vaStatus;    
1560 }
1561
1562 VAStatus 
1563 i965_DestroyBuffer(VADriverContextP ctx, VABufferID buffer_id)
1564 {
1565     struct i965_driver_data *i965 = i965_driver_data(ctx);
1566     struct object_buffer *obj_buffer = BUFFER(buffer_id);
1567
1568     assert(obj_buffer);
1569     i965_destroy_buffer(&i965->buffer_heap, (struct object_base *)obj_buffer);
1570
1571     return VA_STATUS_SUCCESS;
1572 }
1573
1574 VAStatus 
1575 i965_BeginPicture(VADriverContextP ctx,
1576                   VAContextID context,
1577                   VASurfaceID render_target)
1578 {
1579     struct i965_driver_data *i965 = i965_driver_data(ctx); 
1580     struct object_context *obj_context = CONTEXT(context);
1581     struct object_surface *obj_surface = SURFACE(render_target);
1582     struct object_config *obj_config;
1583     VAContextID config;
1584     VAStatus vaStatus;
1585     int i;
1586
1587     assert(obj_context);
1588     assert(obj_surface);
1589
1590     config = obj_context->config_id;
1591     obj_config = CONFIG(config);
1592     assert(obj_config);
1593
1594     switch (obj_config->profile) {
1595     case VAProfileMPEG2Simple:
1596     case VAProfileMPEG2Main:
1597         vaStatus = VA_STATUS_SUCCESS;
1598         break;
1599
1600     case VAProfileH264Baseline:
1601     case VAProfileH264Main:
1602     case VAProfileH264High:
1603         vaStatus = VA_STATUS_SUCCESS;
1604         break;
1605
1606     case VAProfileVC1Simple:
1607     case VAProfileVC1Main:
1608     case VAProfileVC1Advanced:
1609         vaStatus = VA_STATUS_SUCCESS;
1610         break;
1611
1612     case VAProfileJPEGBaseline:
1613         vaStatus = VA_STATUS_SUCCESS;
1614         break;
1615
1616     case VAProfileNone:
1617         vaStatus = VA_STATUS_SUCCESS;
1618         break;
1619
1620     default:
1621         assert(0);
1622         vaStatus = VA_STATUS_ERROR_UNSUPPORTED_PROFILE;
1623         break;
1624     }
1625
1626     if (obj_context->codec_type == CODEC_PROC) {
1627         obj_context->codec_state.proc.current_render_target = render_target;
1628     } else if (obj_context->codec_type == CODEC_ENC) {
1629         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param);
1630
1631         for (i = 0; i < obj_context->codec_state.encode.num_slice_params; i++) {
1632             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params[i]);
1633         }
1634
1635         obj_context->codec_state.encode.num_slice_params = 0;
1636
1637         /* ext */
1638         i965_release_buffer_store(&obj_context->codec_state.encode.pic_param_ext);
1639
1640         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_param); i++)
1641             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_param[i]);
1642
1643         for (i = 0; i < ARRAY_ELEMS(obj_context->codec_state.encode.packed_header_data); i++)
1644             i965_release_buffer_store(&obj_context->codec_state.encode.packed_header_data[i]);
1645
1646         for (i = 0; i < obj_context->codec_state.encode.num_slice_params_ext; i++)
1647             i965_release_buffer_store(&obj_context->codec_state.encode.slice_params_ext[i]);
1648
1649         obj_context->codec_state.encode.num_slice_params_ext = 0;
1650         obj_context->codec_state.encode.current_render_target = render_target;     /*This is input new frame*/
1651         obj_context->codec_state.encode.last_packed_header_type = 0;
1652     } else {
1653         obj_context->codec_state.decode.current_render_target = render_target;
1654         i965_release_buffer_store(&obj_context->codec_state.decode.pic_param);
1655         i965_release_buffer_store(&obj_context->codec_state.decode.iq_matrix);
1656         i965_release_buffer_store(&obj_context->codec_state.decode.bit_plane);
1657         i965_release_buffer_store(&obj_context->codec_state.decode.huffman_table);
1658
1659         for (i = 0; i < obj_context->codec_state.decode.num_slice_params; i++) {
1660             i965_release_buffer_store(&obj_context->codec_state.decode.slice_params[i]);
1661             i965_release_buffer_store(&obj_context->codec_state.decode.slice_datas[i]);
1662         }
1663
1664         obj_context->codec_state.decode.num_slice_params = 0;
1665         obj_context->codec_state.decode.num_slice_datas = 0;
1666     }
1667
1668     return vaStatus;
1669 }
1670
1671 #define I965_RENDER_BUFFER(category, name) i965_render_##category##_##name##_buffer(ctx, obj_context, obj_buffer)
1672
1673 #define DEF_RENDER_SINGLE_BUFFER_FUNC(category, name, member)           \
1674     static VAStatus                                                     \
1675     i965_render_##category##_##name##_buffer(VADriverContextP ctx,      \
1676                                              struct object_context *obj_context, \
1677                                              struct object_buffer *obj_buffer) \
1678     {                                                                   \
1679         struct category##_state *category = &obj_context->codec_state.category; \
1680         assert(obj_buffer->buffer_store->bo == NULL);                   \
1681         assert(obj_buffer->buffer_store->buffer);                       \
1682         i965_release_buffer_store(&category->member);                   \
1683         i965_reference_buffer_store(&category->member, obj_buffer->buffer_store); \
1684         return VA_STATUS_SUCCESS;                                       \
1685     }
1686
1687 #define DEF_RENDER_MULTI_BUFFER_FUNC(category, name, member)            \
1688     static VAStatus                                                     \
1689     i965_render_##category##_##name##_buffer(VADriverContextP ctx,      \
1690                                              struct object_context *obj_context, \
1691                                              struct object_buffer *obj_buffer) \
1692     {                                                                   \
1693         struct category##_state *category = &obj_context->codec_state.category; \
1694         if (category->num_##member == category->max_##member) {         \
1695             category->member = realloc(category->member, (category->max_##member + NUM_SLICES) * sizeof(*category->member)); \
1696             memset(category->member + category->max_##member, 0, NUM_SLICES * sizeof(*category->member)); \
1697             category->max_##member += NUM_SLICES;                       \
1698         }                                                               \
1699         i965_release_buffer_store(&category->member[category->num_##member]); \
1700         i965_reference_buffer_store(&category->member[category->num_##member], obj_buffer->buffer_store); \
1701         category->num_##member++;                                       \
1702         return VA_STATUS_SUCCESS;                                       \
1703     }
1704
1705 #define I965_RENDER_DECODE_BUFFER(name) I965_RENDER_BUFFER(decode, name)
1706
1707 #define DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(decode, name, member)
1708 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(picture_parameter, pic_param)
1709 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(iq_matrix, iq_matrix)
1710 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(bit_plane, bit_plane)
1711 DEF_RENDER_DECODE_SINGLE_BUFFER_FUNC(huffman_table, huffman_table)
1712
1713 #define DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(name, member) DEF_RENDER_MULTI_BUFFER_FUNC(decode, name, member)
1714 DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(slice_parameter, slice_params)
1715 DEF_RENDER_DECODE_MULTI_BUFFER_FUNC(slice_data, slice_datas)
1716
1717 static VAStatus 
1718 i965_decoder_render_picture(VADriverContextP ctx,
1719                             VAContextID context,
1720                             VABufferID *buffers,
1721                             int num_buffers)
1722 {
1723     struct i965_driver_data *i965 = i965_driver_data(ctx); 
1724     struct object_context *obj_context = CONTEXT(context);
1725     VAStatus vaStatus = VA_STATUS_SUCCESS;
1726     int i;
1727
1728     for (i = 0; i < num_buffers && vaStatus == VA_STATUS_SUCCESS; i++) {
1729         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
1730         assert(obj_buffer);
1731
1732         switch (obj_buffer->type) {
1733         case VAPictureParameterBufferType:
1734             vaStatus = I965_RENDER_DECODE_BUFFER(picture_parameter);
1735             break;
1736             
1737         case VAIQMatrixBufferType:
1738             vaStatus = I965_RENDER_DECODE_BUFFER(iq_matrix);
1739             break;
1740
1741         case VABitPlaneBufferType:
1742             vaStatus = I965_RENDER_DECODE_BUFFER(bit_plane);
1743             break;
1744
1745         case VASliceParameterBufferType:
1746             vaStatus = I965_RENDER_DECODE_BUFFER(slice_parameter);
1747             break;
1748
1749         case VASliceDataBufferType:
1750             vaStatus = I965_RENDER_DECODE_BUFFER(slice_data);
1751             break;
1752
1753         case VAHuffmanTableBufferType:
1754             vaStatus = I965_RENDER_DECODE_BUFFER(huffman_table);
1755             break;
1756
1757         default:
1758             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
1759             break;
1760         }
1761     }
1762
1763     return vaStatus;
1764 }
1765
1766 #define I965_RENDER_ENCODE_BUFFER(name) I965_RENDER_BUFFER(encode, name)
1767
1768 #define DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(encode, name, member)
1769 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(sequence_parameter, seq_param)    
1770 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_parameter, pic_param)
1771 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_control, pic_control)
1772 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(qmatrix, q_matrix)
1773 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(iqmatrix, iq_matrix)
1774 /* extended buffer */
1775 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(sequence_parameter_ext, seq_param_ext)
1776 DEF_RENDER_ENCODE_SINGLE_BUFFER_FUNC(picture_parameter_ext, pic_param_ext)
1777
1778 #define DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(name, member) DEF_RENDER_MULTI_BUFFER_FUNC(encode, name, member)
1779 DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(slice_parameter, slice_params)
1780 DEF_RENDER_ENCODE_MULTI_BUFFER_FUNC(slice_parameter_ext, slice_params_ext)
1781
1782 static VAStatus
1783 i965_encoder_render_packed_header_parameter_buffer(VADriverContextP ctx,
1784                                                    struct object_context *obj_context,
1785                                                    struct object_buffer *obj_buffer,
1786                                                    int type_index)
1787 {
1788     struct encode_state *encode = &obj_context->codec_state.encode;
1789
1790     assert(obj_buffer->buffer_store->bo == NULL);
1791     assert(obj_buffer->buffer_store->buffer);
1792     i965_release_buffer_store(&encode->packed_header_param[type_index]);
1793     i965_reference_buffer_store(&encode->packed_header_param[type_index], obj_buffer->buffer_store);
1794
1795     return VA_STATUS_SUCCESS;
1796 }
1797
1798 static VAStatus
1799 i965_encoder_render_packed_header_data_buffer(VADriverContextP ctx,
1800                                               struct object_context *obj_context,
1801                                               struct object_buffer *obj_buffer,
1802                                               int type_index)
1803 {
1804     struct encode_state *encode = &obj_context->codec_state.encode;
1805
1806     assert(obj_buffer->buffer_store->bo == NULL);
1807     assert(obj_buffer->buffer_store->buffer);
1808     i965_release_buffer_store(&encode->packed_header_data[type_index]);
1809     i965_reference_buffer_store(&encode->packed_header_data[type_index], obj_buffer->buffer_store);
1810
1811     return VA_STATUS_SUCCESS;
1812 }
1813
1814 static VAStatus
1815 i965_encoder_render_misc_parameter_buffer(VADriverContextP ctx,
1816                                           struct object_context *obj_context,
1817                                           struct object_buffer *obj_buffer)
1818 {
1819     struct encode_state *encode = &obj_context->codec_state.encode;
1820     VAEncMiscParameterBuffer *param = NULL;
1821
1822     assert(obj_buffer->buffer_store->bo == NULL);
1823     assert(obj_buffer->buffer_store->buffer);
1824
1825     param = (VAEncMiscParameterBuffer *)obj_buffer->buffer_store->buffer;
1826     i965_release_buffer_store(&encode->misc_param[param->type]);
1827     i965_reference_buffer_store(&encode->misc_param[param->type], obj_buffer->buffer_store);
1828
1829     return VA_STATUS_SUCCESS;
1830 }
1831
1832 static VAStatus 
1833 i965_encoder_render_picture(VADriverContextP ctx,
1834                             VAContextID context,
1835                             VABufferID *buffers,
1836                             int num_buffers)
1837 {
1838     struct i965_driver_data *i965 = i965_driver_data(ctx); 
1839     struct object_context *obj_context = CONTEXT(context);
1840     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1841     int i;
1842
1843     for (i = 0; i < num_buffers; i++) {  
1844         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
1845         assert(obj_buffer);
1846
1847         switch (obj_buffer->type) {
1848         case VAQMatrixBufferType:
1849             vaStatus = I965_RENDER_ENCODE_BUFFER(qmatrix);
1850             break;
1851
1852         case VAIQMatrixBufferType:
1853             vaStatus = I965_RENDER_ENCODE_BUFFER(iqmatrix);
1854             break;
1855
1856         case VAEncSequenceParameterBufferType:
1857             vaStatus = I965_RENDER_ENCODE_BUFFER(sequence_parameter_ext);
1858             break;
1859
1860         case VAEncPictureParameterBufferType:
1861             vaStatus = I965_RENDER_ENCODE_BUFFER(picture_parameter_ext);
1862             break;
1863
1864         case VAEncSliceParameterBufferType:
1865             vaStatus = I965_RENDER_ENCODE_BUFFER(slice_parameter_ext);
1866             break;
1867
1868         case VAEncPackedHeaderParameterBufferType:
1869         {
1870             struct encode_state *encode = &obj_context->codec_state.encode;
1871             VAEncPackedHeaderParameterBuffer *param = (VAEncPackedHeaderParameterBuffer *)obj_buffer->buffer_store->buffer;
1872             encode->last_packed_header_type = param->type;
1873
1874             vaStatus = i965_encoder_render_packed_header_parameter_buffer(ctx,
1875                                                                           obj_context,
1876                                                                           obj_buffer,
1877                                                                           va_enc_packed_type_to_idx(encode->last_packed_header_type));
1878             break;
1879         }
1880
1881         case VAEncPackedHeaderDataBufferType:
1882         {
1883             struct encode_state *encode = &obj_context->codec_state.encode;
1884
1885             assert(encode->last_packed_header_type == VAEncPackedHeaderSequence ||
1886                    encode->last_packed_header_type == VAEncPackedHeaderPicture ||
1887                    encode->last_packed_header_type == VAEncPackedHeaderSlice ||
1888                    ((encode->last_packed_header_type & VAEncPackedHeaderMiscMask == VAEncPackedHeaderMiscMask) &&
1889                     (encode->last_packed_header_type & (~VAEncPackedHeaderMiscMask) != 0)));
1890             vaStatus = i965_encoder_render_packed_header_data_buffer(ctx, 
1891                                                                      obj_context,
1892                                                                      obj_buffer,
1893                                                                      va_enc_packed_type_to_idx(encode->last_packed_header_type));
1894             break;       
1895         }
1896
1897         case VAEncMiscParameterBufferType:
1898             vaStatus = i965_encoder_render_misc_parameter_buffer(ctx,
1899                                                                  obj_context,
1900                                                                  obj_buffer);
1901             break;
1902             
1903         default:
1904             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
1905             break;
1906         }
1907     }   
1908
1909     return vaStatus;
1910 }
1911
1912 #define I965_RENDER_PROC_BUFFER(name) I965_RENDER_BUFFER(proc, name)
1913
1914 #define DEF_RENDER_PROC_SINGLE_BUFFER_FUNC(name, member) DEF_RENDER_SINGLE_BUFFER_FUNC(proc, name, member)
1915 DEF_RENDER_PROC_SINGLE_BUFFER_FUNC(pipeline_parameter, pipeline_param)    
1916
1917 static VAStatus 
1918 i965_proc_render_picture(VADriverContextP ctx,
1919                          VAContextID context,
1920                          VABufferID *buffers,
1921                          int num_buffers)
1922 {
1923     struct i965_driver_data *i965 = i965_driver_data(ctx); 
1924     struct object_context *obj_context = CONTEXT(context);
1925     VAStatus vaStatus = VA_STATUS_SUCCESS;
1926     int i;
1927
1928     for (i = 0; i < num_buffers && vaStatus == VA_STATUS_SUCCESS; i++) {
1929         struct object_buffer *obj_buffer = BUFFER(buffers[i]);
1930         assert(obj_buffer);
1931
1932         switch (obj_buffer->type) {
1933         case VAProcPipelineParameterBufferType:
1934             vaStatus = I965_RENDER_PROC_BUFFER(pipeline_parameter);
1935             break;
1936
1937         default:
1938             vaStatus = VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE;
1939             break;
1940         }
1941     }
1942
1943     return vaStatus;
1944 }
1945
1946 VAStatus 
1947 i965_RenderPicture(VADriverContextP ctx,
1948                    VAContextID context,
1949                    VABufferID *buffers,
1950                    int num_buffers)
1951 {
1952     struct i965_driver_data *i965 = i965_driver_data(ctx);
1953     struct object_context *obj_context;
1954     struct object_config *obj_config;
1955     VAContextID config;
1956     VAStatus vaStatus = VA_STATUS_ERROR_UNKNOWN;
1957
1958     obj_context = CONTEXT(context);
1959     assert(obj_context);
1960
1961     config = obj_context->config_id;
1962     obj_config = CONFIG(config);
1963     assert(obj_config);
1964
1965     if (VAEntrypointVideoProc == obj_config->entrypoint) {
1966         vaStatus = i965_proc_render_picture(ctx, context, buffers, num_buffers);
1967     } else if (VAEntrypointEncSlice == obj_config->entrypoint ) {
1968         vaStatus = i965_encoder_render_picture(ctx, context, buffers, num_buffers);
1969     } else {
1970         vaStatus = i965_decoder_render_picture(ctx, context, buffers, num_buffers);
1971     }
1972
1973     return vaStatus;
1974 }
1975
1976 VAStatus 
1977 i965_EndPicture(VADriverContextP ctx, VAContextID context)
1978 {
1979     struct i965_driver_data *i965 = i965_driver_data(ctx); 
1980     struct object_context *obj_context = CONTEXT(context);
1981     struct object_config *obj_config;
1982     VAContextID config;
1983
1984     assert(obj_context);
1985     config = obj_context->config_id;
1986     obj_config = CONFIG(config);
1987     assert(obj_config);
1988
1989     if (obj_context->codec_type == CODEC_PROC) {
1990         assert(VAEntrypointVideoProc == obj_config->entrypoint);
1991     } else if (obj_context->codec_type == CODEC_ENC) {
1992         assert(VAEntrypointEncSlice == obj_config->entrypoint);
1993
1994         assert(obj_context->codec_state.encode.pic_param ||
1995                obj_context->codec_state.encode.pic_param_ext);
1996         assert(obj_context->codec_state.encode.seq_param ||
1997                obj_context->codec_state.encode.seq_param_ext);
1998         assert(obj_context->codec_state.encode.num_slice_params >= 1 ||
1999                obj_context->codec_state.encode.num_slice_params_ext >= 1);
2000     } else {
2001         assert(obj_context->codec_state.decode.pic_param);
2002         assert(obj_context->codec_state.decode.num_slice_params >= 1);
2003         assert(obj_context->codec_state.decode.num_slice_datas >= 1);
2004         assert(obj_context->codec_state.decode.num_slice_params == obj_context->codec_state.decode.num_slice_datas);
2005     }
2006
2007     assert(obj_context->hw_context->run);
2008     obj_context->hw_context->run(ctx, obj_config->profile, &obj_context->codec_state, obj_context->hw_context);
2009
2010     return VA_STATUS_SUCCESS;
2011 }
2012
2013 VAStatus 
2014 i965_SyncSurface(VADriverContextP ctx,
2015                  VASurfaceID render_target)
2016 {
2017     struct i965_driver_data *i965 = i965_driver_data(ctx); 
2018     struct object_surface *obj_surface = SURFACE(render_target);
2019
2020     assert(obj_surface);
2021
2022     if(obj_surface->bo)
2023         drm_intel_bo_wait_rendering(obj_surface->bo);
2024
2025     return VA_STATUS_SUCCESS;
2026 }
2027
2028 VAStatus 
2029 i965_QuerySurfaceStatus(VADriverContextP ctx,
2030                         VASurfaceID render_target,
2031                         VASurfaceStatus *status)        /* out */
2032 {
2033     struct i965_driver_data *i965 = i965_driver_data(ctx); 
2034     struct object_surface *obj_surface = SURFACE(render_target);
2035
2036     assert(obj_surface);
2037
2038     if (obj_surface->bo) {
2039         if (drm_intel_bo_busy(obj_surface->bo)){
2040             *status = VASurfaceRendering;
2041         }
2042         else {
2043             *status = VASurfaceReady;
2044         }
2045     } else {
2046         *status = VASurfaceReady;
2047     }
2048
2049     return VA_STATUS_SUCCESS;
2050 }
2051
2052 static VADisplayAttribute *
2053 get_display_attribute(VADriverContextP ctx, VADisplayAttribType type)
2054 {
2055     struct i965_driver_data * const i965 = i965_driver_data(ctx);
2056     unsigned int i;
2057
2058     if (!i965->display_attributes)
2059         return NULL;
2060
2061     for (i = 0; i < i965->num_display_attributes; i++) {
2062         if (i965->display_attributes[i].type == type)
2063             return &i965->display_attributes[i];
2064     }
2065     return NULL;
2066 }
2067
2068 static bool
2069 i965_display_attributes_init(VADriverContextP ctx)
2070 {
2071     struct i965_driver_data * const i965 = i965_driver_data(ctx);
2072
2073     i965->num_display_attributes = ARRAY_ELEMS(i965_display_attributes);
2074     i965->display_attributes = malloc(
2075         i965->num_display_attributes * sizeof(i965->display_attributes[0]));
2076     if (!i965->display_attributes)
2077         return false;
2078
2079     memcpy(
2080         i965->display_attributes,
2081         i965_display_attributes,
2082         sizeof(i965_display_attributes)
2083     );
2084
2085     i965->rotation_attrib = get_display_attribute(ctx, VADisplayAttribRotation);
2086     if (!i965->rotation_attrib)
2087         return false;
2088     return true;
2089 }
2090
2091 static void
2092 i965_display_attributes_terminate(VADriverContextP ctx)
2093 {
2094     struct i965_driver_data * const i965 = i965_driver_data(ctx);
2095
2096     if (i965->display_attributes) {
2097         free(i965->display_attributes);
2098         i965->display_attributes = NULL;
2099         i965->num_display_attributes = 0;
2100     }
2101 }
2102
2103 /* 
2104  * Query display attributes 
2105  * The caller must provide a "attr_list" array that can hold at
2106  * least vaMaxNumDisplayAttributes() entries. The actual number of attributes
2107  * returned in "attr_list" is returned in "num_attributes".
2108  */
2109 VAStatus 
2110 i965_QueryDisplayAttributes(
2111     VADriverContextP    ctx,
2112     VADisplayAttribute *attribs,        /* out */
2113     int                *num_attribs_ptr /* out */
2114 )
2115 {
2116     const int num_attribs = ARRAY_ELEMS(i965_display_attributes);
2117
2118     if (attribs && num_attribs > 0)
2119         memcpy(attribs, i965_display_attributes, sizeof(i965_display_attributes));
2120
2121     if (num_attribs_ptr)
2122         *num_attribs_ptr = num_attribs;
2123
2124     return VA_STATUS_SUCCESS;
2125 }
2126
2127 /* 
2128  * Get display attributes 
2129  * This function returns the current attribute values in "attr_list".
2130  * Only attributes returned with VA_DISPLAY_ATTRIB_GETTABLE set in the "flags" field
2131  * from vaQueryDisplayAttributes() can have their values retrieved.  
2132  */
2133 VAStatus 
2134 i965_GetDisplayAttributes(
2135     VADriverContextP    ctx,
2136     VADisplayAttribute *attribs,        /* inout */
2137     int                 num_attribs     /* in */
2138 )
2139 {
2140     int i;
2141
2142     for (i = 0; i < num_attribs; i++) {
2143         VADisplayAttribute *src_attrib, * const dst_attrib = &attribs[i];
2144
2145         src_attrib = get_display_attribute(ctx, dst_attrib->type);
2146         if (src_attrib && (src_attrib->flags & VA_DISPLAY_ATTRIB_GETTABLE)) {
2147             dst_attrib->min_value = src_attrib->min_value;
2148             dst_attrib->max_value = src_attrib->max_value;
2149             dst_attrib->value     = src_attrib->value;
2150         }
2151         else
2152             dst_attrib->flags = VA_DISPLAY_ATTRIB_NOT_SUPPORTED;
2153     }
2154     return VA_STATUS_SUCCESS;
2155 }
2156
2157 /* 
2158  * Set display attributes 
2159  * Only attributes returned with VA_DISPLAY_ATTRIB_SETTABLE set in the "flags" field
2160  * from vaQueryDisplayAttributes() can be set.  If the attribute is not settable or 
2161  * the value is out of range, the function returns VA_STATUS_ERROR_ATTR_NOT_SUPPORTED
2162  */
2163 VAStatus 
2164 i965_SetDisplayAttributes(
2165     VADriverContextP    ctx,
2166     VADisplayAttribute *attribs,        /* in */
2167     int                 num_attribs     /* in */
2168 )
2169 {
2170     int i;
2171
2172     for (i = 0; i < num_attribs; i++) {
2173         VADisplayAttribute *dst_attrib, * const src_attrib = &attribs[i];
2174
2175         dst_attrib = get_display_attribute(ctx, src_attrib->type);
2176         if (!dst_attrib)
2177             return VA_STATUS_ERROR_ATTR_NOT_SUPPORTED;
2178
2179         if (!(dst_attrib->flags & VA_DISPLAY_ATTRIB_SETTABLE))
2180             continue;
2181
2182         if (src_attrib->value < dst_attrib->min_value ||
2183             src_attrib->value > dst_attrib->max_value)
2184             return VA_STATUS_ERROR_INVALID_PARAMETER;
2185
2186         dst_attrib->value = src_attrib->value;
2187         /* XXX: track modified attributes through timestamps */
2188     }
2189     return VA_STATUS_SUCCESS;
2190 }
2191
2192 VAStatus 
2193 i965_DbgCopySurfaceToBuffer(VADriverContextP ctx,
2194                             VASurfaceID surface,
2195                             void **buffer,              /* out */
2196                             unsigned int *stride)       /* out */
2197 {
2198     /* TODO */
2199     return VA_STATUS_ERROR_UNIMPLEMENTED;
2200 }
2201
2202 static VAStatus 
2203 i965_Init(VADriverContextP ctx)
2204 {
2205     struct i965_driver_data *i965 = i965_driver_data(ctx); 
2206
2207     if (intel_driver_init(ctx) == False)
2208         return VA_STATUS_ERROR_UNKNOWN;
2209
2210     if (IS_HASWELL(i965->intel.device_id))
2211         i965->codec_info = &gen75_hw_codec_info;
2212     else if (IS_G4X(i965->intel.device_id))
2213         i965->codec_info = &g4x_hw_codec_info;
2214     else if (IS_IRONLAKE(i965->intel.device_id))
2215         i965->codec_info = &ironlake_hw_codec_info;
2216     else if (IS_GEN6(i965->intel.device_id))
2217         i965->codec_info = &gen6_hw_codec_info;
2218     else if (IS_GEN7(i965->intel.device_id))
2219         i965->codec_info = &gen7_hw_codec_info;
2220     else
2221         return VA_STATUS_ERROR_UNKNOWN;
2222
2223     i965->batch = intel_batchbuffer_new(&i965->intel, I915_EXEC_RENDER, 0);
2224
2225     if (!i965_display_attributes_init(ctx))
2226         return VA_STATUS_ERROR_UNKNOWN;
2227
2228     if (i965_post_processing_init(ctx) == False)
2229         return VA_STATUS_ERROR_UNKNOWN;
2230
2231     if (i965_render_init(ctx) == False)
2232         return VA_STATUS_ERROR_UNKNOWN;
2233
2234 #ifdef HAVE_VA_WAYLAND
2235     if (IS_VA_WAYLAND(ctx) && !i965_output_wayland_init(ctx))
2236         return VA_STATUS_ERROR_UNKNOWN;
2237 #endif
2238
2239 #ifdef HAVE_VA_X11
2240     if (IS_VA_X11(ctx) && !i965_output_dri_init(ctx))
2241         return VA_STATUS_ERROR_UNKNOWN;
2242 #endif
2243
2244     _i965InitMutex(&i965->render_mutex);
2245     _i965InitMutex(&i965->pp_mutex);
2246
2247     return VA_STATUS_SUCCESS;
2248 }
2249
2250 static void
2251 i965_destroy_heap(struct object_heap *heap, 
2252                   void (*func)(struct object_heap *heap, struct object_base *object))
2253 {
2254     struct object_base *object;
2255     object_heap_iterator iter;    
2256
2257     object = object_heap_first(heap, &iter);
2258
2259     while (object) {
2260         if (func)
2261             func(heap, object);
2262
2263         object = object_heap_next(heap, &iter);
2264     }
2265
2266     object_heap_destroy(heap);
2267 }
2268
2269
2270 VAStatus 
2271 i965_DestroyImage(VADriverContextP ctx, VAImageID image);
2272
2273 VAStatus 
2274 i965_CreateImage(VADriverContextP ctx,
2275                  VAImageFormat *format,
2276                  int width,
2277                  int height,
2278                  VAImage *out_image)        /* out */
2279 {
2280     struct i965_driver_data *i965 = i965_driver_data(ctx);
2281     struct object_image *obj_image;
2282     VAStatus va_status = VA_STATUS_ERROR_OPERATION_FAILED;
2283     VAImageID image_id;
2284     unsigned int width2, height2, size2, size;
2285
2286     out_image->image_id = VA_INVALID_ID;
2287     out_image->buf      = VA_INVALID_ID;
2288
2289     image_id = NEW_IMAGE_ID();
2290     if (image_id == VA_INVALID_ID)
2291         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2292
2293     obj_image = IMAGE(image_id);
2294     if (!obj_image)
2295         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2296     obj_image->bo         = NULL;
2297     obj_image->palette    = NULL;
2298     obj_image->derived_surface = VA_INVALID_ID;
2299
2300     VAImage * const image = &obj_image->image;
2301     image->image_id       = image_id;
2302     image->buf            = VA_INVALID_ID;
2303
2304     size    = width * height;
2305     width2  = (width  + 1) / 2;
2306     height2 = (height + 1) / 2;
2307     size2   = width2 * height2;
2308
2309     image->num_palette_entries = 0;
2310     image->entry_bytes         = 0;
2311     memset(image->component_order, 0, sizeof(image->component_order));
2312
2313     switch (format->fourcc) {
2314     case VA_FOURCC('I','A','4','4'):
2315     case VA_FOURCC('A','I','4','4'):
2316         image->num_planes = 1;
2317         image->pitches[0] = width;
2318         image->offsets[0] = 0;
2319         image->data_size  = image->offsets[0] + image->pitches[0] * height;
2320         image->num_palette_entries = 16;
2321         image->entry_bytes         = 3;
2322         image->component_order[0]  = 'R';
2323         image->component_order[1]  = 'G';
2324         image->component_order[2]  = 'B';
2325         break;
2326     case VA_FOURCC('I','A','8','8'):
2327     case VA_FOURCC('A','I','8','8'):
2328         image->num_planes = 1;
2329         image->pitches[0] = width * 2;
2330         image->offsets[0] = 0;
2331         image->data_size  = image->offsets[0] + image->pitches[0] * height;
2332         image->num_palette_entries = 256;
2333         image->entry_bytes         = 3;
2334         image->component_order[0]  = 'R';
2335         image->component_order[1]  = 'G';
2336         image->component_order[2]  = 'B';
2337         break;
2338     case VA_FOURCC('B','G','R','A'):
2339     case VA_FOURCC('R','G','B','A'):
2340     case VA_FOURCC('B','G','R','X'):
2341     case VA_FOURCC('R','G','B','X'):
2342         image->num_planes = 1;
2343         image->pitches[0] = width * 4;
2344         image->offsets[0] = 0;
2345         image->data_size  = image->offsets[0] + image->pitches[0] * height;
2346         break;
2347     case VA_FOURCC('Y','V','1','2'):
2348         image->num_planes = 3;
2349         image->pitches[0] = width;
2350         image->offsets[0] = 0;
2351         image->pitches[1] = width2;
2352         image->offsets[1] = size + size2;
2353         image->pitches[2] = width2;
2354         image->offsets[2] = size;
2355         image->data_size  = size + 2 * size2;
2356         break;
2357     case VA_FOURCC('I','4','2','0'):
2358         image->num_planes = 3;
2359         image->pitches[0] = width;
2360         image->offsets[0] = 0;
2361         image->pitches[1] = width2;
2362         image->offsets[1] = size;
2363         image->pitches[2] = width2;
2364         image->offsets[2] = size + size2;
2365         image->data_size  = size + 2 * size2;
2366         break;
2367     case VA_FOURCC('N','V','1','2'):
2368         image->num_planes = 2;
2369         image->pitches[0] = width;
2370         image->offsets[0] = 0;
2371         image->pitches[1] = width;
2372         image->offsets[1] = size;
2373         image->data_size  = size + 2 * size2;
2374         break;
2375     case VA_FOURCC('Y','U','Y','2'):
2376     case VA_FOURCC('U','Y','V','Y'):
2377         image->num_planes = 1;
2378         image->pitches[0] = width * 2;
2379         image->offsets[0] = 0;
2380         image->data_size  = size * 2;
2381         break;
2382     default:
2383         goto error;
2384     }
2385
2386     va_status = i965_CreateBuffer(ctx, 0, VAImageBufferType,
2387                                   image->data_size, 1, NULL, &image->buf);
2388     if (va_status != VA_STATUS_SUCCESS)
2389         goto error;
2390
2391     obj_image->bo = BUFFER(image->buf)->buffer_store->bo;
2392     dri_bo_reference(obj_image->bo);
2393
2394     if (image->num_palette_entries > 0 && image->entry_bytes > 0) {
2395         obj_image->palette = malloc(image->num_palette_entries * sizeof(obj_image->palette));
2396         if (!obj_image->palette)
2397             goto error;
2398     }
2399
2400     image->image_id             = image_id;
2401     image->format               = *format;
2402     image->width                = width;
2403     image->height               = height;
2404
2405     *out_image                  = *image;
2406     return VA_STATUS_SUCCESS;
2407
2408  error:
2409     i965_DestroyImage(ctx, image_id);
2410     return va_status;
2411 }
2412
2413 void 
2414 i965_check_alloc_surface_bo(VADriverContextP ctx,
2415                             struct object_surface *obj_surface,
2416                             int tiled,
2417                             unsigned int fourcc,
2418                             unsigned int subsampling)
2419 {
2420     struct i965_driver_data *i965 = i965_driver_data(ctx);
2421     int region_width, region_height;
2422
2423     if (obj_surface->bo) {
2424         assert(obj_surface->fourcc);
2425         assert(obj_surface->fourcc == fourcc);
2426         assert(obj_surface->subsampling == subsampling);
2427         return;
2428     }
2429
2430     obj_surface->x_cb_offset = 0; /* X offset is always 0 */
2431     obj_surface->x_cr_offset = 0;
2432
2433     if (tiled) {
2434         assert(fourcc == VA_FOURCC('N', 'V', '1', '2') ||
2435                fourcc == VA_FOURCC('I', 'M', 'C', '1') ||
2436                fourcc == VA_FOURCC('I', 'M', 'C', '3') || 
2437                fourcc == VA_FOURCC('R', 'G', 'B', 'A') || 
2438                fourcc == VA_FOURCC('R', 'G', 'B', 'X') || 
2439                fourcc == VA_FOURCC('B', 'G', 'R', 'A') || 
2440                fourcc == VA_FOURCC('B', 'G', 'R', 'X') || 
2441                fourcc == VA_FOURCC('Y', 'U', 'Y', '2'));
2442
2443         obj_surface->width = ALIGN(obj_surface->orig_width, 128);
2444         obj_surface->height = ALIGN(obj_surface->orig_height, 32);
2445         region_height = obj_surface->height;
2446
2447         if (fourcc == VA_FOURCC('N', 'V', '1', '2') ||
2448             fourcc == VA_FOURCC('I', 'M', 'C', '1') ||
2449             fourcc == VA_FOURCC('I', 'M', 'C', '3')) {
2450             obj_surface->cb_cr_pitch = obj_surface->width;
2451             region_width = obj_surface->width;
2452         }
2453         else if (fourcc == VA_FOURCC('Y','U', 'Y', '2')) {
2454             obj_surface->cb_cr_pitch = obj_surface->width * 2;
2455             region_width = obj_surface->width * 2;
2456         }
2457         else if (fourcc == VA_FOURCC('R', 'G', 'B', 'A') || 
2458                  fourcc == VA_FOURCC('R', 'G', 'B', 'X') || 
2459                  fourcc == VA_FOURCC('B', 'G', 'R', 'A') || 
2460                  fourcc == VA_FOURCC('B', 'G', 'R', 'X')) {
2461             region_width = obj_surface->width * 4;
2462         }
2463         else {
2464             assert(0);
2465         }
2466                
2467
2468         if (fourcc == VA_FOURCC('N', 'V', '1', '2')) {
2469             assert(subsampling == SUBSAMPLE_YUV420);
2470             obj_surface->y_cb_offset = obj_surface->height;
2471             obj_surface->y_cr_offset = obj_surface->height;
2472             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2473             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
2474             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32);
2475         } else if (fourcc == VA_FOURCC('I', 'M', 'C', '1') ||
2476                    fourcc == VA_FOURCC('I', 'M', 'C', '3') || 
2477                    fourcc == VA_FOURCC('R', 'G', 'B', 'A') || 
2478                    fourcc == VA_FOURCC('R', 'G', 'B', 'X') || 
2479                    fourcc == VA_FOURCC('B', 'G', 'R', 'A') || 
2480                    fourcc == VA_FOURCC('B', 'G', 'R', 'X') || 
2481                    fourcc == VA_FOURCC('Y', 'U', 'Y', '2')) {
2482             switch (subsampling) {
2483             case SUBSAMPLE_YUV400:
2484                 obj_surface->cb_cr_width = 0;
2485                 obj_surface->cb_cr_height = 0;
2486                 break;
2487
2488             case SUBSAMPLE_YUV420:
2489                 obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2490                 obj_surface->cb_cr_height = obj_surface->orig_height / 2;
2491                 break;
2492
2493             case SUBSAMPLE_YUV422H:
2494                 obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2495                 obj_surface->cb_cr_height = obj_surface->orig_height;
2496                 break;
2497
2498             case SUBSAMPLE_YUV422V:
2499                 obj_surface->cb_cr_width = obj_surface->orig_width;
2500                 obj_surface->cb_cr_height = obj_surface->orig_height / 2;
2501                 break;
2502
2503             case SUBSAMPLE_YUV444:
2504                 obj_surface->cb_cr_width = obj_surface->orig_width;
2505                 obj_surface->cb_cr_height = obj_surface->orig_height;
2506                 break;
2507
2508             case SUBSAMPLE_YUV411:
2509                 obj_surface->cb_cr_width = obj_surface->orig_width / 4;
2510                 obj_surface->cb_cr_height = obj_surface->orig_height;
2511                 break;
2512             case SUBSAMPLE_RGBX:
2513                 break;
2514             default:
2515                 assert(0);
2516                 break;
2517             }
2518
2519             region_height = obj_surface->height + ALIGN(obj_surface->cb_cr_height, 32) * 2;
2520
2521             if (fourcc == VA_FOURCC('I', 'M', 'C', '1')) {
2522                 obj_surface->y_cr_offset = obj_surface->height;
2523                 obj_surface->y_cb_offset = obj_surface->y_cr_offset + ALIGN(obj_surface->cb_cr_height, 32);
2524             } else if (fourcc == VA_FOURCC('I', 'M', 'C', '3')){
2525                 obj_surface->y_cb_offset = obj_surface->height;
2526                 obj_surface->y_cr_offset = obj_surface->y_cb_offset + ALIGN(obj_surface->cb_cr_height, 32);
2527             }
2528             else if (fourcc == VA_FOURCC('Y','U', 'Y', '2')) {
2529                 obj_surface->y_cb_offset = 0; 
2530                 obj_surface->y_cr_offset = 0; 
2531                 region_height = obj_surface->height;
2532             }
2533             else if (fourcc == VA_FOURCC('R', 'G', 'B', 'A') || 
2534                      fourcc == VA_FOURCC('R', 'G', 'B', 'X') || 
2535                      fourcc == VA_FOURCC('B', 'G', 'R', 'A') || 
2536                      fourcc == VA_FOURCC('B', 'G', 'R', 'X')) {
2537                 region_height = obj_surface->height;
2538             }
2539         }
2540     } else {
2541         assert(fourcc != VA_FOURCC('I', 'M', 'C', '1') &&
2542                fourcc != VA_FOURCC('I', 'M', 'C', '3'));
2543         assert(subsampling == SUBSAMPLE_YUV420 || 
2544                subsampling == SUBSAMPLE_YUV422H || 
2545                subsampling == SUBSAMPLE_YUV422V || 
2546                subsampling == SUBSAMPLE_RGBX);
2547
2548         region_width = obj_surface->width;
2549         region_height = obj_surface->height;
2550
2551         switch (fourcc) {
2552         case VA_FOURCC('N', 'V', '1', '2'):
2553             obj_surface->y_cb_offset = obj_surface->height;
2554             obj_surface->y_cr_offset = obj_surface->height;
2555             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2556             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
2557             obj_surface->cb_cr_pitch = obj_surface->width;
2558             region_height = obj_surface->height + obj_surface->height / 2;
2559             break;
2560
2561         case VA_FOURCC('Y', 'V', '1', '2'):
2562         case VA_FOURCC('I', '4', '2', '0'):
2563             if (fourcc == VA_FOURCC('Y', 'V', '1', '2')) {
2564                 obj_surface->y_cr_offset = obj_surface->height;
2565                 obj_surface->y_cb_offset = obj_surface->height + obj_surface->height / 4;
2566             } else {
2567                 obj_surface->y_cb_offset = obj_surface->height;
2568                 obj_surface->y_cr_offset = obj_surface->height + obj_surface->height / 4;
2569             }
2570
2571             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2572             obj_surface->cb_cr_height = obj_surface->orig_height / 2;
2573             obj_surface->cb_cr_pitch = obj_surface->width / 2;
2574             region_height = obj_surface->height + obj_surface->height / 2;
2575             break;
2576
2577         case VA_FOURCC('Y','U', 'Y', '2'):
2578             obj_surface->y_cb_offset = 0;
2579             obj_surface->y_cr_offset = 0;
2580             obj_surface->cb_cr_width = obj_surface->orig_width / 2;
2581             obj_surface->cb_cr_height = obj_surface->orig_height;
2582             obj_surface->cb_cr_pitch = obj_surface->width * 2;
2583             region_width = obj_surface->width * 2;
2584             region_height = obj_surface->height;
2585             break;
2586         case VA_FOURCC('R', 'G', 'B', 'A'):
2587         case VA_FOURCC('R', 'G', 'B', 'X'):
2588         case VA_FOURCC('B', 'G', 'R', 'A'):
2589         case VA_FOURCC('B', 'G', 'R', 'X'):
2590             region_width = obj_surface->width * 4;
2591             region_height = obj_surface->height;
2592             break;
2593
2594         default:
2595             assert(0);
2596             break;
2597         }
2598     }
2599
2600     obj_surface->size = ALIGN(region_width * region_height, 0x1000);
2601
2602     if (tiled) {
2603         uint32_t tiling_mode = I915_TILING_Y; /* always uses Y-tiled format */
2604         unsigned long pitch;
2605
2606         obj_surface->bo = drm_intel_bo_alloc_tiled(i965->intel.bufmgr, 
2607                                                    "vaapi surface",
2608                                                    region_width,
2609                                                    region_height,
2610                                                    1,
2611                                                    &tiling_mode,
2612                                                    &pitch,
2613                                                    0);
2614         assert(tiling_mode == I915_TILING_Y);
2615         assert(pitch == obj_surface->width     || 
2616                pitch == obj_surface->width * 2 ||
2617                pitch == obj_surface->width * 4) ;
2618     } else {
2619         obj_surface->bo = dri_bo_alloc(i965->intel.bufmgr,
2620                                        "vaapi surface",
2621                                        obj_surface->size,
2622                                        0x1000);
2623     }
2624
2625     obj_surface->fourcc = fourcc;
2626     obj_surface->subsampling = subsampling;
2627     assert(obj_surface->bo);
2628 }
2629
2630 VAStatus i965_DeriveImage(VADriverContextP ctx,
2631                           VASurfaceID surface,
2632                           VAImage *out_image)        /* out */
2633 {
2634     struct i965_driver_data *i965 = i965_driver_data(ctx);
2635     struct object_image *obj_image;
2636     struct object_surface *obj_surface; 
2637     VAImageID image_id;
2638     unsigned int w_pitch, h_pitch;
2639     VAStatus va_status = VA_STATUS_ERROR_OPERATION_FAILED;
2640
2641     out_image->image_id = VA_INVALID_ID;
2642     obj_surface = SURFACE(surface);
2643
2644     if (!obj_surface)
2645         return VA_STATUS_ERROR_INVALID_SURFACE;
2646
2647     if (!obj_surface->bo) {
2648         unsigned int is_tiled = 0;
2649         unsigned int fourcc = VA_FOURCC('Y', 'V', '1', '2');
2650         i965_guess_surface_format(ctx, surface, &fourcc, &is_tiled);
2651         int sampling = get_sampling_from_fourcc(fourcc);
2652         i965_check_alloc_surface_bo(ctx, obj_surface, is_tiled, fourcc, sampling);
2653     }
2654
2655     assert(obj_surface->fourcc);
2656
2657     w_pitch = obj_surface->width;
2658     h_pitch = obj_surface->height;
2659
2660     image_id = NEW_IMAGE_ID();
2661
2662     if (image_id == VA_INVALID_ID)
2663         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2664
2665     obj_image = IMAGE(image_id);
2666     
2667     if (!obj_image)
2668         return VA_STATUS_ERROR_ALLOCATION_FAILED;
2669
2670     obj_image->bo = NULL;
2671     obj_image->palette = NULL;
2672     obj_image->derived_surface = VA_INVALID_ID;
2673
2674     VAImage * const image = &obj_image->image;
2675     
2676     memset(image, 0, sizeof(*image));
2677     image->image_id = image_id;
2678     image->buf = VA_INVALID_ID;
2679     image->num_palette_entries = 0;
2680     image->entry_bytes = 0;
2681     image->width = obj_surface->orig_width;
2682     image->height = obj_surface->orig_height;
2683     image->data_size = obj_surface->size;
2684
2685     image->format.fourcc = obj_surface->fourcc;
2686     image->format.byte_order = VA_LSB_FIRST;
2687     image->format.bits_per_pixel = 12;
2688
2689     switch (image->format.fourcc) {
2690     case VA_FOURCC('Y', 'V', '1', '2'):
2691         image->num_planes = 3;
2692         image->pitches[0] = w_pitch; /* Y */
2693         image->offsets[0] = 0;
2694         image->pitches[1] = obj_surface->cb_cr_pitch; /* V */
2695         image->offsets[1] = w_pitch * obj_surface->y_cr_offset;
2696         image->pitches[2] = obj_surface->cb_cr_pitch; /* U */
2697         image->offsets[2] = w_pitch * obj_surface->y_cb_offset;
2698         break;
2699
2700     case VA_FOURCC('N', 'V', '1', '2'):
2701         image->num_planes = 2;
2702         image->pitches[0] = w_pitch; /* Y */
2703         image->offsets[0] = 0;
2704         image->pitches[1] = obj_surface->cb_cr_pitch; /* UV */
2705         image->offsets[1] = w_pitch * obj_surface->y_cb_offset;
2706         break;
2707
2708     case VA_FOURCC('I', '4', '2', '0'):
2709         image->num_planes = 3;
2710         image->pitches[0] = w_pitch; /* Y */
2711         image->offsets[0] = 0;
2712         image->pitches[1] = obj_surface->cb_cr_pitch; /* U */
2713         image->offsets[1] = w_pitch * obj_surface->y_cb_offset;
2714         image->pitches[2] = obj_surface->cb_cr_pitch; /* V */
2715         image->offsets[2] = w_pitch * obj_surface->y_cr_offset;
2716         break;
2717     case VA_FOURCC('Y', 'U', 'Y', '2'):
2718         image->num_planes = 1;
2719         image->pitches[0] = obj_surface->width * 2; /* Y, width is aligned already */
2720         image->offsets[0] = 0;
2721         image->pitches[1] = obj_surface->width * 2; /* U */
2722         image->offsets[1] = 0;
2723         image->pitches[2] = obj_surface->width * 2; /* V */
2724         image->offsets[2] = 0;
2725         break;
2726     case VA_FOURCC('R', 'G', 'B', 'A'):
2727     case VA_FOURCC('R', 'G', 'B', 'X'):
2728     case VA_FOURCC('B', 'G', 'R', 'A'):
2729     case VA_FOURCC('B', 'G', 'R', 'X'):
2730         image->num_planes = 1;
2731         image->pitches[0] = obj_surface->width * 4;
2732         break;
2733     default:
2734         goto error;
2735     }
2736
2737     va_status = i965_create_buffer_internal(ctx, 0, VAImageBufferType,
2738                                             obj_surface->size, 1, NULL, obj_surface->bo, &image->buf);
2739     if (va_status != VA_STATUS_SUCCESS)
2740         goto error;
2741
2742     obj_image->bo = BUFFER(image->buf)->buffer_store->bo;
2743     dri_bo_reference(obj_image->bo);
2744
2745     if (image->num_palette_entries > 0 && image->entry_bytes > 0) {
2746         obj_image->palette = malloc(image->num_palette_entries * sizeof(obj_image->palette));
2747         if (!obj_image->palette) {
2748             va_status = VA_STATUS_ERROR_ALLOCATION_FAILED;
2749             goto error;
2750         }
2751     }
2752
2753     *out_image = *image;
2754     obj_surface->flags |= SURFACE_DERIVED;
2755     obj_image->derived_surface = surface;
2756
2757     return VA_STATUS_SUCCESS;
2758
2759  error:
2760     i965_DestroyImage(ctx, image_id);
2761     return va_status;
2762 }
2763
2764 static void 
2765 i965_destroy_image(struct object_heap *heap, struct object_base *obj)
2766 {
2767     object_heap_free(heap, obj);
2768 }
2769
2770
2771 VAStatus 
2772 i965_DestroyImage(VADriverContextP ctx, VAImageID image)
2773 {
2774     struct i965_driver_data *i965 = i965_driver_data(ctx);
2775     struct object_image *obj_image = IMAGE(image); 
2776     struct object_surface *obj_surface; 
2777
2778     if (!obj_image)
2779         return VA_STATUS_SUCCESS;
2780
2781     dri_bo_unreference(obj_image->bo);
2782     obj_image->bo = NULL;
2783
2784     if (obj_image->image.buf != VA_INVALID_ID) {
2785         i965_DestroyBuffer(ctx, obj_image->image.buf);
2786         obj_image->image.buf = VA_INVALID_ID;
2787     }
2788
2789     if (obj_image->palette) {
2790         free(obj_image->palette);
2791         obj_image->palette = NULL;
2792     }
2793
2794     obj_surface = SURFACE(obj_image->derived_surface);
2795
2796     if (obj_surface) {
2797         obj_surface->flags &= ~SURFACE_DERIVED;
2798     }
2799
2800     i965_destroy_image(&i965->image_heap, (struct object_base *)obj_image);
2801
2802     return VA_STATUS_SUCCESS;
2803 }
2804
2805 /*
2806  * pointer to an array holding the palette data.  The size of the array is
2807  * num_palette_entries * entry_bytes in size.  The order of the components
2808  * in the palette is described by the component_order in VASubpicture struct
2809  */
2810 VAStatus 
2811 i965_SetImagePalette(VADriverContextP ctx,
2812                      VAImageID image,
2813                      unsigned char *palette)
2814 {
2815     struct i965_driver_data *i965 = i965_driver_data(ctx);
2816     unsigned int i;
2817
2818     struct object_image *obj_image = IMAGE(image);
2819     if (!obj_image)
2820         return VA_STATUS_ERROR_INVALID_IMAGE;
2821
2822     if (!obj_image->palette)
2823         return VA_STATUS_ERROR_ALLOCATION_FAILED; /* XXX: unpaletted/error */
2824
2825     for (i = 0; i < obj_image->image.num_palette_entries; i++)
2826         obj_image->palette[i] = (((unsigned int)palette[3*i + 0] << 16) |
2827                                  ((unsigned int)palette[3*i + 1] <<  8) |
2828                                  (unsigned int)palette[3*i + 2]);
2829     return VA_STATUS_SUCCESS;
2830 }
2831
2832 static int 
2833 get_sampling_from_fourcc(unsigned int fourcc)
2834 {
2835     int surface_sampling = -1;
2836     switch (fourcc) {
2837     case VA_FOURCC('N', 'V', '1', '2'):
2838     case VA_FOURCC('Y', 'V', '1', '2'):
2839     case VA_FOURCC('I', '4', '2', '0'):
2840     case VA_FOURCC('I', 'M', 'C', '1'):
2841     case VA_FOURCC('I', 'M', 'C', '3'):
2842         surface_sampling = SUBSAMPLE_YUV420;
2843         break;
2844     case VA_FOURCC('Y', 'U', 'Y', '2'):
2845         surface_sampling = SUBSAMPLE_YUV422H;
2846         break;
2847     case VA_FOURCC('R','G','B','A'):
2848     case VA_FOURCC('R','G','B','X'):
2849     case VA_FOURCC('B','G','R','A'):
2850     case VA_FOURCC('B','G','R','X'):
2851     surface_sampling = SUBSAMPLE_RGBX; 
2852         break;
2853     default:
2854         break;
2855     }
2856     return surface_sampling;
2857 }
2858
2859 static inline void
2860 memcpy_pic(uint8_t *dst, unsigned int dst_stride,
2861            const uint8_t *src, unsigned int src_stride,
2862            unsigned int len, unsigned int height)
2863 {
2864     unsigned int i;
2865
2866     for (i = 0; i < height; i++) {
2867         memcpy(dst, src, len);
2868         dst += dst_stride;
2869         src += src_stride;
2870     }
2871 }
2872
2873 static void
2874 get_image_i420(struct object_image *obj_image, uint8_t *image_data,
2875                struct object_surface *obj_surface,
2876                const VARectangle *rect)
2877 {
2878     uint8_t *dst[3], *src[3];
2879     const int Y = 0;
2880     const int U = obj_image->image.format.fourcc == obj_surface->fourcc ? 1 : 2;
2881     const int V = obj_image->image.format.fourcc == obj_surface->fourcc ? 2 : 1;
2882     unsigned int tiling, swizzle;
2883
2884     if (!obj_surface->bo)
2885         return;
2886
2887     assert(obj_surface->fourcc);
2888     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
2889
2890     if (tiling != I915_TILING_NONE)
2891         drm_intel_gem_bo_map_gtt(obj_surface->bo);
2892     else
2893         dri_bo_map(obj_surface->bo, 0);
2894
2895     if (!obj_surface->bo->virtual)
2896         return;
2897
2898     /* Dest VA image has either I420 or YV12 format.
2899        Source VA surface alway has I420 format */
2900     dst[Y] = image_data + obj_image->image.offsets[Y];
2901     src[0] = (uint8_t *)obj_surface->bo->virtual;
2902     dst[U] = image_data + obj_image->image.offsets[U];
2903     src[1] = src[0] + obj_surface->width * obj_surface->height;
2904     dst[V] = image_data + obj_image->image.offsets[V];
2905     src[2] = src[1] + (obj_surface->width / 2) * (obj_surface->height / 2);
2906
2907     /* Y plane */
2908     dst[Y] += rect->y * obj_image->image.pitches[Y] + rect->x;
2909     src[0] += rect->y * obj_surface->width + rect->x;
2910     memcpy_pic(dst[Y], obj_image->image.pitches[Y],
2911                src[0], obj_surface->width,
2912                rect->width, rect->height);
2913
2914     /* U plane */
2915     dst[U] += (rect->y / 2) * obj_image->image.pitches[U] + rect->x / 2;
2916     src[1] += (rect->y / 2) * obj_surface->width / 2 + rect->x / 2;
2917     memcpy_pic(dst[U], obj_image->image.pitches[U],
2918                src[1], obj_surface->width / 2,
2919                rect->width / 2, rect->height / 2);
2920
2921     /* V plane */
2922     dst[V] += (rect->y / 2) * obj_image->image.pitches[V] + rect->x / 2;
2923     src[2] += (rect->y / 2) * obj_surface->width / 2 + rect->x / 2;
2924     memcpy_pic(dst[V], obj_image->image.pitches[V],
2925                src[2], obj_surface->width / 2,
2926                rect->width / 2, rect->height / 2);
2927
2928     if (tiling != I915_TILING_NONE)
2929         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
2930     else
2931         dri_bo_unmap(obj_surface->bo);
2932 }
2933
2934 static void
2935 get_image_nv12(struct object_image *obj_image, uint8_t *image_data,
2936                struct object_surface *obj_surface,
2937                const VARectangle *rect)
2938 {
2939     uint8_t *dst[2], *src[2];
2940     unsigned int tiling, swizzle;
2941
2942     if (!obj_surface->bo)
2943         return;
2944
2945     assert(obj_surface->fourcc);
2946     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
2947
2948     if (tiling != I915_TILING_NONE)
2949         drm_intel_gem_bo_map_gtt(obj_surface->bo);
2950     else
2951         dri_bo_map(obj_surface->bo, 0);
2952
2953     if (!obj_surface->bo->virtual)
2954         return;
2955
2956     /* Both dest VA image and source surface have NV12 format */
2957     dst[0] = image_data + obj_image->image.offsets[0];
2958     src[0] = (uint8_t *)obj_surface->bo->virtual;
2959     dst[1] = image_data + obj_image->image.offsets[1];
2960     src[1] = src[0] + obj_surface->width * obj_surface->height;
2961
2962     /* Y plane */
2963     dst[0] += rect->y * obj_image->image.pitches[0] + rect->x;
2964     src[0] += rect->y * obj_surface->width + rect->x;
2965     memcpy_pic(dst[0], obj_image->image.pitches[0],
2966                src[0], obj_surface->width,
2967                rect->width, rect->height);
2968
2969     /* UV plane */
2970     dst[1] += (rect->y / 2) * obj_image->image.pitches[1] + (rect->x & -2);
2971     src[1] += (rect->y / 2) * obj_surface->width + (rect->x & -2);
2972     memcpy_pic(dst[1], obj_image->image.pitches[1],
2973                src[1], obj_surface->width,
2974                rect->width, rect->height / 2);
2975
2976     if (tiling != I915_TILING_NONE)
2977         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
2978     else
2979         dri_bo_unmap(obj_surface->bo);
2980 }
2981
2982 static void
2983 get_image_yuy2(struct object_image *obj_image, uint8_t *image_data,
2984                struct object_surface *obj_surface,
2985                const VARectangle *rect)
2986 {
2987     uint8_t *dst, *src;
2988     unsigned int tiling, swizzle;
2989
2990     if (!obj_surface->bo)
2991         return;
2992
2993     assert(obj_surface->fourcc);
2994     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
2995
2996     if (tiling != I915_TILING_NONE)
2997         drm_intel_gem_bo_map_gtt(obj_surface->bo);
2998     else
2999         dri_bo_map(obj_surface->bo, 0);
3000
3001     if (!obj_surface->bo->virtual)
3002         return;
3003
3004     /* Both dest VA image and source surface have YUYV format */
3005     dst = image_data + obj_image->image.offsets[0];
3006     src = (uint8_t *)obj_surface->bo->virtual;
3007
3008     /* Y plane */
3009     dst += rect->y * obj_image->image.pitches[0] + rect->x*2;
3010     src += rect->y * obj_surface->width + rect->x*2;
3011     memcpy_pic(dst, obj_image->image.pitches[0],
3012                src, obj_surface->width*2,
3013                rect->width*2, rect->height);
3014
3015     if (tiling != I915_TILING_NONE)
3016         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
3017     else
3018         dri_bo_unmap(obj_surface->bo);
3019 }
3020
3021 static VAStatus 
3022 i965_sw_getimage(VADriverContextP ctx,
3023                  VASurfaceID surface,
3024                  int x,   /* coordinates of the upper left source pixel */
3025                  int y,
3026                  unsigned int width,      /* width and height of the region */
3027                  unsigned int height,
3028                  VAImageID image)
3029 {
3030     struct i965_driver_data *i965 = i965_driver_data(ctx);
3031     struct i965_render_state *render_state = &i965->render_state;
3032
3033     struct object_surface *obj_surface = SURFACE(surface);
3034     if (!obj_surface)
3035         return VA_STATUS_ERROR_INVALID_SURFACE;
3036
3037     struct object_image *obj_image = IMAGE(image);
3038     if (!obj_image)
3039         return VA_STATUS_ERROR_INVALID_IMAGE;
3040
3041     if (x < 0 || y < 0)
3042         return VA_STATUS_ERROR_INVALID_PARAMETER;
3043     if (x + width > obj_surface->orig_width ||
3044         y + height > obj_surface->orig_height)
3045         return VA_STATUS_ERROR_INVALID_PARAMETER;
3046     if (x + width > obj_image->image.width ||
3047         y + height > obj_image->image.height)
3048         return VA_STATUS_ERROR_INVALID_PARAMETER;
3049
3050     if (obj_surface->fourcc != obj_image->image.format.fourcc)
3051         return VA_STATUS_ERROR_INVALID_IMAGE_FORMAT;
3052
3053     VAStatus va_status;
3054     void *image_data = NULL;
3055
3056     va_status = i965_MapBuffer(ctx, obj_image->image.buf, &image_data);
3057     if (va_status != VA_STATUS_SUCCESS)
3058         return va_status;
3059
3060     VARectangle rect;
3061     rect.x = x;
3062     rect.y = y;
3063     rect.width = width;
3064     rect.height = height;
3065
3066     switch (obj_image->image.format.fourcc) {
3067     case VA_FOURCC('Y','V','1','2'):
3068     case VA_FOURCC('I','4','2','0'):
3069         /* I420 is native format for MPEG-2 decoded surfaces */
3070         if (render_state->interleaved_uv)
3071             goto operation_failed;
3072         get_image_i420(obj_image, image_data, obj_surface, &rect);
3073         break;
3074     case VA_FOURCC('N','V','1','2'):
3075         /* NV12 is native format for H.264 decoded surfaces */
3076         if (!render_state->interleaved_uv)
3077             goto operation_failed;
3078         get_image_nv12(obj_image, image_data, obj_surface, &rect);
3079         break;
3080     case VA_FOURCC('Y','U','Y','2'):
3081         /* YUY2 is the format supported by overlay plane */
3082         get_image_yuy2(obj_image, image_data, obj_surface, &rect);
3083         break;
3084     default:
3085     operation_failed:
3086         va_status = VA_STATUS_ERROR_OPERATION_FAILED;
3087         break;
3088     }
3089
3090     i965_UnmapBuffer(ctx, obj_image->image.buf);
3091     return va_status;
3092 }
3093
3094 static VAStatus 
3095 i965_hw_getimage(VADriverContextP ctx,
3096                  VASurfaceID surface,
3097                  int x,   /* coordinates of the upper left source pixel */
3098                  int y,
3099                  unsigned int width,      /* width and height of the region */
3100                  unsigned int height,
3101                  VAImageID image)
3102 {
3103     struct i965_driver_data *i965 = i965_driver_data(ctx);
3104     struct i965_surface src_surface;
3105     struct i965_surface dst_surface;
3106     VAStatus va_status;
3107     VARectangle rect;
3108     struct object_surface *obj_surface = SURFACE(surface);
3109     struct object_image *obj_image = IMAGE(image);
3110
3111     if (!obj_surface)
3112         return VA_STATUS_ERROR_INVALID_SURFACE;
3113
3114     if (!obj_image)
3115         return VA_STATUS_ERROR_INVALID_IMAGE;
3116
3117     if (x < 0 || y < 0)
3118         return VA_STATUS_ERROR_INVALID_PARAMETER;
3119     if (x + width > obj_surface->orig_width ||
3120         y + height > obj_surface->orig_height)
3121         return VA_STATUS_ERROR_INVALID_PARAMETER;
3122     if (x + width > obj_image->image.width ||
3123         y + height > obj_image->image.height)
3124         return VA_STATUS_ERROR_INVALID_PARAMETER;
3125
3126     if (!obj_surface->bo)
3127         return VA_STATUS_SUCCESS;
3128     assert(obj_image->bo); // image bo is always created, see i965_CreateImage()
3129
3130     rect.x = x;
3131     rect.y = y;
3132     rect.width = width;
3133     rect.height = height;
3134
3135     src_surface.id = surface;
3136     src_surface.type = I965_SURFACE_TYPE_SURFACE;
3137     src_surface.flags = I965_SURFACE_FLAG_FRAME;
3138
3139     dst_surface.id = image;
3140     dst_surface.type = I965_SURFACE_TYPE_IMAGE;
3141     dst_surface.flags = I965_SURFACE_FLAG_FRAME;
3142
3143     va_status = i965_image_processing(ctx,
3144                                       &src_surface,
3145                                       &rect,
3146                                       &dst_surface,
3147                                       &rect);
3148
3149
3150     return va_status;
3151 }
3152
3153 VAStatus 
3154 i965_GetImage(VADriverContextP ctx,
3155               VASurfaceID surface,
3156               int x,   /* coordinates of the upper left source pixel */
3157               int y,
3158               unsigned int width,      /* width and height of the region */
3159               unsigned int height,
3160               VAImageID image)
3161 {
3162     struct i965_driver_data * const i965 = i965_driver_data(ctx);
3163     VAStatus va_status;
3164
3165     if (HAS_ACCELERATED_GETIMAGE(i965))
3166         va_status = i965_hw_getimage(ctx,
3167                                      surface,
3168                                      x, y,
3169                                      width, height,
3170                                      image);
3171     else
3172         va_status = i965_sw_getimage(ctx,
3173                                      surface,
3174                                      x, y,
3175                                      width, height,
3176                                      image);
3177
3178     return va_status;
3179 }
3180
3181 static void
3182 put_image_i420(struct object_surface *obj_surface,
3183                const VARectangle *dst_rect,
3184                struct object_image *obj_image, uint8_t *image_data,
3185                const VARectangle *src_rect)
3186 {
3187     uint8_t *dst[3], *src[3];
3188     const int Y = 0;
3189     const int U = obj_image->image.format.fourcc == obj_surface->fourcc ? 1 : 2;
3190     const int V = obj_image->image.format.fourcc == obj_surface->fourcc ? 2 : 1;
3191     unsigned int tiling, swizzle;
3192
3193     if (!obj_surface->bo)
3194         return;
3195
3196     assert(obj_surface->fourcc);
3197     assert(dst_rect->width == src_rect->width);
3198     assert(dst_rect->height == src_rect->height);
3199     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
3200
3201     if (tiling != I915_TILING_NONE)
3202         drm_intel_gem_bo_map_gtt(obj_surface->bo);
3203     else
3204         dri_bo_map(obj_surface->bo, 0);
3205
3206     if (!obj_surface->bo->virtual)
3207         return;
3208
3209     /* Dest VA image has either I420 or YV12 format.
3210        Source VA surface alway has I420 format */
3211     dst[0] = (uint8_t *)obj_surface->bo->virtual;
3212     src[Y] = image_data + obj_image->image.offsets[Y];
3213     dst[1] = dst[0] + obj_surface->width * obj_surface->height;
3214     src[U] = image_data + obj_image->image.offsets[U];
3215     dst[2] = dst[1] + (obj_surface->width / 2) * (obj_surface->height / 2);
3216     src[V] = image_data + obj_image->image.offsets[V];
3217
3218     /* Y plane */
3219     dst[0] += dst_rect->y * obj_surface->width + dst_rect->x;
3220     src[Y] += src_rect->y * obj_image->image.pitches[Y] + src_rect->x;
3221     memcpy_pic(dst[0], obj_surface->width,
3222                src[Y], obj_image->image.pitches[Y],
3223                src_rect->width, src_rect->height);
3224
3225     /* U plane */
3226     dst[1] += (dst_rect->y / 2) * obj_surface->width / 2 + dst_rect->x / 2;
3227     src[U] += (src_rect->y / 2) * obj_image->image.pitches[U] + src_rect->x / 2;
3228     memcpy_pic(dst[1], obj_surface->width / 2,
3229                src[U], obj_image->image.pitches[U],
3230                src_rect->width / 2, src_rect->height / 2);
3231
3232     /* V plane */
3233     dst[2] += (dst_rect->y / 2) * obj_surface->width / 2 + dst_rect->x / 2;
3234     src[V] += (src_rect->y / 2) * obj_image->image.pitches[V] + src_rect->x / 2;
3235     memcpy_pic(dst[2], obj_surface->width / 2,
3236                src[V], obj_image->image.pitches[V],
3237                src_rect->width / 2, src_rect->height / 2);
3238
3239     if (tiling != I915_TILING_NONE)
3240         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
3241     else
3242         dri_bo_unmap(obj_surface->bo);
3243 }
3244
3245 static void
3246 put_image_nv12(struct object_surface *obj_surface,
3247                const VARectangle *dst_rect,
3248                struct object_image *obj_image, uint8_t *image_data,
3249                const VARectangle *src_rect)
3250 {
3251     uint8_t *dst[2], *src[2];
3252     unsigned int tiling, swizzle;
3253
3254     if (!obj_surface->bo)
3255         return;
3256
3257     assert(obj_surface->fourcc);
3258     assert(dst_rect->width == src_rect->width);
3259     assert(dst_rect->height == src_rect->height);
3260     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
3261
3262     if (tiling != I915_TILING_NONE)
3263         drm_intel_gem_bo_map_gtt(obj_surface->bo);
3264     else
3265         dri_bo_map(obj_surface->bo, 0);
3266
3267     if (!obj_surface->bo->virtual)
3268         return;
3269
3270     /* Both dest VA image and source surface have NV12 format */
3271     dst[0] = (uint8_t *)obj_surface->bo->virtual;
3272     src[0] = image_data + obj_image->image.offsets[0];
3273     dst[1] = dst[0] + obj_surface->width * obj_surface->height;
3274     src[1] = image_data + obj_image->image.offsets[1];
3275
3276     /* Y plane */
3277     dst[0] += dst_rect->y * obj_surface->width + dst_rect->x;
3278     src[0] += src_rect->y * obj_image->image.pitches[0] + src_rect->x;
3279     memcpy_pic(dst[0], obj_surface->width,
3280                src[0], obj_image->image.pitches[0],
3281                src_rect->width, src_rect->height);
3282
3283     /* UV plane */
3284     dst[1] += (dst_rect->y / 2) * obj_surface->width + (dst_rect->x & -2);
3285     src[1] += (src_rect->y / 2) * obj_image->image.pitches[1] + (src_rect->x & -2);
3286     memcpy_pic(dst[1], obj_surface->width,
3287                src[1], obj_image->image.pitches[1],
3288                src_rect->width, src_rect->height / 2);
3289
3290     if (tiling != I915_TILING_NONE)
3291         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
3292     else
3293         dri_bo_unmap(obj_surface->bo);
3294 }
3295
3296 static void
3297 put_image_yuy2(struct object_surface *obj_surface,
3298                const VARectangle *dst_rect,
3299                struct object_image *obj_image, uint8_t *image_data,
3300                const VARectangle *src_rect)
3301 {
3302     uint8_t *dst, *src;
3303     unsigned int tiling, swizzle;
3304
3305     if (!obj_surface->bo)
3306         return;
3307
3308     assert(obj_surface->fourcc);
3309     assert(dst_rect->width == src_rect->width);
3310     assert(dst_rect->height == src_rect->height);
3311     dri_bo_get_tiling(obj_surface->bo, &tiling, &swizzle);
3312
3313     if (tiling != I915_TILING_NONE)
3314         drm_intel_gem_bo_map_gtt(obj_surface->bo);
3315     else
3316         dri_bo_map(obj_surface->bo, 0);
3317
3318     if (!obj_surface->bo->virtual)
3319         return;
3320
3321     /* Both dest VA image and source surface have YUY2 format */
3322     dst = (uint8_t *)obj_surface->bo->virtual;
3323     src = image_data + obj_image->image.offsets[0];
3324
3325     /* YUYV packed plane */
3326     dst += dst_rect->y * obj_surface->width + dst_rect->x*2;
3327     src += src_rect->y * obj_image->image.pitches[0] + src_rect->x*2;
3328     memcpy_pic(dst, obj_surface->width*2,
3329                src, obj_image->image.pitches[0],
3330                src_rect->width*2, src_rect->height);
3331
3332     if (tiling != I915_TILING_NONE)
3333         drm_intel_gem_bo_unmap_gtt(obj_surface->bo);
3334     else
3335         dri_bo_unmap(obj_surface->bo);
3336 }
3337
3338
3339 static VAStatus
3340 i965_sw_putimage(VADriverContextP ctx,
3341                  VASurfaceID surface,
3342                  VAImageID image,
3343                  int src_x,
3344                  int src_y,
3345                  unsigned int src_width,
3346                  unsigned int src_height,
3347                  int dest_x,
3348                  int dest_y,
3349                  unsigned int dest_width,
3350                  unsigned int dest_height)
3351 {
3352     struct i965_driver_data *i965 = i965_driver_data(ctx);
3353     struct object_surface *obj_surface = SURFACE(surface);
3354
3355     if (!obj_surface)
3356         return VA_STATUS_ERROR_INVALID_SURFACE;
3357
3358     struct object_image *obj_image = IMAGE(image);
3359     if (!obj_image)
3360         return VA_STATUS_ERROR_INVALID_IMAGE;
3361
3362     if (src_x < 0 || src_y < 0)
3363         return VA_STATUS_ERROR_INVALID_PARAMETER;
3364     if (src_x + src_width > obj_image->image.width ||
3365         src_y + src_height > obj_image->image.height)
3366         return VA_STATUS_ERROR_INVALID_PARAMETER;
3367     if (dest_x < 0 || dest_y < 0)
3368         return VA_STATUS_ERROR_INVALID_PARAMETER;
3369     if (dest_x + dest_width > obj_surface->orig_width ||
3370         dest_y + dest_height > obj_surface->orig_height)
3371         return VA_STATUS_ERROR_INVALID_PARAMETER;
3372
3373     /* XXX: don't allow scaling */
3374     if (src_width != dest_width || src_height != dest_height)
3375         return VA_STATUS_ERROR_INVALID_PARAMETER;
3376
3377     if (obj_surface->fourcc) {
3378         /* Don't allow format mismatch */
3379         if (obj_surface->fourcc != obj_image->image.format.fourcc)
3380             return VA_STATUS_ERROR_INVALID_IMAGE_FORMAT;
3381     }
3382
3383     else {
3384         /* VA is surface not used for decoding, use same VA image format */
3385         i965_check_alloc_surface_bo(
3386             ctx,
3387             obj_surface,
3388             0, /* XXX: don't use tiled surface */
3389             obj_image->image.format.fourcc,
3390             get_sampling_from_fourcc (obj_image->image.format.fourcc));
3391     }
3392
3393     VAStatus va_status;
3394     void *image_data = NULL;
3395
3396     va_status = i965_MapBuffer(ctx, obj_image->image.buf, &image_data);
3397     if (va_status != VA_STATUS_SUCCESS)
3398         return va_status;
3399
3400     VARectangle src_rect, dest_rect;
3401     src_rect.x       = src_x;
3402     src_rect.y       = src_y;
3403     src_rect.width   = src_width;
3404     src_rect.height  = src_height;
3405     dest_rect.x      = dest_x;
3406     dest_rect.y      = dest_y;
3407     dest_rect.width  = dest_width;
3408     dest_rect.height = dest_height;
3409      
3410     switch (obj_image->image.format.fourcc) {
3411     case VA_FOURCC('Y','V','1','2'):
3412     case VA_FOURCC('I','4','2','0'):
3413         put_image_i420(obj_surface, &dest_rect, obj_image, image_data, &src_rect);
3414         break;
3415     case VA_FOURCC('N','V','1','2'):
3416         put_image_nv12(obj_surface, &dest_rect, obj_image, image_data, &src_rect);
3417         break;
3418     case VA_FOURCC('Y','U','Y','2'):
3419         put_image_yuy2(obj_surface, &dest_rect, obj_image, image_data, &src_rect);
3420         break;
3421     default:
3422         va_status = VA_STATUS_ERROR_OPERATION_FAILED;
3423         break;
3424     }
3425
3426     i965_UnmapBuffer(ctx, obj_image->image.buf);
3427     return va_status;
3428 }
3429
3430 static VAStatus 
3431 i965_hw_putimage(VADriverContextP ctx,
3432                  VASurfaceID surface,
3433                  VAImageID image,
3434                  int src_x,
3435                  int src_y,
3436                  unsigned int src_width,
3437                  unsigned int src_height,
3438                  int dest_x,
3439                  int dest_y,
3440                  unsigned int dest_width,
3441                  unsigned int dest_height)
3442 {
3443     struct i965_driver_data *i965 = i965_driver_data(ctx);
3444     struct object_surface *obj_surface = SURFACE(surface);
3445     struct object_image *obj_image = IMAGE(image);
3446     struct i965_surface src_surface, dst_surface;
3447     VAStatus va_status = VA_STATUS_SUCCESS;
3448     VARectangle src_rect, dst_rect;
3449
3450     if (!obj_surface)
3451         return VA_STATUS_ERROR_INVALID_SURFACE;
3452
3453     if (!obj_image || !obj_image->bo)
3454         return VA_STATUS_ERROR_INVALID_IMAGE;
3455
3456     if (src_x < 0 ||
3457         src_y < 0 ||
3458         src_x + src_width > obj_image->image.width ||
3459         src_y + src_height > obj_image->image.height)
3460         return VA_STATUS_ERROR_INVALID_PARAMETER;
3461
3462     if (dest_x < 0 ||
3463         dest_y < 0 ||
3464         dest_x + dest_width > obj_surface->orig_width ||
3465         dest_y + dest_height > obj_surface->orig_height)
3466         return VA_STATUS_ERROR_INVALID_PARAMETER;
3467
3468     if (!obj_surface->bo) {
3469         unsigned int tiling, swizzle;
3470         int surface_sampling = get_sampling_from_fourcc (obj_image->image.format.fourcc);;
3471         dri_bo_get_tiling(obj_image->bo, &tiling, &swizzle);
3472
3473         i965_check_alloc_surface_bo(ctx,
3474                                     obj_surface,
3475                                     !!tiling,
3476                                     obj_image->image.format.fourcc,
3477                                     surface_sampling);
3478     }
3479
3480     assert(obj_surface->fourcc);
3481
3482     src_surface.id = image;
3483     src_surface.type = I965_SURFACE_TYPE_IMAGE;
3484     src_surface.flags = I965_SURFACE_FLAG_FRAME;
3485     src_rect.x = src_x;
3486     src_rect.y = src_y;
3487     src_rect.width = src_width;
3488     src_rect.height = src_height;
3489
3490     dst_surface.id = surface;
3491     dst_surface.type = I965_SURFACE_TYPE_SURFACE;
3492     dst_surface.flags = I965_SURFACE_FLAG_FRAME;
3493     dst_rect.x = dest_x;
3494     dst_rect.y = dest_y;
3495     dst_rect.width = dest_width;
3496     dst_rect.height = dest_height;
3497
3498     va_status = i965_image_processing(ctx,
3499                                       &src_surface,
3500                                       &src_rect,
3501                                       &dst_surface,
3502                                       &dst_rect);
3503
3504     return  va_status;
3505 }
3506
3507 static VAStatus 
3508 i965_PutImage(VADriverContextP ctx,
3509               VASurfaceID surface,
3510               VAImageID image,
3511               int src_x,
3512               int src_y,
3513               unsigned int src_width,
3514               unsigned int src_height,
3515               int dest_x,
3516               int dest_y,
3517               unsigned int dest_width,
3518               unsigned int dest_height)
3519 {
3520     struct i965_driver_data *i965 = i965_driver_data(ctx);
3521     VAStatus va_status = VA_STATUS_SUCCESS;
3522
3523     if (HAS_ACCELERATED_PUTIMAGE(i965))
3524         va_status = i965_hw_putimage(ctx,
3525                                      surface,
3526                                      image,
3527                                      src_x,
3528                                      src_y,
3529                                      src_width,
3530                                      src_height,
3531                                      dest_x,
3532                                      dest_y,
3533                                      dest_width,
3534                                      dest_height);
3535     else 
3536         va_status = i965_sw_putimage(ctx,
3537                                      surface,
3538                                      image,
3539                                      src_x,
3540                                      src_y,
3541                                      src_width,
3542                                      src_height,
3543                                      dest_x,
3544                                      dest_y,
3545                                      dest_width,
3546                                      dest_height);
3547
3548     return va_status;
3549 }
3550
3551 VAStatus 
3552 i965_PutSurface(VADriverContextP ctx,
3553                 VASurfaceID surface,
3554                 void *draw, /* X Drawable */
3555                 short srcx,
3556                 short srcy,
3557                 unsigned short srcw,
3558                 unsigned short srch,
3559                 short destx,
3560                 short desty,
3561                 unsigned short destw,
3562                 unsigned short desth,
3563                 VARectangle *cliprects, /* client supplied clip list */
3564                 unsigned int number_cliprects, /* number of clip rects in the clip list */
3565                 unsigned int flags) /* de-interlacing flags */
3566 {
3567 #ifdef HAVE_VA_X11
3568     if (IS_VA_X11(ctx)) {
3569         VARectangle src_rect, dst_rect;
3570
3571         src_rect.x      = srcx;
3572         src_rect.y      = srcy;
3573         src_rect.width  = srcw;
3574         src_rect.height = srch;
3575
3576         dst_rect.x      = destx;
3577         dst_rect.y      = desty;
3578         dst_rect.width  = destw;
3579         dst_rect.height = desth;
3580
3581         return i965_put_surface_dri(ctx, surface, draw, &src_rect, &dst_rect,
3582                                     cliprects, number_cliprects, flags);
3583     }
3584 #endif
3585     return VA_STATUS_ERROR_UNIMPLEMENTED;
3586 }
3587
3588 VAStatus 
3589 i965_Terminate(VADriverContextP ctx)
3590 {
3591     struct i965_driver_data *i965 = i965_driver_data(ctx);
3592
3593     if (i965->batch)
3594         intel_batchbuffer_free(i965->batch);
3595
3596     _i965DestroyMutex(&i965->pp_mutex);
3597     _i965DestroyMutex(&i965->render_mutex);
3598
3599 #ifdef HAVE_VA_X11
3600     if (IS_VA_X11(ctx))
3601         i965_output_dri_terminate(ctx);
3602 #endif
3603
3604 #ifdef HAVE_VA_WAYLAND
3605     if (IS_VA_WAYLAND(ctx))
3606         i965_output_wayland_terminate(ctx);
3607 #endif
3608
3609     if (i965_render_terminate(ctx) == False)
3610         return VA_STATUS_ERROR_UNKNOWN;
3611
3612     if (i965_post_processing_terminate(ctx) == False)
3613         return VA_STATUS_ERROR_UNKNOWN;
3614
3615     i965_display_attributes_terminate(ctx);
3616
3617     i965_destroy_heap(&i965->buffer_heap, i965_destroy_buffer);
3618     i965_destroy_heap(&i965->image_heap, i965_destroy_image);
3619     i965_destroy_heap(&i965->subpic_heap, i965_destroy_subpic);
3620     i965_destroy_heap(&i965->surface_heap, i965_destroy_surface);
3621     i965_destroy_heap(&i965->context_heap, i965_destroy_context);
3622     i965_destroy_heap(&i965->config_heap, i965_destroy_config);
3623
3624     if (intel_driver_terminate(ctx) == False)
3625         return VA_STATUS_ERROR_UNKNOWN;
3626
3627     free(ctx->pDriverData);
3628     ctx->pDriverData = NULL;
3629
3630     return VA_STATUS_SUCCESS;
3631 }
3632
3633 static VAStatus
3634 i965_BufferInfo(
3635     VADriverContextP ctx,       /* in */
3636     VABufferID buf_id,          /* in */
3637     VABufferType *type,         /* out */
3638     unsigned int *size,         /* out */
3639     unsigned int *num_elements  /* out */
3640 )
3641 {
3642     struct i965_driver_data *i965 = NULL;
3643     struct object_buffer *obj_buffer = NULL;
3644
3645     i965 = i965_driver_data(ctx);
3646     obj_buffer = BUFFER(buf_id);
3647
3648     *type = obj_buffer->type;
3649     *size = obj_buffer->size_element;
3650     *num_elements = obj_buffer->num_elements;
3651
3652     return VA_STATUS_SUCCESS;
3653 }
3654
3655 static VAStatus
3656 i965_LockSurface(
3657     VADriverContextP ctx,           /* in */
3658     VASurfaceID surface,            /* in */
3659     unsigned int *fourcc,           /* out */
3660     unsigned int *luma_stride,      /* out */
3661     unsigned int *chroma_u_stride,  /* out */
3662     unsigned int *chroma_v_stride,  /* out */
3663     unsigned int *luma_offset,      /* out */
3664     unsigned int *chroma_u_offset,  /* out */
3665     unsigned int *chroma_v_offset,  /* out */
3666     unsigned int *buffer_name,      /* out */
3667     void **buffer                   /* out */
3668 )
3669 {
3670     VAStatus vaStatus = VA_STATUS_SUCCESS;
3671     struct i965_driver_data *i965 = i965_driver_data(ctx);
3672     struct object_surface *obj_surface = NULL;
3673     VAImage tmpImage;
3674
3675     assert(fourcc);
3676     assert(luma_stride);
3677     assert(chroma_u_stride);
3678     assert(chroma_v_stride);
3679     assert(luma_offset);
3680     assert(chroma_u_offset);
3681     assert(chroma_v_offset);
3682     assert(buffer_name);
3683     assert(buffer);
3684
3685     tmpImage.image_id = VA_INVALID_ID;
3686
3687     obj_surface = SURFACE(surface);
3688     if (obj_surface == NULL) {
3689         // Surface is absent.
3690         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
3691         goto error;
3692     }
3693
3694     // Lock functionality is absent now.
3695     if (obj_surface->locked_image_id != VA_INVALID_ID) {
3696         // Surface is locked already.
3697         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
3698         goto error;
3699     }
3700
3701     vaStatus = i965_DeriveImage(
3702         ctx,
3703         surface,
3704         &tmpImage);
3705     if (vaStatus != VA_STATUS_SUCCESS) {
3706         goto error;
3707     }
3708
3709     obj_surface->locked_image_id = tmpImage.image_id;
3710
3711     vaStatus = i965_MapBuffer(
3712         ctx,
3713         tmpImage.buf,
3714         buffer);
3715     if (vaStatus != VA_STATUS_SUCCESS) {
3716         goto error;
3717     }
3718
3719     *fourcc = tmpImage.format.fourcc;
3720     *luma_offset = tmpImage.offsets[0];
3721     *luma_stride = tmpImage.pitches[0];
3722     *chroma_u_offset = tmpImage.offsets[1];
3723     *chroma_u_stride = tmpImage.pitches[1];
3724     *chroma_v_offset = tmpImage.offsets[2];
3725     *chroma_v_stride = tmpImage.pitches[2];
3726     *buffer_name = tmpImage.buf;
3727
3728 error:
3729     if (vaStatus != VA_STATUS_SUCCESS) {
3730         buffer = NULL;
3731     }
3732
3733     return vaStatus;
3734 }
3735
3736 static VAStatus
3737 i965_UnlockSurface(
3738     VADriverContextP ctx,   /* in */
3739     VASurfaceID surface     /* in */
3740 )
3741 {
3742     VAStatus vaStatus = VA_STATUS_SUCCESS;
3743     struct i965_driver_data *i965 = i965_driver_data(ctx);
3744     struct object_image *locked_img = NULL;
3745     struct object_surface *obj_surface = NULL;
3746
3747     obj_surface = SURFACE(surface);
3748
3749     if (obj_surface == NULL) {
3750         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;   // Surface is absent
3751         return vaStatus;
3752     }
3753     if (obj_surface->locked_image_id == VA_INVALID_ID) {
3754         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;   // Surface is not locked
3755         return vaStatus;
3756     }
3757
3758     locked_img = IMAGE(obj_surface->locked_image_id);
3759     if (locked_img == NULL || (locked_img->image.image_id == VA_INVALID_ID)) {
3760         // Work image was deallocated before i965_UnlockSurface()
3761         vaStatus = VA_STATUS_ERROR_INVALID_PARAMETER;
3762         goto error;
3763     }
3764
3765     vaStatus = i965_UnmapBuffer(
3766         ctx,
3767         locked_img->image.buf);
3768     if (vaStatus != VA_STATUS_SUCCESS) {
3769         goto error;
3770     }
3771
3772     vaStatus = i965_DestroyImage(
3773         ctx,
3774         locked_img->image.image_id);
3775     if (vaStatus != VA_STATUS_SUCCESS) {
3776         goto error;
3777     }
3778
3779     locked_img->image.image_id = VA_INVALID_ID;
3780
3781  error:
3782     obj_surface->locked_image_id = VA_INVALID_ID;
3783
3784     return vaStatus;
3785 }
3786
3787 static VAStatus
3788 i965_GetSurfaceAttributes(
3789     VADriverContextP ctx,
3790     VAConfigID config,
3791     VASurfaceAttrib *attrib_list,
3792     unsigned int num_attribs
3793     )
3794 {
3795     VAStatus vaStatus = VA_STATUS_SUCCESS;
3796     struct i965_driver_data *i965 = i965_driver_data(ctx);
3797     struct object_config *obj_config;
3798     int i;
3799
3800     if (config == VA_INVALID_ID)
3801         return VA_STATUS_ERROR_INVALID_CONFIG;
3802
3803     obj_config = CONFIG(config);
3804
3805     if (obj_config == NULL)
3806         return VA_STATUS_ERROR_INVALID_CONFIG;
3807     
3808     if (attrib_list == NULL || num_attribs == 0)
3809         return VA_STATUS_ERROR_INVALID_PARAMETER;
3810
3811     for (i = 0; i < num_attribs; i++) {
3812         switch (attrib_list[i].type) {
3813         case VASurfaceAttribPixelFormat:
3814             attrib_list[i].value.type = VAGenericValueTypeInteger;
3815             attrib_list[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
3816
3817             if (attrib_list[i].value.value.i == 0) {
3818                 if (IS_G4X(i965->intel.device_id)) {
3819                     if (obj_config->profile == VAProfileMPEG2Simple ||
3820                         obj_config->profile == VAProfileMPEG2Main) {
3821                         attrib_list[i].value.value.i = VA_FOURCC('I', '4', '2', '0');
3822                     } else {
3823                         assert(0);
3824                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3825                     }
3826                 } else if (IS_IRONLAKE(i965->intel.device_id)) {
3827                     if (obj_config->profile == VAProfileMPEG2Simple ||
3828                         obj_config->profile == VAProfileMPEG2Main) {
3829                         attrib_list[i].value.value.i = VA_FOURCC('I', '4', '2', '0');
3830                     } else if (obj_config->profile == VAProfileH264Baseline ||
3831                                obj_config->profile == VAProfileH264Main ||
3832                                obj_config->profile == VAProfileH264High) {
3833                         attrib_list[i].value.value.i = VA_FOURCC('N', 'V', '1', '2');
3834                     } else if (obj_config->profile == VAProfileNone) {
3835                         attrib_list[i].value.value.i = VA_FOURCC('N', 'V', '1', '2');
3836                     } else {
3837                         assert(0);
3838                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3839                     }
3840                 } else if (IS_GEN6(i965->intel.device_id)) {
3841                     attrib_list[i].value.value.i = VA_FOURCC('N', 'V', '1', '2');                    
3842                 } else if (IS_GEN7(i965->intel.device_id)) {
3843                     if (obj_config->profile == VAProfileJPEGBaseline)
3844                         attrib_list[i].value.value.i = 0; /* internal format */
3845                     else
3846                         attrib_list[i].value.value.i = VA_FOURCC('N', 'V', '1', '2');
3847                 }
3848             } else {
3849                 if (IS_G4X(i965->intel.device_id)) {
3850                     if (obj_config->profile == VAProfileMPEG2Simple ||
3851                         obj_config->profile == VAProfileMPEG2Main) {
3852                         if (attrib_list[i].value.value.i != VA_FOURCC('I', '4', '2', '0')) {
3853                             attrib_list[i].value.value.i = 0;
3854                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3855                         }
3856                     } else {
3857                         assert(0);
3858                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3859                     }
3860                 } else if (IS_IRONLAKE(i965->intel.device_id)) {
3861                     if (obj_config->profile == VAProfileMPEG2Simple ||
3862                         obj_config->profile == VAProfileMPEG2Main) {
3863                         if (attrib_list[i].value.value.i != VA_FOURCC('I', '4', '2', '0')) {
3864                             attrib_list[i].value.value.i = 0;                            
3865                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3866                         }
3867                     } else if (obj_config->profile == VAProfileH264Baseline ||
3868                                obj_config->profile == VAProfileH264Main ||
3869                                obj_config->profile == VAProfileH264High) {
3870                         if (attrib_list[i].value.value.i != VA_FOURCC('N', 'V', '1', '2')) {
3871                             attrib_list[i].value.value.i = 0;
3872                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3873                         }
3874                     } else if (obj_config->profile == VAProfileNone) {
3875                         switch (attrib_list[i].value.value.i) {
3876                         case VA_FOURCC('N', 'V', '1', '2'):
3877                         case VA_FOURCC('I', '4', '2', '0'):
3878                         case VA_FOURCC('Y', 'V', '1', '2'):
3879                         case VA_FOURCC('Y', 'U', 'Y', '2'):
3880                         case VA_FOURCC('B', 'G', 'R', 'A'):
3881                         case VA_FOURCC('B', 'G', 'R', 'X'):
3882                         case VA_FOURCC('R', 'G', 'B', 'X'):
3883                         case VA_FOURCC('R', 'G', 'B', 'A'):
3884                             break;
3885                         default:
3886                             attrib_list[i].value.value.i = 0;                            
3887                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3888                             break;
3889                         }
3890                     } else {
3891                         assert(0);
3892                         attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3893                     }
3894                 } else if (IS_GEN6(i965->intel.device_id)) {
3895                     if (obj_config->entrypoint == VAEntrypointEncSlice ||
3896                         obj_config->entrypoint == VAEntrypointVideoProc) {
3897                         switch (attrib_list[i].value.value.i) {
3898                         case VA_FOURCC('N', 'V', '1', '2'):
3899                         case VA_FOURCC('I', '4', '2', '0'):
3900                         case VA_FOURCC('Y', 'V', '1', '2'):
3901                         case VA_FOURCC('Y', 'U', 'Y', '2'):
3902                         case VA_FOURCC('B', 'G', 'R', 'A'):
3903                         case VA_FOURCC('B', 'G', 'R', 'X'):
3904                         case VA_FOURCC('R', 'G', 'B', 'X'):
3905                         case VA_FOURCC('R', 'G', 'B', 'A'):
3906                             break;
3907                         default:
3908                             attrib_list[i].value.value.i = 0;                            
3909                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3910                             break;
3911                         }
3912                     } else {
3913                         if (attrib_list[i].value.value.i != VA_FOURCC('N', 'V', '1', '2')) {
3914                             attrib_list[i].value.value.i = 0;
3915                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3916                         }
3917                     }
3918                 } else if (IS_GEN7(i965->intel.device_id)) {
3919                     if (obj_config->entrypoint == VAEntrypointEncSlice ||
3920                         obj_config->entrypoint == VAEntrypointVideoProc) {
3921                         switch (attrib_list[i].value.value.i) {
3922                         case VA_FOURCC('N', 'V', '1', '2'):
3923                         case VA_FOURCC('I', '4', '2', '0'):
3924                         case VA_FOURCC('Y', 'V', '1', '2'):
3925                             break;
3926                         default:
3927                             attrib_list[i].value.value.i = 0;                            
3928                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3929                             break;
3930                         }
3931                     } else {
3932                         if (obj_config->profile == VAProfileJPEGBaseline) {
3933                             attrib_list[i].value.value.i = 0;   /* JPEG decoding always uses an internal format */
3934                             attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3935                         } else {
3936                             if (attrib_list[i].value.value.i != VA_FOURCC('N', 'V', '1', '2')) {
3937                                 attrib_list[i].value.value.i = 0;
3938                                 attrib_list[i].flags &= ~VA_SURFACE_ATTRIB_SETTABLE;
3939                             }
3940                         }
3941                     }
3942                 }
3943             }
3944
3945             break;
3946         case VASurfaceAttribMinWidth:
3947             /* FIXME: add support for it later */
3948             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3949             break;
3950         case VASurfaceAttribMaxWidth:
3951             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3952             break;
3953         case VASurfaceAttribMinHeight:
3954             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3955             break;
3956         case VASurfaceAttribMaxHeight:
3957             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3958             break;
3959         default:
3960             attrib_list[i].flags = VA_SURFACE_ATTRIB_NOT_SUPPORTED;
3961             break;
3962         }
3963     }
3964
3965     return vaStatus;
3966 }
3967
3968 /* 
3969  * Query video processing pipeline 
3970  */
3971 VAStatus i965_QueryVideoProcFilters(
3972     VADriverContextP    ctx,
3973     VAContextID         context,
3974     VAProcFilterType   *filters,
3975     unsigned int       *num_filters
3976     )
3977 {
3978     struct i965_driver_data *const i965 = i965_driver_data(ctx);
3979     unsigned int i = 0;
3980     
3981     if (HAS_VPP(i965)) {
3982         filters[i++] = VAProcFilterNoiseReduction;
3983         filters[i++] = VAProcFilterDeinterlacing;
3984     }
3985
3986     if(IS_HASWELL(i965->intel.device_id)){
3987         filters[i++] = VAProcFilterNone;
3988         filters[i++] = VAProcFilterSharpening;
3989         filters[i++] = VAProcFilterColorBalance;
3990         filters[i++] = VAProcFilterColorStandard;
3991     }
3992
3993     *num_filters = i;
3994
3995     return VA_STATUS_SUCCESS;
3996 }
3997
3998 VAStatus i965_QueryVideoProcFilterCaps(
3999     VADriverContextP    ctx,
4000     VAContextID         context,
4001     VAProcFilterType    type,
4002     void               *filter_caps,
4003     unsigned int       *num_filter_caps
4004     )
4005 {
4006     struct i965_driver_data *const i965 = i965_driver_data(ctx);
4007     unsigned int i = 0;
4008
4009     if (type == VAProcFilterNoiseReduction) {
4010         VAProcFilterCap *cap = filter_caps;
4011
4012         cap->range.min_value = 0.0;
4013         cap->range.max_value = 1.0;
4014         cap->range.default_value = 0.5;
4015         cap->range.step = 0.03125; /* 1.0 / 32 */
4016         i++;
4017     } else if (type == VAProcFilterDeinterlacing) {
4018         VAProcFilterCapDeinterlacing *cap = filter_caps;
4019         
4020         cap->type = VAProcDeinterlacingBob;
4021         i++;
4022         cap++;
4023     }
4024
4025     if(IS_HASWELL(i965->intel.device_id)){
4026        if(type == VAProcFilterColorBalance){
4027          VAProcFilterCapColorBalance *cap = filter_caps;
4028          cap->type = VAProcColorBalanceHue;
4029          cap->range.min_value = -180.0;
4030          cap->range.max_value = 180.0;
4031          cap->range.default_value = 0.0;
4032          cap->range.step = 1.0; 
4033          i++;
4034          cap ++; 
4035  
4036          cap->type = VAProcColorBalanceSaturation;
4037          cap->range.min_value = 0.0;
4038          cap->range.max_value = 10.0;
4039          cap->range.default_value = 0.0;
4040          cap->range.step = 0.1; 
4041          i++;
4042          cap ++; 
4043  
4044          cap->type = VAProcColorBalanceBrightness;
4045          cap->range.min_value = -100.0;
4046          cap->range.max_value = 100.0;
4047          cap->range.default_value = 0.0;
4048          cap->range.step = 1.0; 
4049          i++;
4050          cap ++; 
4051  
4052          cap->type = VAProcColorBalanceContrast;
4053          cap->range.min_value = 0.0;
4054          cap->range.max_value = 10.0;
4055          cap->range.default_value = 0.0;
4056          cap->range.step = 0.1; 
4057          i++;
4058          cap ++; 
4059       }
4060     }
4061
4062
4063     *num_filter_caps = i;
4064
4065     return VA_STATUS_SUCCESS;
4066 }
4067
4068 static VAProcColorStandardType vpp_input_color_standards[VAProcColorStandardCount] = {
4069     VAProcColorStandardBT601,
4070 };
4071
4072 static VAProcColorStandardType vpp_output_color_standards[VAProcColorStandardCount] = {
4073     VAProcColorStandardBT601,
4074 };
4075
4076 VAStatus i965_QueryVideoProcPipelineCaps(
4077     VADriverContextP ctx,
4078     VAContextID context,
4079     VABufferID *filters,
4080     unsigned int num_filters,
4081     VAProcPipelineCaps *pipeline_cap     /* out */
4082     )
4083 {
4084     struct i965_driver_data * const i965 = i965_driver_data(ctx);
4085     unsigned int i = 0;
4086
4087     pipeline_cap->pipeline_flags = 0;
4088     pipeline_cap->filter_flags = 0;
4089     pipeline_cap->num_forward_references = 0;
4090     pipeline_cap->num_backward_references = 0;
4091     pipeline_cap->num_input_color_standards = 1;
4092     pipeline_cap->input_color_standards = vpp_input_color_standards;
4093     pipeline_cap->num_output_color_standards = 1;
4094     pipeline_cap->output_color_standards = vpp_output_color_standards;
4095
4096     for (i = 0; i < num_filters; i++) {
4097         struct object_buffer *obj_buffer = BUFFER(filters[i]);
4098         VAProcFilterParameterBufferBase *base = (VAProcFilterParameterBufferBase *)obj_buffer->buffer_store->buffer;
4099
4100         if (base->type == VAProcFilterNoiseReduction) {
4101             VAProcFilterParameterBuffer *denoise = (VAProcFilterParameterBuffer *)base;
4102             (void)denoise;
4103         } else if (base->type == VAProcFilterDeinterlacing) {
4104             VAProcFilterParameterBufferDeinterlacing *deint = (VAProcFilterParameterBufferDeinterlacing *)base;
4105
4106             assert(deint->algorithm == VAProcDeinterlacingWeave ||
4107                    deint->algorithm == VAProcDeinterlacingBob);
4108         }
4109     }
4110
4111     return VA_STATUS_SUCCESS;
4112 }
4113
4114 VAStatus DLL_EXPORT
4115 VA_DRIVER_INIT_FUNC(VADriverContextP ctx);
4116
4117 VAStatus 
4118 VA_DRIVER_INIT_FUNC(  VADriverContextP ctx )
4119 {
4120     struct VADriverVTable * const vtable = ctx->vtable;
4121     struct VADriverVTableVPP * const vtable_vpp = ctx->vtable_vpp;
4122
4123     struct i965_driver_data *i965;
4124     int result;
4125
4126     ctx->version_major = VA_MAJOR_VERSION;
4127     ctx->version_minor = VA_MINOR_VERSION;
4128     ctx->max_profiles = I965_MAX_PROFILES;
4129     ctx->max_entrypoints = I965_MAX_ENTRYPOINTS;
4130     ctx->max_attributes = I965_MAX_CONFIG_ATTRIBUTES;
4131     ctx->max_image_formats = I965_MAX_IMAGE_FORMATS;
4132     ctx->max_subpic_formats = I965_MAX_SUBPIC_FORMATS;
4133     ctx->max_display_attributes = 1 + ARRAY_ELEMS(i965_display_attributes);
4134
4135     vtable->vaTerminate = i965_Terminate;
4136     vtable->vaQueryConfigEntrypoints = i965_QueryConfigEntrypoints;
4137     vtable->vaQueryConfigProfiles = i965_QueryConfigProfiles;
4138     vtable->vaQueryConfigEntrypoints = i965_QueryConfigEntrypoints;
4139     vtable->vaQueryConfigAttributes = i965_QueryConfigAttributes;
4140     vtable->vaCreateConfig = i965_CreateConfig;
4141     vtable->vaDestroyConfig = i965_DestroyConfig;
4142     vtable->vaGetConfigAttributes = i965_GetConfigAttributes;
4143     vtable->vaCreateSurfaces = i965_CreateSurfaces;
4144     vtable->vaDestroySurfaces = i965_DestroySurfaces;
4145     vtable->vaCreateContext = i965_CreateContext;
4146     vtable->vaDestroyContext = i965_DestroyContext;
4147     vtable->vaCreateBuffer = i965_CreateBuffer;
4148     vtable->vaBufferSetNumElements = i965_BufferSetNumElements;
4149     vtable->vaMapBuffer = i965_MapBuffer;
4150     vtable->vaUnmapBuffer = i965_UnmapBuffer;
4151     vtable->vaDestroyBuffer = i965_DestroyBuffer;
4152     vtable->vaBeginPicture = i965_BeginPicture;
4153     vtable->vaRenderPicture = i965_RenderPicture;
4154     vtable->vaEndPicture = i965_EndPicture;
4155     vtable->vaSyncSurface = i965_SyncSurface;
4156     vtable->vaQuerySurfaceStatus = i965_QuerySurfaceStatus;
4157     vtable->vaPutSurface = i965_PutSurface;
4158     vtable->vaQueryImageFormats = i965_QueryImageFormats;
4159     vtable->vaCreateImage = i965_CreateImage;
4160     vtable->vaDeriveImage = i965_DeriveImage;
4161     vtable->vaDestroyImage = i965_DestroyImage;
4162     vtable->vaSetImagePalette = i965_SetImagePalette;
4163     vtable->vaGetImage = i965_GetImage;
4164     vtable->vaPutImage = i965_PutImage;
4165     vtable->vaQuerySubpictureFormats = i965_QuerySubpictureFormats;
4166     vtable->vaCreateSubpicture = i965_CreateSubpicture;
4167     vtable->vaDestroySubpicture = i965_DestroySubpicture;
4168     vtable->vaSetSubpictureImage = i965_SetSubpictureImage;
4169     vtable->vaSetSubpictureChromakey = i965_SetSubpictureChromakey;
4170     vtable->vaSetSubpictureGlobalAlpha = i965_SetSubpictureGlobalAlpha;
4171     vtable->vaAssociateSubpicture = i965_AssociateSubpicture;
4172     vtable->vaDeassociateSubpicture = i965_DeassociateSubpicture;
4173     vtable->vaQueryDisplayAttributes = i965_QueryDisplayAttributes;
4174     vtable->vaGetDisplayAttributes = i965_GetDisplayAttributes;
4175     vtable->vaSetDisplayAttributes = i965_SetDisplayAttributes;
4176     vtable->vaBufferInfo = i965_BufferInfo;
4177     vtable->vaLockSurface = i965_LockSurface;
4178     vtable->vaUnlockSurface = i965_UnlockSurface;
4179     vtable->vaGetSurfaceAttributes = i965_GetSurfaceAttributes;
4180     vtable->vaCreateSurfaces2 = i965_CreateSurfaces2;
4181
4182     vtable_vpp->vaQueryVideoProcFilters = i965_QueryVideoProcFilters;
4183     vtable_vpp->vaQueryVideoProcFilterCaps = i965_QueryVideoProcFilterCaps;
4184     vtable_vpp->vaQueryVideoProcPipelineCaps = i965_QueryVideoProcPipelineCaps;
4185
4186     i965 = (struct i965_driver_data *)calloc(1, sizeof(*i965));
4187     assert(i965);
4188     ctx->pDriverData = (void *)i965;
4189
4190     result = object_heap_init(&i965->config_heap, 
4191                               sizeof(struct object_config), 
4192                               CONFIG_ID_OFFSET);
4193     assert(result == 0);
4194
4195     result = object_heap_init(&i965->context_heap, 
4196                               sizeof(struct object_context), 
4197                               CONTEXT_ID_OFFSET);
4198     assert(result == 0);
4199
4200     result = object_heap_init(&i965->surface_heap, 
4201                               sizeof(struct object_surface), 
4202                               SURFACE_ID_OFFSET);
4203     assert(result == 0);
4204
4205     result = object_heap_init(&i965->buffer_heap, 
4206                               sizeof(struct object_buffer), 
4207                               BUFFER_ID_OFFSET);
4208     assert(result == 0);
4209
4210     result = object_heap_init(&i965->image_heap, 
4211                               sizeof(struct object_image), 
4212                               IMAGE_ID_OFFSET);
4213     assert(result == 0);
4214
4215     result = object_heap_init(&i965->subpic_heap, 
4216                               sizeof(struct object_subpic), 
4217                               SUBPIC_ID_OFFSET);
4218     assert(result == 0);
4219
4220     sprintf(i965->va_vendor, "%s %s driver - %d.%d.%d",
4221             INTEL_STR_DRIVER_VENDOR,
4222             INTEL_STR_DRIVER_NAME,
4223             INTEL_DRIVER_MAJOR_VERSION,
4224             INTEL_DRIVER_MINOR_VERSION,
4225             INTEL_DRIVER_MICRO_VERSION);
4226
4227     if (INTEL_DRIVER_PRE_VERSION > 0) {
4228         const int len = strlen(i965->va_vendor);
4229         sprintf(&i965->va_vendor[len], ".pre%d", INTEL_DRIVER_PRE_VERSION);
4230     }
4231
4232     i965->current_context_id = VA_INVALID_ID;
4233
4234     ctx->str_vendor = i965->va_vendor;
4235     
4236     return i965_Init(ctx);
4237 }