1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /*
18  * Hardware Composer Rectangles
19  *
20  * Synopsis
21  *   hwcRects [options] (graphicFormat displayFrame [attributes],)...
22  *     options:
23  *       -D #.## - End of test delay
24  *       -v - Verbose
25  *
26  *      graphic formats:
27  *        RGBA8888 (reference frame default)
28  *        RGBX8888
29  *        RGB888
30  *        RGB565
31  *        BGRA8888
32  *        RGBA5551
33  *        RGBA4444
34  *        YV12
35  *
36  *      displayFrame
37  *        [left, top, right, bottom]
38  *
39  *      attributes:
40  *        transform: none | fliph | flipv | rot90 | rot180 | rot270
41  *        blend: none | premult | coverage
42  *        color: [0.##, 0.##, 0.##]
43  *        alpha: 0.##
44  *        sourceDim: [width, height]
45  *        sourceCrop: [left, top, right, bottom]
46  *
47  *      Example:
48  *        # White YV12 rectangle, with overlapping turquoise
49  *        #  RGBA8888 rectangle at 30%% (alpha: 0.7) transparency
50  *        hwcRects -v -D 30.0 \
51  *          YV12 [50, 80, 200, 300] transform: none \
52  *            color: [1.0, 0.5, 0.5], \
53  *          RGBA8888 [100, 150, 300, 400] blend: coverage \
54  *            color: [0.251, 0.878, 0.816] alpha: 0.7 \
55  *            sourceDim: [50, 60] sourceCrop: [5, 8, 12, 15]
56  *
57  * Description
58  *   Constructs a Hardware Composer (HWC) list of frames from
59  *   command-line specified parameters.  Then sends it to the HWC
60  *   be rendered.  The intended purpose of this tool is as a means to
61  *   reproduce and succinctly specify an observed HWC operation, with
62  *   no need to modify/compile a program.
63  *
64  *   The command-line syntax consists of a few standard command-line
65  *   options and then a description of one or more frames.  The frame
66  *   descriptions are separated from one another via a comma.  The
67  *   beginning of a frame description requires the specification
68  *   of the graphic format and then the display frame rectangle where
69  *   the frame will be displayed.  The display frame rectangle is
70  *   specified as follows, with the right and bottom coordinates being
71  *   exclusive values:
72  *
73  *     [left, top, right, bottom]
74  *
75  *   After these two required parameters each frame description can
76  *   specify 1 or more optional attributes.  The name of each optional
77  *   attribute is preceded by a colon.  The current implementation
78  *   then requires white space after the colon and then the value of
79  *   the attribute is specified.  See the synopsis section above for
80  *   a list of attributes and the format of their expected value.
81  */
82 
83 #define LOG_TAG "hwcRectsTest"
84 
85 #include <algorithm>
86 #include <assert.h>
87 #include <cerrno>
88 #include <cmath>
89 #include <cstdlib>
90 #include <ctime>
91 #include <istream>
92 #include <libgen.h>
93 #include <list>
94 #include <sched.h>
95 #include <sstream>
96 #include <stdint.h>
97 #include <string.h>
98 #include <unistd.h>
99 
100 #include <sys/syscall.h>
101 #include <sys/types.h>
102 #include <sys/wait.h>
103 
104 #include <EGL/egl.h>
105 #include <EGL/eglext.h>
106 #include <GLES2/gl2.h>
107 #include <GLES2/gl2ext.h>
108 
109 #include <ui/GraphicBuffer.h>
110 #include <utils/Log.h>
111 #include <testUtil.h>
112 
113 #include <hardware/hwcomposer.h>
114 
115 #include <glTestLib.h>
116 #include "hwcTestLib.h"
117 
118 using namespace std;
119 using namespace android;
120 
121 // Defaults
122 const bool defaultVerbose = false;
123 const float defaultEndDelay = 2.0; // Default delay after rendering graphics
124 
125 const uint32_t   defaultFormat = HAL_PIXEL_FORMAT_RGBA_8888;
126 const int32_t    defaultTransform = 0;
127 const uint32_t   defaultBlend = HWC_BLENDING_NONE;
128 const ColorFract defaultColor(0.5, 0.5, 0.5);
129 const float      defaultAlpha = 1.0; // Opaque
130 const HwcTestDim defaultSourceDim(1, 1);
131 const struct hwc_rect defaultSourceCrop = {0, 0, 1, 1};
132 const struct hwc_rect defaultDisplayFrame = {0, 0, 100, 100};
133 
134 // Defines
135 #define MAXCMD               200
136 #define CMD_STOP_FRAMEWORK   "stop 2>&1"
137 #define CMD_START_FRAMEWORK  "start 2>&1"
138 
139 // Macros
140 #define NUMA(a) (sizeof(a) / sizeof((a)[0])) // Num elements in an array
141 
142 // Local types
143 class Rectangle {
144 public:
Rectangle()145     Rectangle() : format(defaultFormat), transform(defaultTransform),
146                   blend(defaultBlend), color(defaultColor),
147                   alpha(defaultAlpha), sourceDim(defaultSourceDim),
148                   sourceCrop(defaultSourceCrop),
149                   displayFrame(defaultDisplayFrame) {};
150 
151     uint32_t     format;
152     uint32_t     transform;
153     int32_t      blend;
154     ColorFract   color;
155     float        alpha;
156     HwcTestDim   sourceDim;
157     struct hwc_rect   sourceCrop;
158     struct hwc_rect   displayFrame;
159 
160     sp<GraphicBuffer> texture;
161 };
162 
163 // Globals
164 list<Rectangle> rectangle;
165 static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
166         GraphicBuffer::USAGE_SW_WRITE_RARELY;
167 static hwc_composer_device_1_t *hwcDevice;
168 static EGLDisplay dpy;
169 static EGLSurface surface;
170 static EGLint width, height;
171 
172 // Function prototypes
173 static Rectangle parseRect(const string& rectStr);
174 void init(void);
175 void printSyntax(const char *cmd);
176 
177 // Command-line option settings
178 static bool verbose = defaultVerbose;
179 static float endDelay = defaultEndDelay;
180 
181 /*
182  * Main
183  *
184  * Performs the following high-level sequence of operations:
185  *
186  *   1. Parse command-line options
187  *
188  *   2. Stop framework
189  *
190  *   3. Initialization
191  *
192  *   4. Parse frame descriptions
193  *
194  *   5. Create HWC list from frame descriptions
195  *
196  *   6. Have HWC render the list description of the frames
197  *
198  *   7. Delay for amount of time given by endDelay
199  *
200  *   8. Start framework
201  */
202 int
main(int argc,char * argv[])203 main(int argc, char *argv[])
204 {
205     int     rv, opt;
206     char   *chptr;
207     string  str;
208     char cmd[MAXCMD];
209 
210     testSetLogCatTag(LOG_TAG);
211 
212     // Parse command line arguments
213     while ((opt = getopt(argc, argv, "D:v?h")) != -1) {
214         switch (opt) {
215           case 'D': // End of test delay
216             endDelay = strtod(optarg, &chptr);
217             if ((*chptr != '\0') || (endDelay < 0.0)) {
218                 testPrintE("Invalid command-line specified end of test delay "
219                            "of: %s", optarg);
220                 exit(1);
221             }
222             break;
223 
224           case 'v': // Verbose
225             verbose = true;
226             break;
227 
228           case 'h': // Help
229           case '?':
230           default:
231             printSyntax(basename(argv[0]));
232             exit(((optopt == 0) || (optopt == '?')) ? 0 : 2);
233         }
234     }
235 
236     // Stop framework
237     rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
238     if (rv >= (signed) sizeof(cmd) - 1) {
239         testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
240         exit(3);
241     }
242     testExecCmd(cmd);
243     testDelay(1.0); // TODO - needs means to query whether asyncronous stop
244                     // framework operation has completed.  For now, just wait
245                     // a long time.
246 
247     init();
248 
249     // Parse rectangle descriptions
250     int numOpen = 0; // Current number of unmatched <[
251     string rectDesc(""); // String description of a single rectangle
252     while (optind < argc) {
253         string argNext = string(argv[optind++]);
254 
255         if (rectDesc.length()) { rectDesc += ' '; }
256         rectDesc += argNext;
257 
258         // Count number of opening <[ and matching >]
259         // At this point not worried about an opening character being
260         // matched by it's corresponding closing character.  For example,
261         // "<1.0, 2.0]" is incorrect because the opening < should be matched
262         // with a closing >, instead of the closing ].  Such errors are
263         // detected when the actual value is parsed.
264         for (unsigned int n1 = 0; n1 < argNext.length(); n1++) {
265             switch(argNext[n1]) {
266               case '[':
267               case '<':
268                 numOpen++;
269                 break;
270 
271               case ']':
272               case '>':
273                 numOpen--;
274                 break;
275             }
276 
277             // Error anytime there is more closing then opening characters
278             if (numOpen < 0) {
279                 testPrintI("Mismatched number of opening <[ with "
280                            "closing >] in: %s", rectDesc.c_str());
281                 exit(4);
282             }
283         }
284 
285         // Description of a rectangle is complete when all opening
286         // <[ are closed with >] and the string ends with a comma or
287         // there are no more args.
288         if ((numOpen == 0) && rectDesc.length()
289             && ((rectDesc[rectDesc.length() - 1] == ',')
290                 || (optind == argc))) {
291             // Remove trailing comma if it is present
292             if (rectDesc[rectDesc.length() - 1] == ',') {
293                 rectDesc.erase(rectDesc.length() - 1);
294             }
295 
296             // Parse string description of rectangle
297             Rectangle rect = parseRect(rectDesc);
298 
299             // Add to the list of rectangles
300             rectangle.push_back(rect);
301 
302             // Prepare for description of another rectangle
303             rectDesc = string("");
304         }
305     }
306 
307     // Create list of frames
308     hwc_display_contents_1_t *list;
309     list = hwcTestCreateLayerList(rectangle.size());
310     if (list == NULL) {
311         testPrintE("hwcTestCreateLayerList failed");
312         exit(5);
313     }
314 
315     hwc_layer_1_t *layer = &list->hwLayers[0];
316     for (std::list<Rectangle>::iterator it = rectangle.begin();
317          it != rectangle.end(); ++it, ++layer) {
318         layer->handle = it->texture->handle;
319         layer->blending = it->blend;
320         layer->transform = it->transform;
321         layer->sourceCrop = it->sourceCrop;
322         layer->displayFrame = it->displayFrame;
323 
324         layer->visibleRegionScreen.numRects = 1;
325         layer->visibleRegionScreen.rects = &layer->displayFrame;
326     }
327 
328     // Perform prepare operation
329     if (verbose) { testPrintI("Prepare:"); hwcTestDisplayList(list); }
330     hwcDevice->prepare(hwcDevice, 1, &list);
331     if (verbose) {
332         testPrintI("Post Prepare:");
333         hwcTestDisplayListPrepareModifiable(list);
334     }
335 
336     // Turn off the geometry changed flag
337     list->flags &= ~HWC_GEOMETRY_CHANGED;
338 
339     // Perform the set operation(s)
340     if (verbose) {testPrintI("Set:"); }
341     if (verbose) { hwcTestDisplayListHandles(list); }
342     list->dpy = dpy;
343     list->sur = surface;
344     hwcDevice->set(hwcDevice, 1, &list);
345 
346     testDelay(endDelay);
347 
348     // Start framework
349     rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
350     if (rv >= (signed) sizeof(cmd) - 1) {
351         testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
352         exit(6);
353     }
354     testExecCmd(cmd);
355 
356     return 0;
357 }
358 
359 // Parse string description of rectangle and add it to list of rectangles
360 // to be rendered.
parseRect(const string & rectStr)361 static Rectangle parseRect(const string& rectStr)
362 {
363     int rv;
364     string str;
365     bool   error;
366     istringstream in(rectStr);
367     const struct hwcTestGraphicFormat *format;
368     Rectangle rect;
369 
370     // Graphic Format
371     in >> str;
372     if (!in) {
373         testPrintE("Error parsing format from: %s", rectStr.c_str());
374         exit(20);
375     }
376     format = hwcTestGraphicFormatLookup(str.c_str());
377     if (format == NULL) {
378         testPrintE("Unknown graphic format in: %s", rectStr.c_str());
379         exit(21);
380     }
381     rect.format = format->format;
382 
383     // Display Frame
384     rect.displayFrame = hwcTestParseHwcRect(in, error);
385     if (error) {
386         testPrintE("Invalid display frame in: %s", rectStr.c_str());
387         exit(22);
388     }
389 
390     // Set default sourceDim and sourceCrop based on size of display frame.
391     // Default is source size equal to the size of the display frame, with
392     // the source crop being the entire size of the source frame.
393     rect.sourceDim = HwcTestDim(rect.displayFrame.right
394                                      - rect.displayFrame.left,
395                                  rect.displayFrame.bottom
396                                      - rect.displayFrame.top);
397     rect.sourceCrop.left = 0;
398     rect.sourceCrop.top = 0;
399     rect.sourceCrop.right = rect.sourceDim.width();
400     rect.sourceCrop.bottom = rect.sourceDim.height();
401 
402     // Optional settings
403     while ((in.tellg() < (streampos) in.str().length())
404            && (in.tellg() != (streampos) -1)) {
405         string attrName;
406 
407         in >> attrName;
408         if (in.eof()) { break; }
409         if (!in) {
410             testPrintE("Error reading attribute name in: %s",
411                        rectStr.c_str());
412             exit(23);
413         }
414 
415         // Transform
416         if (attrName == "transform:") { // Transform
417             string str;
418 
419             in >> str;
420             if (str == "none") {
421                 rect.transform = 0;
422             } else if (str == "fliph") {
423                 rect.transform = HWC_TRANSFORM_FLIP_H;
424             } else if (str == "flipv") {
425                 rect.transform = HWC_TRANSFORM_FLIP_V;
426             } else if (str == "rot90") {
427                 rect.transform = HWC_TRANSFORM_ROT_90;
428             } else if (str == "rot180") {
429                 rect.transform = HWC_TRANSFORM_ROT_180;
430             } else if (str == "rot270") {
431                 rect.transform = HWC_TRANSFORM_ROT_270;
432             } else {
433                 testPrintE("Unknown transform of \"%s\" in: %s", str.c_str(),
434                            rectStr.c_str());
435                 exit(24);
436             }
437         } else if (attrName == "blend:") { // Blend
438             string str;
439 
440             in >> str;
441             if (str == string("none")) {
442                 rect.blend = HWC_BLENDING_NONE;
443             } else if (str == "premult") {
444                 rect.blend = HWC_BLENDING_PREMULT;
445             } else if (str == "coverage") {
446                 rect.blend = HWC_BLENDING_COVERAGE;
447             } else {
448                 testPrintE("Unknown blend of \"%s\" in: %s", str.c_str(),
449                            rectStr.c_str());
450                 exit(25);
451             }
452         } else if (attrName == "color:") { // Color
453             rect.color = hwcTestParseColor(in, error);
454             if (error) {
455                 testPrintE("Error parsing color in: %s", rectStr.c_str());
456                 exit(26);
457             }
458         } else if (attrName == "alpha:") { // Alpha
459             in >> rect.alpha;
460             if (!in) {
461                 testPrintE("Error parsing value for alpha attribute in: %s",
462                            rectStr.c_str());
463                 exit(27);
464             }
465         } else if (attrName == "sourceDim:") { // Source Dimension
466            rect.sourceDim = hwcTestParseDim(in, error);
467             if (error) {
468                 testPrintE("Error parsing source dimenision in: %s",
469                            rectStr.c_str());
470                 exit(28);
471             }
472         } else if (attrName == "sourceCrop:") { // Source Crop
473             rect.sourceCrop = hwcTestParseHwcRect(in, error);
474             if (error) {
475                 testPrintE("Error parsing source crop in: %s",
476                            rectStr.c_str());
477                 exit(29);
478             }
479         } else { // Unknown attribute
480             testPrintE("Unknown attribute of \"%s\" in: %s", attrName.c_str(),
481                        rectStr.c_str());
482             exit(30);
483         }
484     }
485 
486     // Validate
487     if (((uint32_t) rect.sourceCrop.left >= rect.sourceDim.width())
488         || ((uint32_t) rect.sourceCrop.right > rect.sourceDim.width())
489         || ((uint32_t) rect.sourceCrop.top >= rect.sourceDim.height())
490         || ((uint32_t) rect.sourceCrop.bottom > rect.sourceDim.height())) {
491         testPrintE("Invalid source crop in: %s", rectStr.c_str());
492         exit(31);
493     }
494     if ((rect.displayFrame.left >= width)
495         || (rect.displayFrame.right > width)
496         || (rect.displayFrame.top >= height)
497         || (rect.displayFrame.bottom > height)) {
498         testPrintE("Invalid display frame in: %s", rectStr.c_str());
499         exit(32);
500     }
501     if ((rect.alpha < 0.0) || (rect.alpha > 1.0)) {
502         testPrintE("Invalid alpha in: %s", rectStr.c_str());
503         exit(33);
504     }
505 
506     // Create source texture
507     rect.texture = new GraphicBuffer(rect.sourceDim.width(),
508                                      rect.sourceDim.height(),
509                                      rect.format, texUsage);
510     if ((rv = rect.texture->initCheck()) != NO_ERROR) {
511         testPrintE("source texture initCheck failed, rv: %i", rv);
512         testPrintE("  %s", rectStr.c_str());
513 
514     }
515 
516     // Fill with uniform color
517     hwcTestFillColor(rect.texture.get(), rect.color, rect.alpha);
518     if (verbose) {
519         testPrintI("    buf: %p handle: %p format: %s width: %u height: %u "
520                    "color: %s alpha: %f",
521                    rect.texture.get(), rect.texture->handle, format->desc,
522                    rect.sourceDim.width(), rect.sourceDim.height(),
523                    string(rect.color).c_str(), rect.alpha);
524     }
525 
526     return rect;
527 }
528 
init(void)529 void init(void)
530 {
531     // Seed pseudo random number generator
532     // Needed so that the pad areas of frames are filled with a deterministic
533     // pseudo random value.
534     srand48(0);
535 
536     hwcTestInitDisplay(verbose, &dpy, &surface, &width, &height);
537 
538     hwcTestOpenHwc(&hwcDevice);
539 }
540 
printSyntax(const char * cmd)541 void printSyntax(const char *cmd)
542 {
543     testPrintE("  %s [options] (graphicFormat displayFrame [attributes],)...",
544                cmd);
545     testPrintE("    options:");
546     testPrintE("      -D End of test delay");
547     testPrintE("      -v Verbose");
548     testPrintE("");
549     testPrintE("    graphic formats:");
550     for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
551         testPrintE("      %s", hwcTestGraphicFormat[n1].desc);
552     }
553     testPrintE("");
554     testPrintE("    displayFrame");
555     testPrintE("      [left, top, right, bottom]");
556     testPrintE("");
557     testPrintE("    attributes:");
558     testPrintE("      transform: none | fliph | flipv | rot90 | rot180 "
559                " | rot270");
560     testPrintE("      blend: none | premult | coverage");
561     testPrintE("      color: [0.##, 0.##, 0.##]");
562     testPrintE("      alpha: 0.##");
563     testPrintE("      sourceDim: [width, height]");
564     testPrintE("      sourceCrop: [left, top, right, bottom]");
565     testPrintE("");
566     testPrintE("    Example:");
567     testPrintE("      # White YV12 rectangle, with overlapping turquoise ");
568     testPrintE("      #  RGBA8888 rectangle at 30%% (alpha: 0.7) transparency");
569     testPrintE("      %s -v -D 30.0 \\", cmd);
570     testPrintE("        YV12 [50, 80, 200, 300] transform: none \\");
571     testPrintE("          color: [1.0, 0.5, 0.5], \\");
572     testPrintE("        RGBA8888 [100, 150, 300, 400] blend: coverage \\");
573     testPrintE("          color: [0.251, 0.878, 0.816] alpha: 0.7 \\");
574     testPrintE("          sourceDim: [50, 60] sourceCrop: [5, 8, 12, 15]");
575 }
576