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