1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
4 #include <regex>
5 #include <set>
6 #include <chrono>
8 #include <sys/select.h>
10 #include <kms++/kms++.h>
11 #include <kms++/modedb.h>
12 #include <kms++/mode_cvt.h>
14 #include <kms++util/kms++util.h>
16 using namespace std;
17 using namespace kms;
19 struct PlaneInfo
20 {
21 Plane* plane;
23 unsigned x;
24 unsigned y;
25 unsigned w;
26 unsigned h;
28 unsigned view_x;
29 unsigned view_y;
30 unsigned view_w;
31 unsigned view_h;
33 vector<MappedFramebuffer*> fbs;
34 };
36 struct OutputInfo
37 {
38 Connector* connector;
40 Crtc* crtc;
41 Plane* primary_plane;
42 Videomode mode;
43 bool user_set_crtc;
44 vector<MappedFramebuffer*> fbs;
46 vector<PlaneInfo> planes;
47 };
49 static bool s_use_dmt;
50 static bool s_use_cea;
51 static unsigned s_num_buffers = 1;
52 static bool s_flip_mode;
53 static bool s_flip_sync;
54 static bool s_cvt;
55 static bool s_cvt_v2;
56 static bool s_cvt_vid_opt;
57 static unsigned s_max_flips;
59 static set<Crtc*> s_used_crtcs;
60 static set<Plane*> s_used_planes;
62 __attribute__ ((unused))
63 static void print_regex_match(smatch sm)
64 {
65 for (unsigned i = 0; i < sm.size(); ++i) {
66 string str = sm[i].str();
67 printf("%u: %s\n", i, str.c_str());
68 }
69 }
71 static void get_connector(ResourceManager& resman, OutputInfo& output, const string& str = "")
72 {
73 Connector* conn = resman.reserve_connector(str);
75 if (!conn)
76 EXIT("No connector '%s'", str.c_str());
78 if (!conn->connected())
79 EXIT("Connector '%s' not connected", conn->fullname().c_str());
81 output.connector = conn;
82 output.mode = output.connector->get_default_mode();
83 }
85 static void get_default_crtc(Card& card, OutputInfo& output)
86 {
87 Crtc* crtc = output.connector->get_current_crtc();
89 if (crtc && s_used_crtcs.find(crtc) == s_used_crtcs.end()) {
90 s_used_crtcs.insert(crtc);
91 output.crtc = crtc;
92 return;
93 }
95 for (const auto& possible : output.connector->get_possible_crtcs()) {
96 if (s_used_crtcs.find(possible) == s_used_crtcs.end()) {
97 s_used_crtcs.insert(possible);
98 output.crtc = possible;
99 return;
100 }
101 }
103 EXIT("Could not find available crtc");
104 }
106 static void parse_crtc(Card& card, const string& crtc_str, OutputInfo& output)
107 {
108 // @12:1920x1200i@60
109 // @12:33000000,800/210/30/16/-,480/22/13/10/-,i
111 const regex modename_re("(?:(@?)(\\d+):)?" // @12:
112 "(?:(\\d+)x(\\d+)(i)?)" // 1920x1200i
113 "(?:@([\\d\\.]+))?"); // @60
115 const regex modeline_re("(?:(@?)(\\d+):)?" // @12:
116 "(\\d+)," // 33000000,
117 "(\\d+)/(\\d+)/(\\d+)/(\\d+)/([+-])," // 800/210/30/16/-,
118 "(\\d+)/(\\d+)/(\\d+)/(\\d+)/([+-])" // 480/22/13/10/-
119 "(?:,([i]+))?" // ,i
120 );
122 smatch sm;
123 if (regex_match(crtc_str, sm, modename_re)) {
124 if (sm[2].matched) {
125 bool use_id = sm[1].length() == 1;
126 unsigned num = stoul(sm[2].str());
128 if (use_id) {
129 Crtc* c = card.get_crtc(num);
130 if (!c)
131 EXIT("Bad crtc id '%u'", num);
133 output.crtc = c;
134 } else {
135 auto crtcs = card.get_crtcs();
137 if (num >= crtcs.size())
138 EXIT("Bad crtc number '%u'", num);
140 output.crtc = crtcs[num];
141 }
142 } else {
143 output.crtc = output.connector->get_current_crtc();
144 }
146 unsigned w = stoul(sm[3]);
147 unsigned h = stoul(sm[4]);
148 bool ilace = sm[5].matched ? true : false;
149 float refresh = sm[6].matched ? stof(sm[6]) : 0;
151 if (s_cvt) {
152 output.mode = videomode_from_cvt(w, h, refresh, ilace, s_cvt_v2, s_cvt_vid_opt);
153 } else if (s_use_dmt) {
154 try {
155 output.mode = find_dmt(w, h, refresh, ilace);
156 } catch (exception& e) {
157 EXIT("Mode not found from DMT tables\n");
158 }
159 } else if (s_use_cea) {
160 try {
161 output.mode = find_cea(w, h, refresh, ilace);
162 } catch (exception& e) {
163 EXIT("Mode not found from CEA tables\n");
164 }
165 } else {
166 try {
167 output.mode = output.connector->get_mode(w, h, refresh, ilace);
168 } catch (exception& e) {
169 EXIT("Mode not found from the connector\n");
170 }
171 }
172 } else if (regex_match(crtc_str, sm, modeline_re)) {
173 if (sm[2].matched) {
174 bool use_id = sm[1].length() == 1;
175 unsigned num = stoul(sm[2].str());
177 if (use_id) {
178 Crtc* c = card.get_crtc(num);
179 if (!c)
180 EXIT("Bad crtc id '%u'", num);
182 output.crtc = c;
183 } else {
184 auto crtcs = card.get_crtcs();
186 if (num >= crtcs.size())
187 EXIT("Bad crtc number '%u'", num);
189 output.crtc = crtcs[num];
190 }
191 } else {
192 output.crtc = output.connector->get_current_crtc();
193 }
195 unsigned clock = stoul(sm[3]);
197 unsigned hact = stoul(sm[4]);
198 unsigned hfp = stoul(sm[5]);
199 unsigned hsw = stoul(sm[6]);
200 unsigned hbp = stoul(sm[7]);
201 bool h_pos_sync = sm[8] == "+" ? true : false;
203 unsigned vact = stoul(sm[9]);
204 unsigned vfp = stoul(sm[10]);
205 unsigned vsw = stoul(sm[11]);
206 unsigned vbp = stoul(sm[12]);
207 bool v_pos_sync = sm[13] == "+" ? true : false;
209 output.mode = videomode_from_timings(clock / 1000, hact, hfp, hsw, hbp, vact, vfp, vsw, vbp);
210 output.mode.set_hsync(h_pos_sync ? SyncPolarity::Positive : SyncPolarity::Negative);
211 output.mode.set_vsync(v_pos_sync ? SyncPolarity::Positive : SyncPolarity::Negative);
213 if (sm[14].matched) {
214 for (int i = 0; i < sm[14].length(); ++i) {
215 char f = string(sm[14])[i];
217 switch (f) {
218 case 'i':
219 output.mode.set_interlace(true);
220 break;
221 default:
222 EXIT("Bad mode flag %c", f);
223 }
224 }
225 }
226 } else {
227 EXIT("Failed to parse crtc option '%s'", crtc_str.c_str());
228 }
229 }
231 static void parse_plane(Card& card, const string& plane_str, const OutputInfo& output, PlaneInfo& pinfo)
232 {
233 // 3:400,400-400x400
234 const regex plane_re("(?:(@?)(\\d+):)?" // 3:
235 "(?:(\\d+),(\\d+)-)?" // 400,400-
236 "(\\d+)x(\\d+)"); // 400x400
238 smatch sm;
239 if (!regex_match(plane_str, sm, plane_re))
240 EXIT("Failed to parse plane option '%s'", plane_str.c_str());
242 if (sm[2].matched) {
243 bool use_id = sm[1].length() == 1;
244 unsigned num = stoul(sm[2].str());
246 if (use_id) {
247 Plane* p = card.get_plane(num);
248 if (!p)
249 EXIT("Bad plane id '%u'", num);
251 pinfo.plane = p;
252 } else {
253 auto planes = card.get_planes();
255 if (num >= planes.size())
256 EXIT("Bad plane number '%u'", num);
258 pinfo.plane = planes[num];
259 }
260 } else {
261 for (Plane* p : output.crtc->get_possible_planes()) {
262 if (s_used_planes.find(p) != s_used_planes.end())
263 continue;
265 if (p->plane_type() != PlaneType::Overlay)
266 continue;
268 pinfo.plane = p;
269 }
271 if (!pinfo.plane)
272 EXIT("Failed to find available plane");
273 }
275 s_used_planes.insert(pinfo.plane);
277 pinfo.w = stoul(sm[5]);
278 pinfo.h = stoul(sm[6]);
280 if (sm[3].matched)
281 pinfo.x = stoul(sm[3]);
282 else
283 pinfo.x = output.mode.hdisplay / 2 - pinfo.w / 2;
285 if (sm[4].matched)
286 pinfo.y = stoul(sm[4]);
287 else
288 pinfo.y = output.mode.vdisplay / 2 - pinfo.h / 2;
289 }
291 static vector<MappedFramebuffer*> get_default_fb(Card& card, unsigned width, unsigned height)
292 {
293 vector<MappedFramebuffer*> v;
295 for (unsigned i = 0; i < s_num_buffers; ++i)
296 v.push_back(new DumbFramebuffer(card, width, height, PixelFormat::XRGB8888));
298 return v;
299 }
301 static vector<MappedFramebuffer*> parse_fb(Card& card, const string& fb_str, unsigned def_w, unsigned def_h)
302 {
303 unsigned w = def_w;
304 unsigned h = def_h;
305 PixelFormat format = PixelFormat::XRGB8888;
307 if (!fb_str.empty()) {
308 // XXX the regexp is not quite correct
309 // 400x400-NV12
310 const regex fb_re("(?:(\\d+)x(\\d+))?" // 400x400
311 "(?:-)?" // -
312 "(\\w\\w\\w\\w)?"); // NV12
314 smatch sm;
315 if (!regex_match(fb_str, sm, fb_re))
316 EXIT("Failed to parse fb option '%s'", fb_str.c_str());
318 if (sm[1].matched)
319 w = stoul(sm[1]);
320 if (sm[2].matched)
321 h = stoul(sm[2]);
322 if (sm[3].matched)
323 format = FourCCToPixelFormat(sm[3]);
324 }
326 vector<MappedFramebuffer*> v;
328 for (unsigned i = 0; i < s_num_buffers; ++i)
329 v.push_back(new DumbFramebuffer(card, w, h, format));
331 return v;
332 }
334 static void parse_view(const string& view_str, PlaneInfo& pinfo)
335 {
336 const regex view_re("(\\d+),(\\d+)-(\\d+)x(\\d+)"); // 400,400-400x400
338 smatch sm;
339 if (!regex_match(view_str, sm, view_re))
340 EXIT("Failed to parse view option '%s'", view_str.c_str());
342 pinfo.view_x = stoul(sm[1]);
343 pinfo.view_y = stoul(sm[2]);
344 pinfo.view_w = stoul(sm[3]);
345 pinfo.view_h = stoul(sm[4]);
346 }
348 static const char* usage_str =
349 "Usage: kmstest [OPTION]...\n\n"
350 "Show a test pattern on a display or plane\n\n"
351 "Options:\n"
352 " --device=DEVICE DEVICE is the path to DRM card to open\n"
353 " -c, --connector=CONN CONN is <connector>\n"
354 " -r, --crtc=CRTC CRTC is [<crtc>:]<w>x<h>[@<Hz>]\n"
355 " or\n"
356 " [<crtc>:]<pclk>,<hact>/<hfp>/<hsw>/<hbp>/<hsp>,<vact>/<vfp>/<vsw>/<vbp>/<vsp>[,i]\n"
357 " -p, --plane=PLANE PLANE is [<plane>:][<x>,<y>-]<w>x<h>\n"
358 " -f, --fb=FB FB is [<w>x<h>][-][<4cc>]\n"
359 " -v, --view=VIEW VIEW is <x>,<y>-<w>x<h>\n"
360 " --dmt Search for the given mode from DMT tables\n"
361 " --cea Search for the given mode from CEA tables\n"
362 " --cvt=CVT Create videomode with CVT. CVT is 'v1', 'v2' or 'v2o'\n"
363 " --flip[=max] Do page flipping for each output with an optional maximum flips count\n"
364 " --sync Synchronize page flipping\n"
365 "\n"
366 "<connector>, <crtc> and <plane> can be given by index (<idx>) or id (@<id>).\n"
367 "<connector> can also be given by name.\n"
368 "\n"
369 "Options can be given multiple times to set up multiple displays or planes.\n"
370 "Options may apply to previous options, e.g. a plane will be set on a crtc set in\n"
371 "an earlier option.\n"
372 "If you omit parameters, kmstest tries to guess what you mean\n"
373 "\n"
374 "Examples:\n"
375 "\n"
376 "Set eDP-1 mode to 1920x1080@60, show XR24 framebuffer on the crtc, and a 400x400 XB24 plane:\n"
377 " kmstest -c eDP-1 -r 1920x1080@60 -f XR24 -p 400x400 -f XB24\n\n"
378 "XR24 framebuffer on first connected connector in the default mode:\n"
379 " kmstest -f XR24\n\n"
380 "XR24 framebuffer on a 400x400 plane on the first connected connector in the default mode:\n"
381 " kmstest -p 400x400 -f XR24\n\n"
382 "Test pattern on the second connector with default mode:\n"
383 " kmstest -c 1\n"
384 ;
386 static void usage()
387 {
388 puts(usage_str);
389 }
391 enum class ObjectType
392 {
393 Connector,
394 Crtc,
395 Plane,
396 Framebuffer,
397 View,
398 };
400 struct Arg
401 {
402 ObjectType type;
403 string arg;
404 };
406 static string s_device_path = "/dev/dri/card0";
408 static vector<Arg> parse_cmdline(int argc, char **argv)
409 {
410 vector<Arg> args;
412 OptionSet optionset = {
413 Option("|device=",
414 [&](string s)
415 {
416 s_device_path = s;
417 }),
418 Option("c|connector=",
419 [&](string s)
420 {
421 args.push_back(Arg { ObjectType::Connector, s });
422 }),
423 Option("r|crtc=", [&](string s)
424 {
425 args.push_back(Arg { ObjectType::Crtc, s });
426 }),
427 Option("p|plane=", [&](string s)
428 {
429 args.push_back(Arg { ObjectType::Plane, s });
430 }),
431 Option("f|fb=", [&](string s)
432 {
433 args.push_back(Arg { ObjectType::Framebuffer, s });
434 }),
435 Option("v|view=", [&](string s)
436 {
437 args.push_back(Arg { ObjectType::View, s });
438 }),
439 Option("|dmt", []()
440 {
441 s_use_dmt = true;
442 }),
443 Option("|cea", []()
444 {
445 s_use_cea = true;
446 }),
447 Option("|flip?", [&](string s)
448 {
449 s_flip_mode = true;
450 s_num_buffers = 2;
451 if (!s.empty())
452 s_max_flips = stoi(s);
453 }),
454 Option("|sync", []()
455 {
456 s_flip_sync = true;
457 }),
458 Option("|cvt=", [&](string s)
459 {
460 if (s == "v1")
461 s_cvt = true;
462 else if (s == "v2")
463 s_cvt = s_cvt_v2 = true;
464 else if (s == "v2o")
465 s_cvt = s_cvt_v2 = s_cvt_vid_opt = true;
466 else {
467 usage();
468 exit(-1);
469 }
470 }),
471 Option("h|help", [&]()
472 {
473 usage();
474 exit(-1);
475 }),
476 };
478 optionset.parse(argc, argv);
480 if (optionset.params().size() > 0) {
481 usage();
482 exit(-1);
483 }
485 return args;
486 }
488 static vector<OutputInfo> setups_to_outputs(Card& card, ResourceManager& resman, const vector<Arg>& output_args)
489 {
490 vector<OutputInfo> outputs;
492 if (output_args.size() == 0) {
493 // no output args, show a pattern on all screens
494 for (Connector* conn : card.get_connectors()) {
495 if (!conn->connected())
496 continue;
498 OutputInfo output = { };
499 output.connector = resman.reserve_connector(conn);
500 EXIT_IF(!output.connector, "Failed to reserve connector %s", conn->fullname().c_str());
501 output.crtc = resman.reserve_crtc(conn);
502 EXIT_IF(!output.crtc, "Failed to reserve crtc for %s", conn->fullname().c_str());
503 output.mode = output.connector->get_default_mode();
505 output.fbs = get_default_fb(card, output.mode.hdisplay, output.mode.vdisplay);
507 outputs.push_back(output);
508 }
510 return outputs;
511 }
513 OutputInfo* current_output = 0;
514 PlaneInfo* current_plane = 0;
516 for (auto& arg : output_args) {
517 switch (arg.type) {
518 case ObjectType::Connector:
519 {
520 outputs.push_back(OutputInfo { });
521 current_output = &outputs.back();
523 get_connector(resman, *current_output, arg.arg);
524 current_plane = 0;
526 break;
527 }
529 case ObjectType::Crtc:
530 {
531 if (!current_output) {
532 outputs.push_back(OutputInfo { });
533 current_output = &outputs.back();
534 }
536 if (!current_output->connector)
537 get_connector(resman, *current_output);
539 parse_crtc(card, arg.arg, *current_output);
541 current_output->user_set_crtc = true;
543 current_plane = 0;
545 break;
546 }
548 case ObjectType::Plane:
549 {
550 if (!current_output) {
551 outputs.push_back(OutputInfo { });
552 current_output = &outputs.back();
553 }
555 if (!current_output->connector)
556 get_connector(resman, *current_output);
558 if (!current_output->crtc)
559 get_default_crtc(card, *current_output);
561 current_output->planes.push_back(PlaneInfo { });
562 current_plane = ¤t_output->planes.back();
564 parse_plane(card, arg.arg, *current_output, *current_plane);
566 break;
567 }
569 case ObjectType::Framebuffer:
570 {
571 if (!current_output) {
572 outputs.push_back(OutputInfo { });
573 current_output = &outputs.back();
574 }
576 if (!current_output->connector)
577 get_connector(resman, *current_output);
579 if (!current_output->crtc)
580 get_default_crtc(card, *current_output);
582 int def_w, def_h;
584 if (current_plane) {
585 def_w = current_plane->w;
586 def_h = current_plane->h;
587 } else {
588 def_w = current_output->mode.hdisplay;
589 def_h = current_output->mode.vdisplay;
590 }
592 auto fbs = parse_fb(card, arg.arg, def_w, def_h);
594 if (current_plane)
595 current_plane->fbs = fbs;
596 else
597 current_output->fbs = fbs;
599 break;
600 }
602 case ObjectType::View:
603 {
604 if (!current_plane || current_plane->fbs.empty())
605 EXIT("'view' parameter requires a plane and a fb");
607 parse_view(arg.arg, *current_plane);
608 break;
609 }
610 }
611 }
613 // create default framebuffers if needed
614 for (OutputInfo& o : outputs) {
615 if (!o.crtc) {
616 get_default_crtc(card, o);
617 o.user_set_crtc = true;
618 }
620 if (o.fbs.empty() && o.user_set_crtc)
621 o.fbs = get_default_fb(card, o.mode.hdisplay, o.mode.vdisplay);
623 for (PlaneInfo &p : o.planes) {
624 if (p.fbs.empty())
625 p.fbs = get_default_fb(card, p.w, p.h);
626 }
627 }
629 return outputs;
630 }
632 static std::string videomode_to_string(const Videomode& m)
633 {
634 string h = sformat("%u/%u/%u/%u", m.hdisplay, m.hfp(), m.hsw(), m.hbp());
635 string v = sformat("%u/%u/%u/%u", m.vdisplay, m.vfp(), m.vsw(), m.vbp());
637 return sformat("%s %.3f %s %s %u (%.2f) %#x %#x",
638 m.name.c_str(),
639 m.clock / 1000.0,
640 h.c_str(), v.c_str(),
641 m.vrefresh, m.calculated_vrefresh(),
642 m.flags,
643 m.type);
644 }
646 static void print_outputs(const vector<OutputInfo>& outputs)
647 {
648 for (unsigned i = 0; i < outputs.size(); ++i) {
649 const OutputInfo& o = outputs[i];
651 printf("Connector %u/@%u: %s\n", o.connector->idx(), o.connector->id(),
652 o.connector->fullname().c_str());
653 printf(" Crtc %u/@%u", o.crtc->idx(), o.crtc->id());
654 if (o.primary_plane)
655 printf(" (plane %u/@%u)", o.primary_plane->idx(), o.primary_plane->id());
656 printf(": %s\n", videomode_to_string(o.mode).c_str());
657 if (!o.fbs.empty()) {
658 auto fb = o.fbs[0];
659 printf(" Fb %u %ux%u-%s\n", fb->id(), fb->width(), fb->height(),
660 PixelFormatToFourCC(fb->format()).c_str());
661 }
663 for (unsigned j = 0; j < o.planes.size(); ++j) {
664 const PlaneInfo& p = o.planes[j];
665 auto fb = p.fbs[0];
666 printf(" Plane %u/@%u: %u,%u-%ux%u\n", p.plane->idx(), p.plane->id(),
667 p.x, p.y, p.w, p.h);
668 printf(" Fb %u %ux%u-%s\n", fb->id(), fb->width(), fb->height(),
669 PixelFormatToFourCC(fb->format()).c_str());
670 }
671 }
672 }
674 static void draw_test_patterns(const vector<OutputInfo>& outputs)
675 {
676 for (const OutputInfo& o : outputs) {
677 for (auto fb : o.fbs)
678 draw_test_pattern(*fb);
680 for (const PlaneInfo& p : o.planes)
681 for (auto fb : p.fbs)
682 draw_test_pattern(*fb);
683 }
684 }
686 static void set_crtcs_n_planes_legacy(Card& card, const vector<OutputInfo>& outputs)
687 {
688 // Disable unused crtcs
689 for (Crtc* crtc : card.get_crtcs()) {
690 if (find_if(outputs.begin(), outputs.end(), [crtc](const OutputInfo& o) { return o.crtc == crtc; }) != outputs.end())
691 continue;
693 crtc->disable_mode();
694 }
696 for (const OutputInfo& o : outputs) {
697 auto conn = o.connector;
698 auto crtc = o.crtc;
700 if (!o.fbs.empty()) {
701 auto fb = o.fbs[0];
702 int r = crtc->set_mode(conn, *fb, o.mode);
703 if (r)
704 printf("crtc->set_mode() failed for crtc %u: %s\n",
705 crtc->id(), strerror(-r));
706 }
708 for (const PlaneInfo& p : o.planes) {
709 auto fb = p.fbs[0];
710 int r = crtc->set_plane(p.plane, *fb,
711 p.x, p.y, p.w, p.h,
712 0, 0, fb->width(), fb->height());
713 if (r)
714 printf("crtc->set_plane() failed for plane %u: %s\n",
715 p.plane->id(), strerror(-r));
716 }
717 }
718 }
720 static void set_crtcs_n_planes_atomic(Card& card, const vector<OutputInfo>& outputs)
721 {
722 int r;
724 // XXX DRM framework doesn't allow moving an active plane from one crtc to another.
725 // See drm_atomic.c::plane_switching_crtc().
726 // For the time being, disable all crtcs and planes here.
728 AtomicReq disable_req(card);
730 // Disable unused crtcs
731 for (Crtc* crtc : card.get_crtcs()) {
732 //if (find_if(outputs.begin(), outputs.end(), [crtc](const OutputInfo& o) { return o.crtc == crtc; }) != outputs.end())
733 // continue;
735 disable_req.add(crtc, {
736 { "ACTIVE", 0 },
737 });
738 }
740 // Disable unused planes
741 for (Plane* plane : card.get_planes()) {
742 //if (find_if(outputs.begin(), outputs.end(), [plane](const OutputInfo& o) { return o.primary_plane == plane; }) != outputs.end())
743 // continue;
745 disable_req.add(plane, {
746 { "FB_ID", 0 },
747 { "CRTC_ID", 0 },
748 });
749 }
751 r = disable_req.commit_sync(true);
752 if (r)
753 EXIT("Atomic commit failed when disabling: %d\n", r);
756 // Keep blobs here so that we keep ref to them until we have committed the req
757 vector<unique_ptr<Blob>> blobs;
759 AtomicReq req(card);
761 for (const OutputInfo& o : outputs) {
762 auto conn = o.connector;
763 auto crtc = o.crtc;
765 blobs.emplace_back(o.mode.to_blob(card));
766 Blob* mode_blob = blobs.back().get();
768 req.add(conn, {
769 { "CRTC_ID", crtc->id() },
770 });
772 req.add(crtc, {
773 { "ACTIVE", 1 },
774 { "MODE_ID", mode_blob->id() },
775 });
777 if (!o.fbs.empty()) {
778 auto fb = o.fbs[0];
780 req.add(o.primary_plane, {
781 { "FB_ID", fb->id() },
782 { "CRTC_ID", crtc->id() },
783 { "SRC_X", 0 << 16 },
784 { "SRC_Y", 0 << 16 },
785 { "SRC_W", fb->width() << 16 },
786 { "SRC_H", fb->height() << 16 },
787 { "CRTC_X", 0 },
788 { "CRTC_Y", 0 },
789 { "CRTC_W", fb->width() },
790 { "CRTC_H", fb->height() },
791 });
792 }
794 for (const PlaneInfo& p : o.planes) {
795 auto fb = p.fbs[0];
797 req.add(p.plane, {
798 { "FB_ID", fb->id() },
799 { "CRTC_ID", crtc->id() },
800 { "SRC_X", (p.view_x ?: 0) << 16 },
801 { "SRC_Y", (p.view_y ?: 0) << 16 },
802 { "SRC_W", (p.view_w ?: fb->width()) << 16 },
803 { "SRC_H", (p.view_h ?: fb->height()) << 16 },
804 { "CRTC_X", p.x },
805 { "CRTC_Y", p.y },
806 { "CRTC_W", p.w },
807 { "CRTC_H", p.h },
808 });
809 }
810 }
812 r = req.test(true);
813 if (r)
814 EXIT("Atomic test failed: %d\n", r);
816 r = req.commit_sync(true);
817 if (r)
818 EXIT("Atomic commit failed: %d\n", r);
819 }
821 static void set_crtcs_n_planes(Card& card, const vector<OutputInfo>& outputs)
822 {
823 if (card.has_atomic())
824 set_crtcs_n_planes_atomic(card, outputs);
825 else
826 set_crtcs_n_planes_legacy(card, outputs);
827 }
829 static bool max_flips_reached;
831 class FlipState : private PageFlipHandlerBase
832 {
833 public:
834 FlipState(Card& card, const string& name, vector<const OutputInfo*> outputs)
835 : m_card(card), m_name(name), m_outputs(outputs)
836 {
837 }
839 void start_flipping()
840 {
841 m_prev_frame = m_prev_print = std::chrono::steady_clock::now();
842 m_slowest_frame = std::chrono::duration<float>::min();
843 m_frame_num = 0;
844 queue_next();
845 }
847 private:
848 void handle_page_flip(uint32_t frame, double time)
849 {
850 m_frame_num++;
851 if (s_max_flips && m_frame_num >= s_max_flips)
852 max_flips_reached = true;
854 auto now = std::chrono::steady_clock::now();
856 std::chrono::duration<float> diff = now - m_prev_frame;
857 if (diff > m_slowest_frame)
858 m_slowest_frame = diff;
860 if (m_frame_num % 100 == 0) {
861 std::chrono::duration<float> fsec = now - m_prev_print;
862 printf("Connector %s: fps %f, slowest %.2f ms\n",
863 m_name.c_str(),
864 100.0 / fsec.count(),
865 m_slowest_frame.count() * 1000);
866 m_prev_print = now;
867 m_slowest_frame = std::chrono::duration<float>::min();
868 }
870 m_prev_frame = now;
872 queue_next();
873 }
875 static unsigned get_bar_pos(MappedFramebuffer* fb, unsigned frame_num)
876 {
877 return (frame_num * bar_speed) % (fb->width() - bar_width + 1);
878 }
880 static void draw_bar(MappedFramebuffer* fb, unsigned frame_num)
881 {
882 int old_xpos = frame_num < s_num_buffers ? -1 : get_bar_pos(fb, frame_num - s_num_buffers);
883 int new_xpos = get_bar_pos(fb, frame_num);
885 draw_color_bar(*fb, old_xpos, new_xpos, bar_width);
886 draw_text(*fb, fb->width() / 2, 0, to_string(frame_num), RGB(255, 255, 255));
887 }
889 static void do_flip_output(AtomicReq& req, unsigned frame_num, const OutputInfo& o)
890 {
891 unsigned cur = frame_num % s_num_buffers;
893 if (!o.fbs.empty()) {
894 auto fb = o.fbs[cur];
896 draw_bar(fb, frame_num);
898 req.add(o.primary_plane, {
899 { "FB_ID", fb->id() },
900 });
901 }
903 for (const PlaneInfo& p : o.planes) {
904 auto fb = p.fbs[cur];
906 draw_bar(fb, frame_num);
908 req.add(p.plane, {
909 { "FB_ID", fb->id() },
910 });
911 }
912 }
914 void do_flip_output_legacy(unsigned frame_num, const OutputInfo& o)
915 {
916 unsigned cur = frame_num % s_num_buffers;
918 if (!o.fbs.empty()) {
919 auto fb = o.fbs[cur];
921 draw_bar(fb, frame_num);
923 int r = o.crtc->page_flip(*fb, this);
924 ASSERT(r == 0);
925 }
927 for (const PlaneInfo& p : o.planes) {
928 auto fb = p.fbs[cur];
930 draw_bar(fb, frame_num);
932 int r = o.crtc->set_plane(p.plane, *fb,
933 p.x, p.y, p.w, p.h,
934 0, 0, fb->width(), fb->height());
935 ASSERT(r == 0);
936 }
937 }
939 void queue_next()
940 {
941 if (m_card.has_atomic()) {
942 AtomicReq req(m_card);
944 for (auto o : m_outputs)
945 do_flip_output(req, m_frame_num, *o);
947 int r = req.commit(this);
948 if (r)
949 EXIT("Flip commit failed: %d\n", r);
950 } else {
951 ASSERT(m_outputs.size() == 1);
952 do_flip_output_legacy(m_frame_num, *m_outputs[0]);
953 }
954 }
956 Card& m_card;
957 string m_name;
958 vector<const OutputInfo*> m_outputs;
959 unsigned m_frame_num;
961 chrono::steady_clock::time_point m_prev_print;
962 chrono::steady_clock::time_point m_prev_frame;
963 chrono::duration<float> m_slowest_frame;
965 static const unsigned bar_width = 20;
966 static const unsigned bar_speed = 8;
967 };
969 static void main_flip(Card& card, const vector<OutputInfo>& outputs)
970 {
971 fd_set fds;
973 FD_ZERO(&fds);
975 int fd = card.fd();
977 vector<unique_ptr<FlipState>> flipstates;
979 if (!s_flip_sync) {
980 for (const OutputInfo& o : outputs) {
981 auto fs = unique_ptr<FlipState>(new FlipState(card, to_string(o.connector->idx()), { &o }));
982 flipstates.push_back(move(fs));
983 }
984 } else {
985 vector<const OutputInfo*> ois;
987 string name;
988 for (const OutputInfo& o : outputs) {
989 name += to_string(o.connector->idx()) + ",";
990 ois.push_back(&o);
991 }
993 auto fs = unique_ptr<FlipState>(new FlipState(card, name, ois));
994 flipstates.push_back(move(fs));
995 }
997 for (unique_ptr<FlipState>& fs : flipstates)
998 fs->start_flipping();
1000 while (!max_flips_reached) {
1001 int r;
1003 FD_SET(0, &fds);
1004 FD_SET(fd, &fds);
1006 r = select(fd + 1, &fds, NULL, NULL, NULL);
1007 if (r < 0) {
1008 fprintf(stderr, "select() failed with %d: %m\n", errno);
1009 break;
1010 } else if (FD_ISSET(0, &fds)) {
1011 fprintf(stderr, "Exit due to user-input\n");
1012 break;
1013 } else if (FD_ISSET(fd, &fds)) {
1014 card.call_page_flip_handlers();
1015 }
1016 }
1017 }
1019 int main(int argc, char **argv)
1020 {
1021 vector<Arg> output_args = parse_cmdline(argc, argv);
1023 Card card(s_device_path);
1025 if (!card.has_atomic() && s_flip_sync)
1026 EXIT("Synchronized flipping requires atomic modesetting");
1028 ResourceManager resman(card);
1030 vector<OutputInfo> outputs = setups_to_outputs(card, resman, output_args);
1032 if (card.has_atomic()) {
1033 for (OutputInfo& o : outputs) {
1034 if (o.fbs.empty())
1035 continue;
1037 o.primary_plane = resman.reserve_primary_plane(o.crtc);
1039 if (!o.primary_plane)
1040 EXIT("Could not get primary plane for crtc '%u'", o.crtc->id());
1041 }
1042 }
1044 if (!s_flip_mode)
1045 draw_test_patterns(outputs);
1047 print_outputs(outputs);
1049 set_crtcs_n_planes(card, outputs);
1051 printf("press enter to exit\n");
1053 if (s_flip_mode)
1054 main_flip(card, outputs);
1055 else
1056 getchar();
1057 }