OSDN Git Service

modetest: Unify buffer allocation
[android-x86/external-libdrm.git] / tests / modetest / modetest.c
1 /*
2  * DRM based mode setting test program
3  * Copyright 2008 Tungsten Graphics
4  *   Jakob Bornecrantz <jakob@tungstengraphics.com>
5  * Copyright 2008 Intel Corporation
6  *   Jesse Barnes <jesse.barnes@intel.com>
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24  * IN THE SOFTWARE.
25  */
26
27 /*
28  * This fairly simple test program dumps output in a similar format to the
29  * "xrandr" tool everyone knows & loves.  It's necessarily slightly different
30  * since the kernel separates outputs into encoder and connector structures,
31  * each with their own unique ID.  The program also allows test testing of the
32  * memory management and mode setting APIs by allowing the user to specify a
33  * connector and mode to use for mode setting.  If all works as expected, a
34  * blue background should be painted on the monitor attached to the specified
35  * connector after the selected mode is set.
36  *
37  * TODO: use cairo to write the mode info on the selected output once
38  *       the mode has been programmed, along with possible test patterns.
39  */
40 #include "config.h"
41
42 #include <assert.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <stdint.h>
46 #include <inttypes.h>
47 #include <unistd.h>
48 #include <string.h>
49 #include <errno.h>
50 #include <sys/poll.h>
51 #include <sys/time.h>
52
53 #include "xf86drm.h"
54 #include "xf86drmMode.h"
55 #include "drm_fourcc.h"
56 #include "libkms.h"
57
58 #ifdef HAVE_CAIRO
59 #include <math.h>
60 #include <cairo.h>
61 #endif
62
63 drmModeRes *resources;
64 int fd, modes;
65
66 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
67
68 struct type_name {
69         int type;
70         char *name;
71 };
72
73 #define type_name_fn(res) \
74 char * res##_str(int type) {                    \
75         unsigned int i;                                 \
76         for (i = 0; i < ARRAY_SIZE(res##_names); i++) { \
77                 if (res##_names[i].type == type)        \
78                         return res##_names[i].name;     \
79         }                                               \
80         return "(invalid)";                             \
81 }
82
83 struct type_name encoder_type_names[] = {
84         { DRM_MODE_ENCODER_NONE, "none" },
85         { DRM_MODE_ENCODER_DAC, "DAC" },
86         { DRM_MODE_ENCODER_TMDS, "TMDS" },
87         { DRM_MODE_ENCODER_LVDS, "LVDS" },
88         { DRM_MODE_ENCODER_TVDAC, "TVDAC" },
89 };
90
91 type_name_fn(encoder_type)
92
93 struct type_name connector_status_names[] = {
94         { DRM_MODE_CONNECTED, "connected" },
95         { DRM_MODE_DISCONNECTED, "disconnected" },
96         { DRM_MODE_UNKNOWNCONNECTION, "unknown" },
97 };
98
99 type_name_fn(connector_status)
100
101 struct type_name connector_type_names[] = {
102         { DRM_MODE_CONNECTOR_Unknown, "unknown" },
103         { DRM_MODE_CONNECTOR_VGA, "VGA" },
104         { DRM_MODE_CONNECTOR_DVII, "DVI-I" },
105         { DRM_MODE_CONNECTOR_DVID, "DVI-D" },
106         { DRM_MODE_CONNECTOR_DVIA, "DVI-A" },
107         { DRM_MODE_CONNECTOR_Composite, "composite" },
108         { DRM_MODE_CONNECTOR_SVIDEO, "s-video" },
109         { DRM_MODE_CONNECTOR_LVDS, "LVDS" },
110         { DRM_MODE_CONNECTOR_Component, "component" },
111         { DRM_MODE_CONNECTOR_9PinDIN, "9-pin DIN" },
112         { DRM_MODE_CONNECTOR_DisplayPort, "displayport" },
113         { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" },
114         { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" },
115         { DRM_MODE_CONNECTOR_TV, "TV" },
116         { DRM_MODE_CONNECTOR_eDP, "embedded displayport" },
117 };
118
119 type_name_fn(connector_type)
120
121 #define bit_name_fn(res)                                        \
122 char * res##_str(int type) {                                    \
123         int i;                                                  \
124         const char *sep = "";                                   \
125         for (i = 0; i < ARRAY_SIZE(res##_names); i++) {         \
126                 if (type & (1 << i)) {                          \
127                         printf("%s%s", sep, res##_names[i]);    \
128                         sep = ", ";                             \
129                 }                                               \
130         }                                                       \
131 }
132
133 static const char *mode_type_names[] = {
134         "builtin",
135         "clock_c",
136         "crtc_c",
137         "preferred",
138         "default",
139         "userdef",
140         "driver",
141 };
142
143 bit_name_fn(mode_type)
144
145 static const char *mode_flag_names[] = {
146         "phsync",
147         "nhsync",
148         "pvsync",
149         "nvsync",
150         "interlace",
151         "dblscan",
152         "csync",
153         "pcsync",
154         "ncsync",
155         "hskew",
156         "bcast",
157         "pixmux",
158         "dblclk",
159         "clkdiv2"
160 };
161
162 bit_name_fn(mode_flag)
163
164 void dump_encoders(void)
165 {
166         drmModeEncoder *encoder;
167         int i;
168
169         printf("Encoders:\n");
170         printf("id\tcrtc\ttype\tpossible crtcs\tpossible clones\t\n");
171         for (i = 0; i < resources->count_encoders; i++) {
172                 encoder = drmModeGetEncoder(fd, resources->encoders[i]);
173
174                 if (!encoder) {
175                         fprintf(stderr, "could not get encoder %i: %s\n",
176                                 resources->encoders[i], strerror(errno));
177                         continue;
178                 }
179                 printf("%d\t%d\t%s\t0x%08x\t0x%08x\n",
180                        encoder->encoder_id,
181                        encoder->crtc_id,
182                        encoder_type_str(encoder->encoder_type),
183                        encoder->possible_crtcs,
184                        encoder->possible_clones);
185                 drmModeFreeEncoder(encoder);
186         }
187         printf("\n");
188 }
189
190 void dump_mode(drmModeModeInfo *mode)
191 {
192         printf("  %s %d %d %d %d %d %d %d %d %d",
193                mode->name,
194                mode->vrefresh,
195                mode->hdisplay,
196                mode->hsync_start,
197                mode->hsync_end,
198                mode->htotal,
199                mode->vdisplay,
200                mode->vsync_start,
201                mode->vsync_end,
202                mode->vtotal);
203
204         printf(" flags: ");
205         mode_flag_str(mode->flags);
206         printf("; type: ");
207         mode_type_str(mode->type);
208         printf("\n");
209 }
210
211 static void
212 dump_blob(uint32_t blob_id)
213 {
214         uint32_t i;
215         unsigned char *blob_data;
216         drmModePropertyBlobPtr blob;
217
218         blob = drmModeGetPropertyBlob(fd, blob_id);
219         if (!blob)
220                 return;
221
222         blob_data = blob->data;
223
224         for (i = 0; i < blob->length; i++) {
225                 if (i % 16 == 0)
226                         printf("\n\t\t\t");
227                 printf("%.2hhx", blob_data[i]);
228         }
229         printf("\n");
230
231         drmModeFreePropertyBlob(blob);
232 }
233
234 static void
235 dump_prop(uint32_t prop_id, uint64_t value)
236 {
237         int i;
238         drmModePropertyPtr prop;
239
240         prop = drmModeGetProperty(fd, prop_id);
241
242         printf("\t%d", prop_id);
243         if (!prop) {
244                 printf("\n");
245                 return;
246         }
247
248         printf(" %s:\n", prop->name);
249
250         printf("\t\tflags:");
251         if (prop->flags & DRM_MODE_PROP_PENDING)
252                 printf(" pending");
253         if (prop->flags & DRM_MODE_PROP_RANGE)
254                 printf(" range");
255         if (prop->flags & DRM_MODE_PROP_IMMUTABLE)
256                 printf(" immutable");
257         if (prop->flags & DRM_MODE_PROP_ENUM)
258                 printf(" enum");
259         if (prop->flags & DRM_MODE_PROP_BITMASK)
260                 printf(" bitmask");
261         if (prop->flags & DRM_MODE_PROP_BLOB)
262                 printf(" blob");
263         printf("\n");
264
265         if (prop->flags & DRM_MODE_PROP_RANGE) {
266                 printf("\t\tvalues:");
267                 for (i = 0; i < prop->count_values; i++)
268                         printf(" %"PRIu64, prop->values[i]);
269                 printf("\n");
270         }
271
272         if (prop->flags & DRM_MODE_PROP_ENUM) {
273                 printf("\t\tenums:");
274                 for (i = 0; i < prop->count_enums; i++)
275                         printf(" %s=%llu", prop->enums[i].name,
276                                prop->enums[i].value);
277                 printf("\n");
278         } else if (prop->flags & DRM_MODE_PROP_BITMASK) {
279                 printf("\t\tvalues:");
280                 for (i = 0; i < prop->count_enums; i++)
281                         printf(" %s=0x%llx", prop->enums[i].name,
282                                (1LL << prop->enums[i].value));
283                 printf("\n");
284         } else {
285                 assert(prop->count_enums == 0);
286         }
287
288         if (prop->flags & DRM_MODE_PROP_BLOB) {
289                 printf("\t\tblobs:\n");
290                 for (i = 0; i < prop->count_blobs; i++)
291                         dump_blob(prop->blob_ids[i]);
292                 printf("\n");
293         } else {
294                 assert(prop->count_blobs == 0);
295         }
296
297         printf("\t\tvalue:");
298         if (prop->flags & DRM_MODE_PROP_BLOB)
299                 dump_blob(value);
300         else
301                 printf(" %"PRIu64"\n", value);
302
303         drmModeFreeProperty(prop);
304 }
305
306 void dump_connectors(void)
307 {
308         drmModeConnector *connector;
309         int i, j;
310
311         printf("Connectors:\n");
312         printf("id\tencoder\tstatus\t\ttype\tsize (mm)\tmodes\tencoders\n");
313         for (i = 0; i < resources->count_connectors; i++) {
314                 connector = drmModeGetConnector(fd, resources->connectors[i]);
315
316                 if (!connector) {
317                         fprintf(stderr, "could not get connector %i: %s\n",
318                                 resources->connectors[i], strerror(errno));
319                         continue;
320                 }
321
322                 printf("%d\t%d\t%s\t%s\t%dx%d\t\t%d\t",
323                        connector->connector_id,
324                        connector->encoder_id,
325                        connector_status_str(connector->connection),
326                        connector_type_str(connector->connector_type),
327                        connector->mmWidth, connector->mmHeight,
328                        connector->count_modes);
329
330                 for (j = 0; j < connector->count_encoders; j++)
331                         printf("%s%d", j > 0 ? ", " : "", connector->encoders[j]);
332                 printf("\n");
333
334                 if (connector->count_modes) {
335                         printf("  modes:\n");
336                         printf("\tname refresh (Hz) hdisp hss hse htot vdisp "
337                                "vss vse vtot)\n");
338                         for (j = 0; j < connector->count_modes; j++)
339                                 dump_mode(&connector->modes[j]);
340
341                         printf("  props:\n");
342                         for (j = 0; j < connector->count_props; j++)
343                                 dump_prop(connector->props[j],
344                                           connector->prop_values[j]);
345                 }
346
347                 drmModeFreeConnector(connector);
348         }
349         printf("\n");
350 }
351
352 void dump_crtcs(void)
353 {
354         drmModeCrtc *crtc;
355         drmModeObjectPropertiesPtr props;
356         int i;
357         uint32_t j;
358
359         printf("CRTCs:\n");
360         printf("id\tfb\tpos\tsize\n");
361         for (i = 0; i < resources->count_crtcs; i++) {
362                 crtc = drmModeGetCrtc(fd, resources->crtcs[i]);
363
364                 if (!crtc) {
365                         fprintf(stderr, "could not get crtc %i: %s\n",
366                                 resources->crtcs[i], strerror(errno));
367                         continue;
368                 }
369                 printf("%d\t%d\t(%d,%d)\t(%dx%d)\n",
370                        crtc->crtc_id,
371                        crtc->buffer_id,
372                        crtc->x, crtc->y,
373                        crtc->width, crtc->height);
374                 dump_mode(&crtc->mode);
375
376                 printf("  props:\n");
377                 props = drmModeObjectGetProperties(fd, crtc->crtc_id,
378                                                    DRM_MODE_OBJECT_CRTC);
379                 if (props) {
380                         for (j = 0; j < props->count_props; j++)
381                                 dump_prop(props->props[j],
382                                           props->prop_values[j]);
383                         drmModeFreeObjectProperties(props);
384                 } else {
385                         printf("\tcould not get crtc properties: %s\n",
386                                strerror(errno));
387                 }
388
389                 drmModeFreeCrtc(crtc);
390         }
391         printf("\n");
392 }
393
394 void dump_framebuffers(void)
395 {
396         drmModeFB *fb;
397         int i;
398
399         printf("Frame buffers:\n");
400         printf("id\tsize\tpitch\n");
401         for (i = 0; i < resources->count_fbs; i++) {
402                 fb = drmModeGetFB(fd, resources->fbs[i]);
403
404                 if (!fb) {
405                         fprintf(stderr, "could not get fb %i: %s\n",
406                                 resources->fbs[i], strerror(errno));
407                         continue;
408                 }
409                 printf("%u\t(%ux%u)\t%u\n",
410                        fb->fb_id,
411                        fb->width, fb->height,
412                        fb->pitch);
413
414                 drmModeFreeFB(fb);
415         }
416         printf("\n");
417 }
418
419 static void dump_planes(void)
420 {
421         drmModeObjectPropertiesPtr props;
422         drmModePlaneRes *plane_resources;
423         drmModePlane *ovr;
424         unsigned int i, j;
425
426         plane_resources = drmModeGetPlaneResources(fd);
427         if (!plane_resources) {
428                 fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
429                         strerror(errno));
430                 return;
431         }
432
433         printf("Planes:\n");
434         printf("id\tcrtc\tfb\tCRTC x,y\tx,y\tgamma size\n");
435         for (i = 0; i < plane_resources->count_planes; i++) {
436                 ovr = drmModeGetPlane(fd, plane_resources->planes[i]);
437                 if (!ovr) {
438                         fprintf(stderr, "drmModeGetPlane failed: %s\n",
439                                 strerror(errno));
440                         continue;
441                 }
442
443                 printf("%d\t%d\t%d\t%d,%d\t\t%d,%d\t%d\n",
444                        ovr->plane_id, ovr->crtc_id, ovr->fb_id,
445                        ovr->crtc_x, ovr->crtc_y, ovr->x, ovr->y,
446                        ovr->gamma_size);
447
448                 if (!ovr->count_formats)
449                         continue;
450
451                 printf("  formats:");
452                 for (j = 0; j < ovr->count_formats; j++)
453                         printf(" %4.4s", (char *)&ovr->formats[j]);
454                 printf("\n");
455
456                 printf("  props:\n");
457                 props = drmModeObjectGetProperties(fd, ovr->plane_id,
458                                                    DRM_MODE_OBJECT_PLANE);
459                 if (props) {
460                         for (j = 0; j < props->count_props; j++)
461                                 dump_prop(props->props[j],
462                                           props->prop_values[j]);
463                         drmModeFreeObjectProperties(props);
464                 } else {
465                         printf("\tcould not get plane properties: %s\n",
466                                strerror(errno));
467                 }
468
469                 drmModeFreePlane(ovr);
470         }
471         printf("\n");
472
473         drmModeFreePlaneResources(plane_resources);
474         return;
475 }
476
477 /*
478  * Mode setting with the kernel interfaces is a bit of a chore.
479  * First you have to find the connector in question and make sure the
480  * requested mode is available.
481  * Then you need to find the encoder attached to that connector so you
482  * can bind it with a free crtc.
483  */
484 struct connector {
485         uint32_t id;
486         char mode_str[64];
487         drmModeModeInfo *mode;
488         drmModeEncoder *encoder;
489         int crtc;
490         int pipe;
491         unsigned int fb_id[2], current_fb_id;
492         struct timeval start;
493
494         int swap_count;
495 };
496
497 struct plane {
498         uint32_t con_id;  /* the id of connector to bind to */
499         uint32_t w, h;
500         unsigned int fb_id;
501         char format_str[5]; /* need to leave room for terminating \0 */
502 };
503
504 static void
505 connector_find_mode(struct connector *c)
506 {
507         drmModeConnector *connector;
508         int i, j;
509
510         /* First, find the connector & mode */
511         c->mode = NULL;
512         for (i = 0; i < resources->count_connectors; i++) {
513                 connector = drmModeGetConnector(fd, resources->connectors[i]);
514
515                 if (!connector) {
516                         fprintf(stderr, "could not get connector %i: %s\n",
517                                 resources->connectors[i], strerror(errno));
518                         drmModeFreeConnector(connector);
519                         continue;
520                 }
521
522                 if (!connector->count_modes) {
523                         drmModeFreeConnector(connector);
524                         continue;
525                 }
526
527                 if (connector->connector_id != c->id) {
528                         drmModeFreeConnector(connector);
529                         continue;
530                 }
531
532                 for (j = 0; j < connector->count_modes; j++) {
533                         c->mode = &connector->modes[j];
534                         if (!strcmp(c->mode->name, c->mode_str))
535                                 break;
536                 }
537
538                 /* Found it, break out */
539                 if (c->mode)
540                         break;
541
542                 drmModeFreeConnector(connector);
543         }
544
545         if (!c->mode) {
546                 fprintf(stderr, "failed to find mode \"%s\"\n", c->mode_str);
547                 return;
548         }
549
550         /* Now get the encoder */
551         for (i = 0; i < resources->count_encoders; i++) {
552                 c->encoder = drmModeGetEncoder(fd, resources->encoders[i]);
553
554                 if (!c->encoder) {
555                         fprintf(stderr, "could not get encoder %i: %s\n",
556                                 resources->encoders[i], strerror(errno));
557                         drmModeFreeEncoder(c->encoder);
558                         continue;
559                 }
560
561                 if (c->encoder->encoder_id  == connector->encoder_id)
562                         break;
563
564                 drmModeFreeEncoder(c->encoder);
565         }
566
567         if (c->crtc == -1)
568                 c->crtc = c->encoder->crtc_id;
569
570         /* and figure out which crtc index it is: */
571         for (i = 0; i < resources->count_crtcs; i++) {
572                 if (c->crtc == resources->crtcs[i]) {
573                         c->pipe = i;
574                         break;
575                 }
576         }
577
578 }
579
580 static struct kms_bo *
581 allocate_buffer(struct kms_driver *kms,
582                 int width, int height, int *stride)
583 {
584         struct kms_bo *bo;
585         unsigned bo_attribs[] = {
586                 KMS_WIDTH,   0,
587                 KMS_HEIGHT,  0,
588                 KMS_BO_TYPE, KMS_BO_TYPE_SCANOUT_X8R8G8B8,
589                 KMS_TERMINATE_PROP_LIST
590         };
591         int ret;
592
593         bo_attribs[1] = width;
594         bo_attribs[3] = height;
595
596         ret = kms_bo_create(kms, bo_attribs, &bo);
597         if (ret) {
598                 fprintf(stderr, "failed to alloc buffer: %s\n",
599                         strerror(-ret));
600                 return NULL;
601         }
602
603         ret = kms_bo_get_prop(bo, KMS_PITCH, stride);
604         if (ret) {
605                 fprintf(stderr, "failed to retreive buffer stride: %s\n",
606                         strerror(-ret));
607                 kms_bo_destroy(&bo);
608                 return NULL;
609         }
610
611         return bo;
612 }
613
614 static void
615 make_pwetty(void *data, int width, int height, int stride)
616 {
617 #ifdef HAVE_CAIRO
618         cairo_surface_t *surface;
619         cairo_t *cr;
620         int x, y;
621
622         surface = cairo_image_surface_create_for_data(data,
623                                                       CAIRO_FORMAT_ARGB32,
624                                                       width, height,
625                                                       stride);
626         cr = cairo_create(surface);
627         cairo_surface_destroy(surface);
628
629         cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);
630         for (x = 0; x < width; x += 250)
631                 for (y = 0; y < height; y += 250) {
632                         char buf[64];
633
634                         cairo_move_to(cr, x, y - 20);
635                         cairo_line_to(cr, x, y + 20);
636                         cairo_move_to(cr, x - 20, y);
637                         cairo_line_to(cr, x + 20, y);
638                         cairo_new_sub_path(cr);
639                         cairo_arc(cr, x, y, 10, 0, M_PI * 2);
640                         cairo_set_line_width(cr, 4);
641                         cairo_set_source_rgb(cr, 0, 0, 0);
642                         cairo_stroke_preserve(cr);
643                         cairo_set_source_rgb(cr, 1, 1, 1);
644                         cairo_set_line_width(cr, 2);
645                         cairo_stroke(cr);
646
647                         snprintf(buf, sizeof buf, "%d, %d", x, y);
648                         cairo_move_to(cr, x + 20, y + 20);
649                         cairo_text_path(cr, buf);
650                         cairo_set_source_rgb(cr, 0, 0, 0);
651                         cairo_stroke_preserve(cr);
652                         cairo_set_source_rgb(cr, 1, 1, 1);
653                         cairo_fill(cr);
654                 }
655
656         cairo_destroy(cr);
657 #endif
658 }
659
660 /* -----------------------------------------------------------------------------
661  * Buffers management
662  */
663
664 /* swap these for big endian.. */
665 #define RED   2
666 #define GREEN 1
667 #define BLUE  0
668
669 struct format_name {
670         unsigned int format;
671         const char *name;
672 };
673
674 static const struct format_name format_names[] = {
675         { DRM_FORMAT_YUYV, "YUYV" },
676         { DRM_FORMAT_NV12, "NV12" },
677         { DRM_FORMAT_YVU420, "YV12" },
678         { DRM_FORMAT_XRGB1555, "XR15" },
679         { DRM_FORMAT_XRGB8888, "XR24" },
680         { DRM_FORMAT_ARGB1555, "AR15" },
681 };
682
683 unsigned int format_fourcc(const char *name)
684 {
685         unsigned int i;
686         for (i = 0; i < ARRAY_SIZE(format_names); i++) {
687                 if (!strcmp(format_names[i].name, name))
688                         return format_names[i].format;
689         }
690         return 0;
691 }
692
693 static void
694 fill420(unsigned char *y, unsigned char *u, unsigned char *v,
695                 int cs /*chroma pixel stride */,
696                 int n, int width, int height, int stride)
697 {
698         int i, j;
699
700         /* paint the buffer with colored tiles, in blocks of 2x2 */
701         for (j = 0; j < height; j+=2) {
702                 unsigned char *y1p = y + j * stride;
703                 unsigned char *y2p = y1p + stride;
704                 unsigned char *up = u + (j/2) * stride * cs / 2;
705                 unsigned char *vp = v + (j/2) * stride * cs / 2;
706
707                 for (i = 0; i < width; i+=2) {
708                         div_t d = div(n+i+j, width);
709                         uint32_t rgb = 0x00130502 * (d.quot >> 6) + 0x000a1120 * (d.rem >> 6);
710                         unsigned char *rgbp = (unsigned char *)&rgb;
711                         unsigned char y = (0.299 * rgbp[RED]) + (0.587 * rgbp[GREEN]) + (0.114 * rgbp[BLUE]);
712
713                         *(y2p++) = *(y1p++) = y;
714                         *(y2p++) = *(y1p++) = y;
715
716                         *up = (rgbp[BLUE] - y) * 0.565 + 128;
717                         *vp = (rgbp[RED] - y) * 0.713 + 128;
718                         up += cs;
719                         vp += cs;
720                 }
721         }
722 }
723
724 static void
725 fill422(unsigned char *virtual, int n, int width, int height, int stride)
726 {
727         int i, j;
728         /* paint the buffer with colored tiles */
729         for (j = 0; j < height; j++) {
730                 uint8_t *ptr = (uint8_t*)((char*)virtual + j * stride);
731                 for (i = 0; i < width; i++) {
732                         div_t d = div(n+i+j, width);
733                         uint32_t rgb = 0x00130502 * (d.quot >> 6) + 0x000a1120 * (d.rem >> 6);
734                         unsigned char *rgbp = (unsigned char *)&rgb;
735                         unsigned char y = (0.299 * rgbp[RED]) + (0.587 * rgbp[GREEN]) + (0.114 * rgbp[BLUE]);
736
737                         *(ptr++) = y;
738                         *(ptr++) = (rgbp[BLUE] - y) * 0.565 + 128;
739                         *(ptr++) = y;
740                         *(ptr++) = (rgbp[RED] - y) * 0.713 + 128;
741                 }
742         }
743 }
744
745 static void
746 fill1555(unsigned char *virtual, int n, int width, int height, int stride)
747 {
748         int i, j;
749         /* paint the buffer with colored tiles */
750         for (j = 0; j < height; j++) {
751                 uint16_t *ptr = (uint16_t*)((char*)virtual + j * stride);
752                 for (i = 0; i < width; i++) {
753                         div_t d = div(n+i+j, width);
754                         uint32_t rgb = 0x00130502 * (d.quot >> 6) + 0x000a1120 * (d.rem >> 6);
755                         unsigned char *rgbp = (unsigned char *)&rgb;
756
757                         *(ptr++) = 0x8000 |
758                                         (rgbp[RED] >> 3) << 10 |
759                                         (rgbp[GREEN] >> 3) << 5 |
760                                         (rgbp[BLUE] >> 3);
761                 }
762         }
763 }
764
765 static void
766 fill8888(unsigned char *virtual, int width, int height, int stride)
767 {
768         int i, j;
769         /* paint the buffer with colored tiles */
770         for (j = 0; j < height; j++) {
771                 uint32_t *ptr = (uint32_t*)((char*)virtual + j * stride);
772                 for (i = 0; i < width; i++) {
773                         div_t d = div(i, width);
774                         ptr[i] =
775                                 0x00130502 * (d.quot >> 6) +
776                                 0x000a1120 * (d.rem >> 6);
777                 }
778         }
779
780         make_pwetty(virtual, width, height, stride);
781 }
782
783 static void
784 fill_grey(unsigned char *virtual, int width, int height, int stride)
785 {
786         memset(virtual, 0x77, stride * height);
787 }
788
789 static struct kms_bo *
790 create_test_buffer(struct kms_driver *kms, unsigned int format,
791                    int width, int height, int handles[4],
792                    int pitches[4], int offsets[4], int grey)
793 {
794         struct kms_bo *bo;
795         int ret, stride;
796         void *virtual;
797
798         bo = allocate_buffer(kms, width, height, &pitches[0]);
799         if (!bo)
800                 return NULL;
801
802         ret = kms_bo_map(bo, &virtual);
803         if (ret) {
804                 fprintf(stderr, "failed to map buffer: %s\n",
805                         strerror(-ret));
806                 kms_bo_destroy(&bo);
807                 return NULL;
808         }
809
810         /* just testing a limited # of formats to test single
811          * and multi-planar path.. would be nice to add more..
812          */
813         switch (format) {
814         case DRM_FORMAT_YUYV:
815                 pitches[0] = width * 2;
816                 offsets[0] = 0;
817                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
818
819                 fill422(virtual, 0, width, height, pitches[0]);
820                 break;
821
822         case DRM_FORMAT_NV12:
823                 pitches[0] = width;
824                 offsets[0] = 0;
825                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
826                 pitches[1] = width;
827                 offsets[1] = width * height;
828                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[1]);
829
830                 fill420(virtual, virtual+offsets[1], virtual+offsets[1]+1,
831                                 2, 0, width, height, pitches[0]);
832                 break;
833
834         case DRM_FORMAT_YVU420:
835                 pitches[0] = width;
836                 offsets[0] = 0;
837                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
838                 pitches[1] = width / 2;
839                 offsets[1] = width * height;
840                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[1]);
841                 pitches[2] = width / 2;
842                 offsets[2] = offsets[1] + (width * height) / 4;
843                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[2]);
844
845                 fill420(virtual, virtual+offsets[1], virtual+offsets[2],
846                                 1, 0, width, height, pitches[0]);
847                 break;
848
849         case DRM_FORMAT_XRGB1555:
850                 pitches[0] = width * 2;
851                 offsets[0] = 0;
852                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
853
854                 fill1555(virtual, 0, width, height, pitches[0]);
855                 break;
856
857         case DRM_FORMAT_XRGB8888:
858                 pitches[0] = width * 4;
859                 offsets[0] = 0;
860                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
861
862                 if (grey)
863                         fill_grey(virtual, width, height, pitches[0]);
864                 else
865                         fill8888(virtual, width, height, pitches[0]);
866                 break;
867
868         case DRM_FORMAT_ARGB1555:
869                 pitches[0] = width * 2;
870                 offsets[0] = 0;
871                 kms_bo_get_prop(bo, KMS_HANDLE, &handles[0]);
872
873                 fill1555(virtual, 0, width, height, pitches[0]);
874                 break;
875         }
876
877         kms_bo_unmap(bo);
878
879         return bo;
880 }
881
882 /* -------------------------------------------------------------------------- */
883
884 void
885 page_flip_handler(int fd, unsigned int frame,
886                   unsigned int sec, unsigned int usec, void *data)
887 {
888         struct connector *c;
889         unsigned int new_fb_id;
890         struct timeval end;
891         double t;
892
893         c = data;
894         if (c->current_fb_id == c->fb_id[0])
895                 new_fb_id = c->fb_id[1];
896         else
897                 new_fb_id = c->fb_id[0];
898
899         drmModePageFlip(fd, c->crtc, new_fb_id,
900                         DRM_MODE_PAGE_FLIP_EVENT, c);
901         c->current_fb_id = new_fb_id;
902         c->swap_count++;
903         if (c->swap_count == 60) {
904                 gettimeofday(&end, NULL);
905                 t = end.tv_sec + end.tv_usec * 1e-6 -
906                         (c->start.tv_sec + c->start.tv_usec * 1e-6);
907                 fprintf(stderr, "freq: %.02fHz\n", c->swap_count / t);
908                 c->swap_count = 0;
909                 c->start = end;
910         }
911 }
912
913 static int
914 set_plane(struct kms_driver *kms, struct connector *c, struct plane *p)
915 {
916         drmModePlaneRes *plane_resources;
917         drmModePlane *ovr;
918         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
919         uint32_t plane_id = 0;
920         struct kms_bo *plane_bo;
921         uint32_t plane_flags = 0, format;
922         int ret, crtc_x, crtc_y, crtc_w, crtc_h;
923         unsigned int i;
924
925         format = format_fourcc(p->format_str);
926         if (format == 0) {
927                 fprintf(stderr, "Unknown format: %s\n", p->format_str);
928                 return -1;
929         }
930
931         /* find an unused plane which can be connected to our crtc */
932         plane_resources = drmModeGetPlaneResources(fd);
933         if (!plane_resources) {
934                 fprintf(stderr, "drmModeGetPlaneResources failed: %s\n",
935                         strerror(errno));
936                 return -1;
937         }
938
939         for (i = 0; i < plane_resources->count_planes && !plane_id; i++) {
940                 ovr = drmModeGetPlane(fd, plane_resources->planes[i]);
941                 if (!ovr) {
942                         fprintf(stderr, "drmModeGetPlane failed: %s\n",
943                                 strerror(errno));
944                         return -1;
945                 }
946
947                 if ((ovr->possible_crtcs & (1 << c->pipe)) && !ovr->crtc_id)
948                         plane_id = ovr->plane_id;
949
950                 drmModeFreePlane(ovr);
951         }
952
953         fprintf(stderr, "testing %dx%d@%s overlay plane\n",
954                         p->w, p->h, p->format_str);
955
956         if (!plane_id) {
957                 fprintf(stderr, "failed to find plane!\n");
958                 return -1;
959         }
960
961         plane_bo = create_test_buffer(kms, format, p->w, p->h, handles,
962                                       pitches, offsets, 0);
963         if (plane_bo == NULL)
964                 return -1;
965
966         /* just use single plane format for now.. */
967         if (drmModeAddFB2(fd, p->w, p->h, format,
968                         handles, pitches, offsets, &p->fb_id, plane_flags)) {
969                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
970                 return -1;
971         }
972
973         /* ok, boring.. but for now put in middle of screen: */
974         crtc_x = c->mode->hdisplay / 3;
975         crtc_y = c->mode->vdisplay / 3;
976         crtc_w = crtc_x;
977         crtc_h = crtc_y;
978
979         /* note src coords (last 4 args) are in Q16 format */
980         if (drmModeSetPlane(fd, plane_id, c->crtc, p->fb_id,
981                             plane_flags, crtc_x, crtc_y, crtc_w, crtc_h,
982                             0, 0, p->w << 16, p->h << 16)) {
983                 fprintf(stderr, "failed to enable plane: %s\n",
984                         strerror(errno));
985                 return -1;
986         }
987
988         return 0;
989 }
990
991 static void
992 set_mode(struct connector *c, int count, struct plane *p, int plane_count,
993                 int page_flip)
994 {
995         struct kms_driver *kms;
996         struct kms_bo *bo, *other_bo;
997         unsigned int fb_id, other_fb_id;
998         int i, j, ret, width, height, x;
999         uint32_t handles[4], pitches[4], offsets[4] = {0}; /* we only use [0] */
1000         drmEventContext evctx;
1001
1002         width = 0;
1003         height = 0;
1004         for (i = 0; i < count; i++) {
1005                 connector_find_mode(&c[i]);
1006                 if (c[i].mode == NULL)
1007                         continue;
1008                 width += c[i].mode->hdisplay;
1009                 if (height < c[i].mode->vdisplay)
1010                         height = c[i].mode->vdisplay;
1011         }
1012
1013         ret = kms_create(fd, &kms);
1014         if (ret) {
1015                 fprintf(stderr, "failed to create kms driver: %s\n",
1016                         strerror(-ret));
1017                 return;
1018         }
1019
1020         bo = create_test_buffer(kms, DRM_FORMAT_XRGB8888, width, height, handles,
1021                                 pitches, offsets, 0);
1022         if (bo == NULL)
1023                 return;
1024
1025         ret = drmModeAddFB(fd, width, height, 24, 32, pitches[0], handles[0], &fb_id);
1026         if (ret) {
1027                 fprintf(stderr, "failed to add fb (%ux%u): %s\n",
1028                         width, height, strerror(errno));
1029                 return;
1030         }
1031
1032         x = 0;
1033         for (i = 0; i < count; i++) {
1034                 if (c[i].mode == NULL)
1035                         continue;
1036
1037                 printf("setting mode %s on connector %d, crtc %d\n",
1038                        c[i].mode_str, c[i].id, c[i].crtc);
1039
1040                 ret = drmModeSetCrtc(fd, c[i].crtc, fb_id, x, 0,
1041                                      &c[i].id, 1, c[i].mode);
1042
1043                 /* XXX: Actually check if this is needed */
1044                 drmModeDirtyFB(fd, fb_id, NULL, 0);
1045
1046                 x += c[i].mode->hdisplay;
1047
1048                 if (ret) {
1049                         fprintf(stderr, "failed to set mode: %s\n", strerror(errno));
1050                         return;
1051                 }
1052
1053                 /* if we have a plane/overlay to show, set that up now: */
1054                 for (j = 0; j < plane_count; j++)
1055                         if (p[j].con_id == c[i].id)
1056                                 if (set_plane(kms, &c[i], &p[j]))
1057                                         return;
1058         }
1059
1060         if (!page_flip)
1061                 return;
1062         
1063         other_bo = create_test_buffer(kms, DRM_FORMAT_XRGB8888, width, height, handles,
1064                                       pitches, offsets, 1);
1065         if (other_bo == NULL)
1066                 return;
1067
1068         ret = drmModeAddFB(fd, width, height, 32, 32, pitches[0], handles[0],
1069                            &other_fb_id);
1070         if (ret) {
1071                 fprintf(stderr, "failed to add fb: %s\n", strerror(errno));
1072                 return;
1073         }
1074
1075         for (i = 0; i < count; i++) {
1076                 if (c[i].mode == NULL)
1077                         continue;
1078
1079                 ret = drmModePageFlip(fd, c[i].crtc, other_fb_id,
1080                                       DRM_MODE_PAGE_FLIP_EVENT, &c[i]);
1081                 if (ret) {
1082                         fprintf(stderr, "failed to page flip: %s\n", strerror(errno));
1083                         return;
1084                 }
1085                 gettimeofday(&c[i].start, NULL);
1086                 c[i].swap_count = 0;
1087                 c[i].fb_id[0] = fb_id;
1088                 c[i].fb_id[1] = other_fb_id;
1089                 c[i].current_fb_id = other_fb_id;
1090         }
1091
1092         memset(&evctx, 0, sizeof evctx);
1093         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1094         evctx.vblank_handler = NULL;
1095         evctx.page_flip_handler = page_flip_handler;
1096         
1097         while (1) {
1098 #if 0
1099                 struct pollfd pfd[2];
1100
1101                 pfd[0].fd = 0;
1102                 pfd[0].events = POLLIN;
1103                 pfd[1].fd = fd;
1104                 pfd[1].events = POLLIN;
1105
1106                 if (poll(pfd, 2, -1) < 0) {
1107                         fprintf(stderr, "poll error\n");
1108                         break;
1109                 }
1110
1111                 if (pfd[0].revents)
1112                         break;
1113 #else
1114                 struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
1115                 fd_set fds;
1116                 int ret;
1117
1118                 FD_ZERO(&fds);
1119                 FD_SET(0, &fds);
1120                 FD_SET(fd, &fds);
1121                 ret = select(fd + 1, &fds, NULL, NULL, &timeout);
1122
1123                 if (ret <= 0) {
1124                         fprintf(stderr, "select timed out or error (ret %d)\n",
1125                                 ret);
1126                         continue;
1127                 } else if (FD_ISSET(0, &fds)) {
1128                         break;
1129                 }
1130 #endif
1131
1132                 drmHandleEvent(fd, &evctx);
1133         }
1134
1135         kms_bo_destroy(&bo);
1136         kms_bo_destroy(&other_bo);
1137         kms_destroy(&kms);
1138 }
1139
1140 extern char *optarg;
1141 extern int optind, opterr, optopt;
1142 static char optstr[] = "ecpmfs:P:v";
1143
1144 void usage(char *name)
1145 {
1146         fprintf(stderr, "usage: %s [-ecpmf]\n", name);
1147         fprintf(stderr, "\t-e\tlist encoders\n");
1148         fprintf(stderr, "\t-c\tlist connectors\n");
1149         fprintf(stderr, "\t-p\tlist CRTCs and planes (pipes)\n");
1150         fprintf(stderr, "\t-m\tlist modes\n");
1151         fprintf(stderr, "\t-f\tlist framebuffers\n");
1152         fprintf(stderr, "\t-v\ttest vsynced page flipping\n");
1153         fprintf(stderr, "\t-s <connector_id>:<mode>\tset a mode\n");
1154         fprintf(stderr, "\t-s <connector_id>@<crtc_id>:<mode>\tset a mode\n");
1155         fprintf(stderr, "\t-P <connector_id>:<w>x<h>\tset a plane\n");
1156         fprintf(stderr, "\t-P <connector_id>:<w>x<h>@<format>\tset a plane\n");
1157         fprintf(stderr, "\n\tDefault is to dump all info.\n");
1158         exit(0);
1159 }
1160
1161 #define dump_resource(res) if (res) dump_##res()
1162
1163 static int page_flipping_supported(void)
1164 {
1165         /*FIXME: generic ioctl needed? */
1166         return 1;
1167 #if 0
1168         int ret, value;
1169         struct drm_i915_getparam gp;
1170
1171         gp.param = I915_PARAM_HAS_PAGEFLIPPING;
1172         gp.value = &value;
1173
1174         ret = drmCommandWriteRead(fd, DRM_I915_GETPARAM, &gp, sizeof(gp));
1175         if (ret) {
1176                 fprintf(stderr, "drm_i915_getparam: %m\n");
1177                 return 0;
1178         }
1179
1180         return *gp.value;
1181 #endif
1182 }
1183
1184 int main(int argc, char **argv)
1185 {
1186         int c;
1187         int encoders = 0, connectors = 0, crtcs = 0, planes = 0, framebuffers = 0;
1188         int test_vsync = 0;
1189         char *modules[] = { "i915", "radeon", "nouveau", "vmwgfx", "omapdrm", "exynos" };
1190         unsigned int i;
1191         int count = 0, plane_count = 0;
1192         struct connector con_args[2];
1193         struct plane plane_args[2] = {0};
1194         
1195         opterr = 0;
1196         while ((c = getopt(argc, argv, optstr)) != -1) {
1197                 switch (c) {
1198                 case 'e':
1199                         encoders = 1;
1200                         break;
1201                 case 'c':
1202                         connectors = 1;
1203                         break;
1204                 case 'p':
1205                         crtcs = 1;
1206                         planes = 1;
1207                         break;
1208                 case 'm':
1209                         modes = 1;
1210                         break;
1211                 case 'f':
1212                         framebuffers = 1;
1213                         break;
1214                 case 'v':
1215                         test_vsync = 1;
1216                         break;
1217                 case 's':
1218                         con_args[count].crtc = -1;
1219                         if (sscanf(optarg, "%d:%64s",
1220                                    &con_args[count].id,
1221                                    con_args[count].mode_str) != 2 &&
1222                             sscanf(optarg, "%d@%d:%64s",
1223                                    &con_args[count].id,
1224                                    &con_args[count].crtc,
1225                                    con_args[count].mode_str) != 3)
1226                                 usage(argv[0]);
1227                         count++;                                      
1228                         break;
1229                 case 'P':
1230                         strcpy(plane_args[plane_count].format_str, "XR24");
1231                         if (sscanf(optarg, "%d:%dx%d@%4s",
1232                                         &plane_args[plane_count].con_id,
1233                                         &plane_args[plane_count].w,
1234                                         &plane_args[plane_count].h,
1235                                         plane_args[plane_count].format_str) != 4 &&
1236                                 sscanf(optarg, "%d:%dx%d",
1237                                         &plane_args[plane_count].con_id,
1238                                         &plane_args[plane_count].w,
1239                                         &plane_args[plane_count].h) != 3)
1240                                 usage(argv[0]);
1241                         plane_count++;
1242                         break;
1243                 default:
1244                         usage(argv[0]);
1245                         break;
1246                 }
1247         }
1248
1249         if (argc == 1)
1250                 encoders = connectors = crtcs = planes = modes = framebuffers = 1;
1251
1252         for (i = 0; i < ARRAY_SIZE(modules); i++) {
1253                 printf("trying to load module %s...", modules[i]);
1254                 fd = drmOpen(modules[i], NULL);
1255                 if (fd < 0) {
1256                         printf("failed.\n");
1257                 } else {
1258                         printf("success.\n");
1259                         break;
1260                 }
1261         }
1262
1263         if (test_vsync && !page_flipping_supported()) {
1264                 fprintf(stderr, "page flipping not supported by drm.\n");
1265                 return -1;
1266         }
1267
1268         if (i == ARRAY_SIZE(modules)) {
1269                 fprintf(stderr, "failed to load any modules, aborting.\n");
1270                 return -1;
1271         }
1272
1273         resources = drmModeGetResources(fd);
1274         if (!resources) {
1275                 fprintf(stderr, "drmModeGetResources failed: %s\n",
1276                         strerror(errno));
1277                 drmClose(fd);
1278                 return 1;
1279         }
1280
1281         dump_resource(encoders);
1282         dump_resource(connectors);
1283         dump_resource(crtcs);
1284         dump_resource(planes);
1285         dump_resource(framebuffers);
1286
1287         if (count > 0) {
1288                 set_mode(con_args, count, plane_args, plane_count, test_vsync);
1289                 getchar();
1290         }
1291
1292         drmModeFreeResources(resources);
1293
1294         return 0;
1295 }