Debian Codegraph @

utils/cec-ctl/cec-ctl.cpp

raw
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
4 */
5
6 #include <algorithm>
7 #include <cctype>
8 #include <cerrno>
9 #include <cstring>
10 #include <ctime>
11 #include <map>
12 #include <string>
13 #include <vector>
14
15 #include <dirent.h>
16 #include <fcntl.h>
17 #include <getopt.h>
18 #include <pthread.h>
19 #include <sys/ioctl.h>
20 #include <sys/time.h>
21 #include <unistd.h>
22
23 #include <linux/cec-funcs.h>
24 #include "cec-htng-funcs.h"
25 #include "cec-log.h"
26 #include "cec-parse.h"
27
28 #include "cec-ctl.h"
29 #include "compiler.h"
30
31 static struct timespec start_monotonic;
32 static struct timeval start_timeofday;
33 static time_t valid_until_t;
34 static bool ignore_la[16];
35 static const char *edid_path;
36 static bool is_paused;
37
38 #define CEC_CTL_VERSION 2
39
40 #define POLL_FAKE_OPCODE 256
41 static unsigned short ignore_opcode[257];
42
43 static char options[512];
44
45 #define VENDOR_EXTRA \
46 " --vendor-command payload=<byte>[:<byte>]*\n" \
47 " Send VENDOR_COMMAND message (" xstr(CEC_MSG_VENDOR_COMMAND) ")\n" \
48 " --vendor-command-with-id vendor-id=<val>,cmd=<byte>[:<byte>]*\n" \
49 " Send VENDOR_COMMAND_WITH_ID message (" xstr(CEC_MSG_VENDOR_COMMAND_WITH_ID) ")\n" \
50 " --vendor-remote-button-down rc-code=<byte>[:<byte>]*\n" \
51 " Send VENDOR_REMOTE_BUTTON_DOWN message (" xstr(CEC_MSG_VENDOR_REMOTE_BUTTON_DOWN) ")\n"
52
53 /* Short option list
54
55 Please keep in alphabetical order.
56 That makes it easier to see which short options are still free.
57
58 In general the lower case is used to set something and the upper
59 case is used to retrieve a setting. */
60 enum Option {
61 OptSetAdapter = 'a',
62 OptListDevices = 'A',
63 OptClear = 'C',
64 OptSetDevice = 'd',
65 OptSetDriver = 'D',
66 OptPhysAddrFromEDID = 'e',
67 OptPhysAddrFromEDIDPoll = 'E',
68 OptFrom = 'f',
69 OptHelp = 'h',
70 OptShowLogicalAddress = 'l',
71 OptShowLogicalAddresses = 'L',
72 OptMonitor = 'm',
73 OptMonitorAll = 'M',
74 OptToggleNoReply = 'n',
75 OptNonBlocking = 'N',
76 OptOsdName = 'o',
77 OptPhysAddr = 'p',
78 OptPoll = 'P',
79 OptShowRaw = 'r',
80 OptSkipInfo = 's',
81 OptShowTopology = 'S',
82 OptTo = 't',
83 OptTrace = 'T',
84 OptVerbose = 'v',
85 OptVendorID = 'V',
86 OptWallClock = 'w',
87 OptWaitForMsgs = 'W',
88 OptShowPhysAddr = 'x',
89
90 OptTV = 128,
91 OptRecord,
92 OptTuner,
93 OptPlayback,
94 OptAudio,
95 OptProcessor,
96 OptSwitch,
97 OptCDCOnly,
98 OptUnregistered,
99 OptCECVersion1_4,
100 OptAllowUnregFallback,
101 OptNoRC,
102 OptReplyToFollowers,
103 OptRawMsg,
104 OptTimeout,
105 OptMonitorTime,
106 OptMonitorPin,
107 OptIgnore,
108 OptStorePin,
109 OptAnalyzePin,
110 OptRcTVProfile1,
111 OptRcTVProfile2,
112 OptRcTVProfile3,
113 OptRcTVProfile4,
114 OptRcSrcDevRoot,
115 OptRcSrcDevSetup,
116 OptRcSrcContents,
117 OptRcSrcMediaTop,
118 OptRcSrcMediaContext,
119 OptFeatRecordTVScreen,
120 OptFeatSetOSDString,
121 OptFeatDeckControl,
122 OptFeatSetAudioRate,
123 OptFeatSinkHasARCTx,
124 OptFeatSourceHasARCRx,
125 OptTestReliability,
126 OptTestStandbyWakeupCycle,
127 OptStressTestStandbyWakeupCycle,
128 OptStressTestRandomStandbyWakeupCycle,
129 OptVendorCommand = 508,
130 OptVendorCommandWithID,
131 OptVendorRemoteButtonDown,
132 OptCustomCommand,
133 OptVersion,
134 };
135
136 struct node {
137 int fd;
138 const char *device;
139 unsigned caps;
140 unsigned available_log_addrs;
141 unsigned num_log_addrs;
142 __u16 log_addr_mask;
143 __u16 phys_addr;
144 __u8 log_addr[CEC_MAX_LOG_ADDRS];
145 };
146
147 #define doioctl(n, r, p) cec_named_ioctl((n)->fd, #r, r, p)
148
149 bool verbose;
150
151 using msg_vec = std::vector<cec_msg>;
152
153 static struct option long_options[] = {
154 { "device", required_argument, nullptr, OptSetDevice },
155 { "adapter", required_argument, nullptr, OptSetAdapter },
156 { "driver", required_argument, nullptr, OptSetDriver },
157 { "help", no_argument, nullptr, OptHelp },
158 { "trace", no_argument, nullptr, OptTrace },
159 { "verbose", no_argument, nullptr, OptVerbose },
160 { "wall-clock", no_argument, nullptr, OptWallClock },
161 { "osd-name", required_argument, nullptr, OptOsdName },
162 { "phys-addr-from-edid-poll", required_argument, nullptr, OptPhysAddrFromEDIDPoll },
163 { "phys-addr-from-edid", required_argument, nullptr, OptPhysAddrFromEDID },
164 { "phys-addr", required_argument, nullptr, OptPhysAddr },
165 { "vendor-id", required_argument, nullptr, OptVendorID },
166 { "cec-version-1.4", no_argument, nullptr, OptCECVersion1_4 },
167 { "allow-unreg-fallback", no_argument, nullptr, OptAllowUnregFallback },
168 { "no-rc-passthrough", no_argument, nullptr, OptNoRC },
169 { "reply-to-followers", no_argument, nullptr, OptReplyToFollowers },
170 { "raw-msg", no_argument, nullptr, OptRawMsg },
171 { "timeout", required_argument, nullptr, OptTimeout },
172 { "clear", no_argument, nullptr, OptClear },
173 { "wait-for-msgs", no_argument, nullptr, OptWaitForMsgs },
174 { "monitor", no_argument, nullptr, OptMonitor },
175 { "monitor-all", no_argument, nullptr, OptMonitorAll },
176 { "monitor-pin", no_argument, nullptr, OptMonitorPin },
177 { "monitor-time", required_argument, nullptr, OptMonitorTime },
178 { "ignore", required_argument, nullptr, OptIgnore },
179 { "store-pin", required_argument, nullptr, OptStorePin },
180 { "analyze-pin", required_argument, nullptr, OptAnalyzePin },
181 { "no-reply", no_argument, nullptr, OptToggleNoReply },
182 { "non-blocking", no_argument, nullptr, OptNonBlocking },
183 { "logical-address", no_argument, nullptr, OptShowLogicalAddress },
184 { "logical-addresses", no_argument, nullptr, OptShowLogicalAddresses },
185 { "physical-address", no_argument, nullptr, OptShowPhysAddr },
186 { "to", required_argument, nullptr, OptTo },
187 { "from", required_argument, nullptr, OptFrom },
188 { "skip-info", no_argument, nullptr, OptSkipInfo },
189 { "show-raw", no_argument, nullptr, OptShowRaw },
190 { "show-topology", no_argument, nullptr, OptShowTopology },
191 { "list-devices", no_argument, nullptr, OptListDevices },
192 { "poll", no_argument, nullptr, OptPoll },
193 { "rc-tv-profile-1", no_argument, nullptr, OptRcTVProfile1 },
194 { "rc-tv-profile-2", no_argument, nullptr, OptRcTVProfile2 },
195 { "rc-tv-profile-3", no_argument, nullptr, OptRcTVProfile3 },
196 { "rc-tv-profile-4", no_argument, nullptr, OptRcTVProfile4 },
197 { "rc-src-dev-root", no_argument, nullptr, OptRcSrcDevRoot },
198 { "rc-src-dev-setup", no_argument, nullptr, OptRcSrcDevSetup },
199 { "rc-src-contents", no_argument, nullptr, OptRcSrcContents },
200 { "rc-src-media-top", no_argument, nullptr, OptRcSrcMediaTop },
201 { "rc-src-media-context", no_argument, nullptr, OptRcSrcMediaContext },
202 { "feat-record-tv-screen", no_argument, nullptr, OptFeatRecordTVScreen },
203 { "feat-set-osd-string", no_argument, nullptr, OptFeatSetOSDString },
204 { "feat-deck-control", no_argument, nullptr, OptFeatDeckControl },
205 { "feat-set-audio-rate", no_argument, nullptr, OptFeatSetAudioRate },
206 { "feat-sink-has-arc-tx", no_argument, nullptr, OptFeatSinkHasARCTx },
207 { "feat-source-has-arc-rx", no_argument, nullptr, OptFeatSourceHasARCRx },
208
209 { "tv", no_argument, nullptr, OptTV },
210 { "record", no_argument, nullptr, OptRecord },
211 { "tuner", no_argument, nullptr, OptTuner },
212 { "playback", no_argument, nullptr, OptPlayback },
213 { "audio", no_argument, nullptr, OptAudio },
214 { "processor", no_argument, nullptr, OptProcessor },
215 { "switch", no_argument, nullptr, OptSwitch },
216 { "cdc-only", no_argument, nullptr, OptCDCOnly },
217 { "unregistered", no_argument, nullptr, OptUnregistered },
218 { "help-all", no_argument, nullptr, OptHelpAll },
219
220 { "version", no_argument, nullptr, OptVersion },
221
222 CEC_PARSE_LONG_OPTS
223
224 { "vendor-remote-button-down", required_argument, nullptr, OptVendorRemoteButtonDown }, \
225 { "vendor-command-with-id", required_argument, nullptr, OptVendorCommandWithID }, \
226 { "vendor-command", required_argument, nullptr, OptVendorCommand }, \
227 { "custom-command", required_argument, nullptr, OptCustomCommand }, \
228
229 // Keep old option names for backwards compatibility
230 { "test-power-cycle", optional_argument, nullptr, OptTestStandbyWakeupCycle }, \
231 { "stress-test-power-cycle", required_argument, nullptr, OptStressTestStandbyWakeupCycle }, \
232 { "test-random-power-states", required_argument, nullptr, OptStressTestRandomStandbyWakeupCycle }, \
233
234 { "test-reliability", required_argument, nullptr, OptTestReliability }, \
235 { "test-standby-wakeup-cycle", optional_argument, nullptr, OptTestStandbyWakeupCycle }, \
236 { "stress-test-standby-wakeup-cycle", required_argument, nullptr, OptStressTestStandbyWakeupCycle }, \
237 { "stress-test-random-standby-wakeup-cycle", required_argument, nullptr, OptStressTestRandomStandbyWakeupCycle }, \
238
239 { nullptr, 0, nullptr, 0 }
240 };
241
242 static void print_version()
243 {
244 #define STR(x) #x
245 #define STRING(x) STR(x)
246 printf("cec-ctl %s%s\n", PACKAGE_VERSION, STRING(GIT_COMMIT_CNT));
247 if (strlen(STRING(GIT_SHA)))
248 printf("cec-ctl SHA: %s %s\n", STRING(GIT_SHA), STRING(GIT_COMMIT_DATE));
249 }
250
251 static void usage()
252 {
253 printf("Usage:\n"
254 " -A, --list-devices List all cec devices\n"
255 " -d, --device <dev> Use device <dev> instead of /dev/cec0\n"
256 " If <dev> starts with a digit, then /dev/cec<dev> is used.\n"
257 " -D, --driver <driver> Use a cec device with this driver name\n"
258 " -a, --adapter <adapter> Use a cec device with this adapter name\n"
259 " -p, --phys-addr <addr> Use this physical address\n"
260 " -e, --phys-addr-from-edid <path>\n"
261 " Set physical address from this EDID file\n"
262 " -E, --phys-addr-from-edid-poll <path>\n"
263 " Continuously poll the EDID file for changes, and update the\n"
264 " physical address whenever there is a change\n"
265 " -o, --osd-name <name> Use this OSD name\n"
266 " -V, --vendor-id <id> Use this vendor ID\n"
267 " -x, --physical-address Show the physical address\n"
268 " -l, --logical-address Show first configured logical address\n"
269 " -L, --logical-addresses Show all configured logical addresses\n"
270 " -C, --clear Clear all logical addresses\n"
271 " -n, --no-reply Toggle 'don't wait for a reply'\n"
272 " -N, --non-blocking Transmit messages in non-blocking mode\n"
273 " -t, --to <la> Send message to the given logical address\n"
274 " -f, --from <la> Send message from the given logical address\n"
275 " By default use the first assigned logical address\n"
276 " -r, --show-raw Show the raw CEC message (hex values)\n"
277 " -s, --skip-info Skip Driver Info output\n"
278 " -S, --show-topology Show the CEC topology\n"
279 " -P, --poll Send poll message\n"
280 " -h, --help Display this help message\n"
281 " --help-all Show all help messages\n"
282 " -T, --trace Trace all called ioctls\n"
283 " -v, --verbose Turn on verbose reporting\n"
284 " --version Show version information\n"
285 " -w, --wall-clock Show timestamps as wall-clock time (implies -v)\n"
286 " -W, --wait-for-msgs Wait for messages and events for up to --monitor-time secs.\n"
287 " --cec-version-1.4 Use CEC Version 1.4 instead of 2.0\n"
288 " --allow-unreg-fallback Allow fallback to Unregistered\n"
289 " --no-rc-passthrough Disable the RC passthrough\n"
290 " --reply-to-followers The reply will be sent to followers as well\n"
291 " --raw-msg Transmit the message without validating it (must be root)\n"
292 " --timeout <ms> Set the reply timeout in milliseconds (default is 1000 ms)\n"
293 "\n"
294 " --tv This is a TV\n"
295 " --record This is a recording and playback device\n"
296 " --tuner This is a tuner device\n"
297 " --playback This is a playback device\n"
298 " --audio This is an audio system device\n"
299 " --processor This is a processor device\n"
300 " --switch This is a pure CEC switch\n"
301 " --cdc-only This is a CDC-only device\n"
302 " --unregistered This is an unregistered device\n"
303 "\n"
304 " --feat-record-tv-screen Signal the Record TV Screen feature\n"
305 " --feat-set-osd-string Signal the Set OSD String feature\n"
306 " --feat-deck-control Signal the Deck Control feature\n"
307 " --feat-set-audio-rate Signal the Set Audio Rate feature\n"
308 " --feat-sink-has-arc-tx Signal the sink ARC Tx feature\n"
309 " --feat-source-has-arc-rx Signal the source ARC Rx feature\n"
310 "\n"
311 " --rc-tv-profile-1 Signal RC TV Profile 1\n"
312 " --rc-tv-profile-2 Signal RC TV Profile 2\n"
313 " --rc-tv-profile-3 Signal RC TV Profile 3\n"
314 " --rc-tv-profile-4 Signal RC TV Profile 4\n"
315 "\n"
316 " --rc-src-dev-root Signal that the RC source has a Dev Root Menu\n"
317 " --rc-src-dev-setup Signal that the RC source has a Dev Setup Menu\n"
318 " --rc-src-contents Signal that the RC source has a Contents Menu\n"
319 " --rc-src-media-top Signal that the RC source has a Media Top Menu\n"
320 " --rc-src-media-context Signal that the RC source has a Media Context Menu\n"
321 "\n"
322 " -m, --monitor Monitor CEC traffic\n"
323 " -M, --monitor-all Monitor all CEC traffic\n"
324 " --monitor-pin Monitor low-level CEC pin\n"
325 " --monitor-time <secs> Monitor for <secs> seconds (default is forever)\n"
326 " --ignore <la>,<opcode> Ignore messages from logical address <la> and opcode\n"
327 " <opcode> when monitoring. 'all' can be used for <la>\n"
328 " or <opcode> to match all logical addresses or opcodes.\n"
329 " To ignore poll messages use 'poll' as <opcode>.\n"
330 " --store-pin <to> Store the low-level CEC pin changes to the file <to>.\n"
331 " Use - for stdout.\n"
332 " --analyze-pin <from> Analyze the low-level CEC pin changes from the file <from>.\n"
333 " Use - for stdin.\n"
334 " --test-reliability <secs>\n"
335 " Test CEC line reliability. It continuously transmits <Give Physical Address>\n"
336 " for <secs> seconds, checking that the broadcast reply is always the same.\n"
337 " If <secs> is 0, then keep trying forever.\n"
338 " --test-standby-wakeup-cycle [polls=<n>][,sleep=<secs>][,hpd-may-be-low=<0/1>]\n"
339 " Test standby-wakeup cycle behavior of the display. It polls up to\n"
340 " <n> times (default 15), waiting for a state change. If\n"
341 " that fails it waits <secs> seconds (default 10) before\n"
342 " retrying this.\n"
343 " If <hpd-may-be-low> is 1, then the HPD is allowed to be low when in standby.\n"
344 " --stress-test-standby-wakeup-cycle cnt=<count>[,polls=<n>][,max-sleep=<maxsecs>][,min-sleep=<minsecs>][,seed=<seed>][,repeats=<reps>][,sleep-before-on=<secs1>][,sleep-before-off=<secs2>][,hpd-may-be-low=<0/1>]\n"
345 " Standby-Wakeup cycle display <count> times. If 0, then never stop.\n"
346 " It polls up to <n> times (default 30), waiting for a state change.\n"
347 " If <maxsecs> is non-zero (0 is the default), then sleep for\n"
348 " a random number of seconds between <minsecs> (0 is the default) and <maxsecs>\n"
349 " before each <Standby> or <Image View On> message.\n"
350 " If <seed> is specified, then set the randomizer seed to\n"
351 " that value instead of using the current time as seed.\n"
352 " If <reps> is specified, then repeat the <Image View On> and\n"
353 " <Standby> up to <reps> times. Note: should not be needed!\n"
354 " If <secs1> is specified, then sleep for <secs1> seconds\n"
355 " before transmitting <Image View On>.\n"
356 " If <secs2> is specified, then sleep for <secs2> seconds\n"
357 " before transmitting <Standby>.\n"
358 " If <hpd-may-be-low> is 1, then the HPD is allowed to be low when in standby.\n"
359 " --stress-test-random-standby-wakeup-cycle cnt=<count>[,max-sleep=<maxsecs>][,min-sleep=<minsecs>][,seed=<seed>][,hpd-may-be-low=<0/1>]\n"
360 " Randomly transmit <Standby> or <Image View On> up to <count> times.\n"
361 " If <count> is 0, then never stop. After each transmit wait between\n"
362 " <min-sleep> (default 0) and <max-sleep> (default 10) seconds.\n"
363 " If <seed> is specified, then set the randomizer seed to\n"
364 " that value instead of using the current time as seed.\n"
365 " If <hpd-may-be-low> is 1, then the HPD is allowed to be low when in standby.\n"
366 " This test does not check if the display reached the new state,\n"
367 " it checks if the display can handle this situation without\n"
368 " locking up. After every 10 cycles it attempts to properly\n"
369 " wake up the display and check if that works. If not, this test fails.\n"
370 "\n"
371 CEC_PARSE_USAGE
372 "\n"
373 " --custom-command cmd=<byte>[,payload=<byte>[:<byte>]*]\n"
374 " Send custom message\n"
375 );
376 }
377
378 static const char *power_status2s(__u8 power_status)
379 {
380 switch (power_status) {
381 case CEC_OP_POWER_STATUS_ON:
382 return "On";
383 case CEC_OP_POWER_STATUS_STANDBY:
384 return "Standby";
385 case CEC_OP_POWER_STATUS_TO_ON:
386 return "In transition Standby to On";
387 case CEC_OP_POWER_STATUS_TO_STANDBY:
388 return "In transition On to Standby";
389 default:
390 return "Unknown";
391 }
392 }
393
394 std::string ts2s(__u64 ts)
395 {
396 static char buf[64];
397 static unsigned last_secs;
398 static time_t last_t;
399 std::string s;
400 struct timeval sub = {};
401 struct timeval res;
402 unsigned secs;
403 __s64 diff;
404 time_t t;
405
406 if (!options[OptWallClock]) {
407 sprintf(buf, "%llu.%06llus", ts / 1000000000, (ts % 1000000000) / 1000);
408 return buf;
409 }
410 diff = ts - start_monotonic.tv_sec * 1000000000ULL - start_monotonic.tv_nsec;
411 if (diff >= 0) {
412 sub.tv_sec = diff / 1000000000ULL;
413 sub.tv_usec = (diff % 1000000000ULL) / 1000;
414 }
415 timeradd(&start_timeofday, &sub, &res);
416 t = res.tv_sec;
417 if (t >= valid_until_t) {
418 struct tm tm = *localtime(&t);
419 last_secs = tm.tm_min * 60 + tm.tm_sec;
420 last_t = t;
421 valid_until_t = t + 60 - last_secs;
422 strftime(buf, sizeof(buf), "%a %b %e %T.000000", &tm);
423 }
424 secs = last_secs + t - last_t;
425 sprintf(buf + 14, "%02u:%02u.%06llu", secs / 60, secs % 60, (__u64)res.tv_usec);
426 return buf;
427 }
428
429 std::string ts2s(double ts)
430 {
431 __u64 t = static_cast<__u64>(ts * 1000000000.0);
432
433 if (!options[OptWallClock]) {
434 char buf[64];
435
436 sprintf(buf, "%llu.%06llu", t / 1000000000, (t % 1000000000) / 1000);
437 return buf;
438 }
439 return ts2s(t);
440 }
441
442 static __u64 current_ts()
443 {
444 struct timespec ts;
445
446 clock_gettime(CLOCK_MONOTONIC, &ts);
447 return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
448 }
449
450 static int cec_named_ioctl(int fd, const char *name,
451 unsigned long int request, void *parm)
452 {
453 int retval = ioctl(fd, request, parm);
454 int e;
455
456 e = retval == 0 ? 0 : errno;
457 if (options[OptTrace])
458 printf("\t\t%s returned %d (%s)\n",
459 name, retval, strerror(e));
460
461 return retval == -1 ? e : (retval ? -1 : 0);
462 }
463
464 static void print_bytes(const __u8 *bytes, unsigned len)
465 {
466 for (unsigned i = 0; i < len; i++)
467 printf(" 0x%02x", bytes[i]);
468 printf(" (");
469 for (unsigned i = 0; i < len; i++)
470 if (bytes[i] >= 32 && bytes[i] <= 127)
471 printf("%c", bytes[i]);
472 else
473 printf(" ");
474 printf(")");
475 }
476
477 static void log_raw_msg(const struct cec_msg *msg)
478 {
479 printf("\tRaw:");
480 print_bytes(msg->msg, msg->len);
481 printf("\n");
482 }
483
484 static const char *event2s(__u32 event)
485 {
486 switch (event) {
487 case CEC_EVENT_STATE_CHANGE:
488 return "State Change";
489 case CEC_EVENT_LOST_MSGS:
490 return "Lost Messages";
491 case CEC_EVENT_PIN_CEC_LOW:
492 return "CEC Pin Low";
493 case CEC_EVENT_PIN_CEC_HIGH:
494 return "CEC Pin High";
495 case CEC_EVENT_PIN_HPD_LOW:
496 return "HPD Pin Low";
497 case CEC_EVENT_PIN_HPD_HIGH:
498 return "HPD Pin High";
499 case CEC_EVENT_PIN_5V_LOW:
500 return "5V Pin Low";
501 case CEC_EVENT_PIN_5V_HIGH:
502 return "5V Pin High";
503 default:
504 return "Unknown";
505 }
506 }
507
508 static void log_event(struct cec_event &ev, bool show, bool pin_logging = false)
509 {
510 bool is_high = ev.event == CEC_EVENT_PIN_CEC_HIGH;
511 bool is_initial = ev.flags & CEC_EVENT_FL_INITIAL_STATE;
512 __u16 pa;
513
514 if (ev.event != CEC_EVENT_PIN_CEC_LOW && ev.event != CEC_EVENT_PIN_CEC_HIGH &&
515 ev.event != CEC_EVENT_PIN_HPD_LOW && ev.event != CEC_EVENT_PIN_HPD_HIGH &&
516 ev.event != CEC_EVENT_PIN_5V_LOW && ev.event != CEC_EVENT_PIN_5V_HIGH)
517 printf("\n");
518
519 if ((ev.flags & CEC_EVENT_FL_DROPPED_EVENTS) && show)
520 printf("(warn: %s events were lost)\n", event2s(ev.event));
521 if (show) {
522 if (is_initial) {
523 printf("Initial ");
524 } else if (ev.event != CEC_EVENT_PIN_CEC_LOW && ev.event != CEC_EVENT_PIN_CEC_HIGH) {
525 if (pin_logging)
526 printf("%s: ", ts2s(ev.ts / 1000000000.0).c_str());
527 else
528 printf("%s: ", ts2s(ev.ts).c_str());
529 }
530 }
531
532 switch (ev.event) {
533 case CEC_EVENT_STATE_CHANGE:
534 pa = ev.state_change.phys_addr;
535 if (show && pin_logging)
536 printf("Event: State Change: PA: %x.%x.%x.%x, LA mask: 0x%04x\n",
537 cec_phys_addr_exp(pa), ev.state_change.log_addr_mask);
538 else if (show)
539 printf("Event: State Change: PA: %x.%x.%x.%x, LA mask: 0x%04x, Conn Info: %s\n",
540 cec_phys_addr_exp(pa),
541 ev.state_change.log_addr_mask,
542 ev.state_change.have_conn_info ? "yes" : "no");
543 break;
544 case CEC_EVENT_LOST_MSGS:
545 if (show)
546 printf("Event: Lost %d messages\n",
547 ev.lost_msgs.lost_msgs);
548 break;
549 case CEC_EVENT_PIN_CEC_LOW:
550 case CEC_EVENT_PIN_CEC_HIGH:
551 if ((ev.flags & CEC_EVENT_FL_INITIAL_STATE) && show)
552 printf("Event: CEC Pin %s\n", is_high ? "High" : "Low");
553
554 log_event_pin(is_high, ev.ts, show);
555 return;
556 case CEC_EVENT_PIN_HPD_LOW:
557 case CEC_EVENT_PIN_HPD_HIGH:
558 if (show)
559 printf("Event: HPD Pin %s\n",
560 ev.event == CEC_EVENT_PIN_HPD_HIGH ? "High" : "Low");
561 break;
562 case CEC_EVENT_PIN_5V_LOW:
563 case CEC_EVENT_PIN_5V_HIGH:
564 if (show)
565 printf("Event: 5V Pin %s\n",
566 ev.event == CEC_EVENT_PIN_5V_HIGH ? "High" : "Low");
567 break;
568 default:
569 if (show)
570 printf("Event: Unknown (0x%x)\n", ev.event);
571 break;
572 }
573 }
574
575 /*
576 * Bits 23-8 contain the physical address, bits 0-3 the logical address
577 * (equal to the index).
578 */
579 static __u32 phys_addrs[16];
580
581 static int showTopologyDevice(struct node *node, unsigned i, unsigned la)
582 {
583 struct cec_msg msg;
584 char osd_name[15];
585
586 printf("\tSystem Information for device %d (%s) from device %d (%s):\n",
587 i, cec_la2s(i), la & 0xf, cec_la2s(la));
588
589 cec_msg_init(&msg, la, i);
590 cec_msg_get_cec_version(&msg, true);
591 doioctl(node, CEC_TRANSMIT, &msg);
592 printf("\t\tCEC Version : %s\n",
593 (!cec_msg_status_is_ok(&msg)) ? cec_status2s(msg).c_str() : cec_version2s(msg.msg[2]));
594
595 cec_msg_init(&msg, la, i);
596 cec_msg_give_physical_addr(&msg, true);
597 doioctl(node, CEC_TRANSMIT, &msg);
598 printf("\t\tPhysical Address : ");
599 if (!cec_msg_status_is_ok(&msg)) {
600 printf("%s\n", cec_status2s(msg).c_str());
601 } else {
602 __u16 phys_addr = (msg.msg[2] << 8) | msg.msg[3];
603
604 printf("%x.%x.%x.%x\n", cec_phys_addr_exp(phys_addr));
605 printf("\t\tPrimary Device Type : %s\n",
606 cec_prim_type2s(msg.msg[4]));
607 phys_addrs[i] = (phys_addr << 8) | i;
608 }
609
610 cec_msg_init(&msg, la, i);
611 cec_msg_give_device_vendor_id(&msg, true);
612 doioctl(node, CEC_TRANSMIT, &msg);
613 printf("\t\tVendor ID : ");
614 if (!cec_msg_status_is_ok(&msg)) {
615 printf("%s\n", cec_status2s(msg).c_str());
616 } else {
617 __u32 vendor_id = msg.msg[2] << 16 | msg.msg[3] << 8 | msg.msg[4];
618 const char *vendor = cec_vendor2s(vendor_id);
619
620 if (vendor)
621 printf("0x%06x (%s)\n", vendor_id, vendor);
622 else
623 printf("0x%06x, %u\n", vendor_id, vendor_id);
624 }
625
626 cec_msg_init(&msg, la, i);
627 cec_msg_give_osd_name(&msg, true);
628 doioctl(node, CEC_TRANSMIT, &msg);
629 cec_ops_set_osd_name(&msg, osd_name);
630 printf("\t\tOSD Name : ");
631 if (cec_msg_status_is_ok(&msg))
632 printf("'%s'\n", osd_name);
633 else
634 printf("%s\n", cec_status2s(msg).c_str());
635
636 cec_msg_init(&msg, la, i);
637 cec_msg_get_menu_language(&msg, true);
638 doioctl(node, CEC_TRANSMIT, &msg);
639 if (cec_msg_status_is_ok(&msg)) {
640 char language[4];
641
642 cec_ops_set_menu_language(&msg, language);
643 language[3] = 0;
644 printf("\t\tMenu Language : %s\n", language);
645 }
646
647 cec_msg_init(&msg, la, i);
648 cec_msg_give_device_power_status(&msg, true);
649 doioctl(node, CEC_TRANSMIT, &msg);
650 if (cec_msg_status_is_ok(&msg)) {
651 __u8 pwr;
652
653 cec_ops_report_power_status(&msg, &pwr);
654 printf("\t\tPower Status : %s\n",
655 power_status2s(pwr));
656 }
657
658 cec_msg_init(&msg, la, i);
659 cec_msg_give_features(&msg, true);
660 doioctl(node, CEC_TRANSMIT, &msg);
661 if (cec_msg_status_is_ok(&msg)) {
662 __u8 vers, all_dev_types;
663 const __u8 *rc, *feat;
664
665 cec_ops_report_features(&msg, &vers, &all_dev_types, &rc, &feat);
666
667 printf("\t\tFeatures :\n");
668 printf("\t\t CEC Version : %s\n", cec_version2s(vers));
669 printf("\t\t All Device Types : %s\n",
670 cec_all_dev_types2s(all_dev_types).c_str());
671 while (rc) {
672 if (*rc & 0x40) {
673 printf("\t\t RC Source Profile :\n%s",
674 cec_rc_src_prof2s(*rc, "\t").c_str());
675 } else {
676 const char *s = "Reserved";
677
678 switch (*rc & 0xf) {
679 case 0:
680 s = "None";
681 break;
682 case 2:
683 s = "RC Profile 1";
684 break;
685 case 6:
686 s = "RC Profile 2";
687 break;
688 case 10:
689 s = "RC Profile 3";
690 break;
691 case 14:
692 s = "RC Profile 4";
693 break;
694 }
695 printf("\t\t RC TV Profile : %s\n", s);
696 }
697 if (!(*rc++ & CEC_OP_FEAT_EXT))
698 break;
699 }
700
701 while (feat) {
702 printf("\t\t Device Features :\n%s",
703 cec_dev_feat2s(*feat, "\t").c_str());
704 if (!(*feat++ & CEC_OP_FEAT_EXT))
705 break;
706 }
707 }
708 return 0;
709 }
710
711 static __u16 calc_mask(__u16 pa)
712 {
713 if (pa & 0xf)
714 return 0xffff;
715 if (pa & 0xff)
716 return 0xfff0;
717 if (pa & 0xfff)
718 return 0xff00;
719 if (pa & 0xffff)
720 return 0xf000;
721 return 0;
722 }
723
724 static int showTopology(struct node *node)
725 {
726 struct cec_msg msg;
727 struct cec_log_addrs laddrs = { };
728
729 if (!(node->caps & CEC_CAP_TRANSMIT))
730 return -ENOTTY;
731
732 doioctl(node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
733
734 if (!laddrs.num_log_addrs)
735 return 0;
736
737 for (unsigned i = 0; i < 15; i++) {
738 int ret;
739
740 cec_msg_init(&msg, laddrs.log_addr[0], i);
741 ret = doioctl(node, CEC_TRANSMIT, &msg);
742
743 if (ret)
744 continue;
745
746 if (msg.tx_status & CEC_TX_STATUS_OK)
747 showTopologyDevice(node, i, laddrs.log_addr[0]);
748 else if (verbose && !(msg.tx_status & CEC_TX_STATUS_MAX_RETRIES))
749 printf("\t\t%s for addr %d\n", cec_status2s(msg).c_str(), i);
750 }
751
752 __u32 pas[16];
753
754 memcpy(pas, phys_addrs, sizeof(pas));
755 std::sort(pas, pas + 16);
756 int level = 0;
757 unsigned last_pa_mask = 0;
758
759 if ((pas[0] >> 8) == 0xffff)
760 return 0;
761
762 printf("\n\tTopology:\n\n");
763 for (unsigned int i : pas) {
764 __u16 pa = i >> 8;
765 __u8 la = i & 0xf;
766
767 if (pa == 0xffff)
768 break;
769
770 __u16 pa_mask = calc_mask(pa);
771
772 while (last_pa_mask < pa_mask) {
773 last_pa_mask = (last_pa_mask >> 4) | 0xf000;
774 level++;
775 }
776 while (last_pa_mask > pa_mask) {
777 last_pa_mask <<= 4;
778 level--;
779 }
780 printf("\t");
781 if (level < 1)
782 level = 1;
783 for (int j = 0; j < level; j++)
784 printf(" ");
785 printf("%x.%x.%x.%x: %s\n", cec_phys_addr_exp(pa),
786 cec_la2s(la));
787 }
788 return 0;
789 }
790
791 static inline unsigned response_time_ms(const struct cec_msg &msg)
792 {
793 unsigned ms = (msg.rx_ts - msg.tx_ts) / 1000000;
794
795 // Compensate for the time it took (approx.) to receive the
796 // message.
797 if (ms >= msg.len * 24)
798 return ms - msg.len * 24;
799 return 0;
800 }
801
802 static void generate_eob_event(__u64 ts, FILE *fstore)
803 {
804 if (!eob_ts || eob_ts_max >= ts)
805 return;
806
807 struct cec_event ev_eob = {
808 eob_ts,
809 CEC_EVENT_PIN_CEC_HIGH
810 };
811
812 if (fstore) {
813 fprintf(fstore, "%llu.%09llu 0x%x\n",
814 ev_eob.ts / 1000000000, ev_eob.ts % 1000000000,
815 ev_eob.event - CEC_EVENT_PIN_CEC_LOW);
816 fflush(fstore);
817 }
818 log_event(ev_eob, fstore != stdout, true);
819 }
820
821 static void show_msg(const cec_msg &msg)
822 {
823 __u8 from = cec_msg_initiator(&msg);
824 __u8 to = cec_msg_destination(&msg);
825
826 if (ignore_la[from])
827 return;
828 if ((msg.len == 1 && (ignore_opcode[POLL_FAKE_OPCODE] & (1 << from))) ||
829 (msg.len > 1 && (ignore_opcode[msg.msg[1]] & (1 << from))))
830 return;
831
832 bool transmitted = msg.tx_status != 0;
833 printf("%s %s to %s (%d to %d): ",
834 transmitted ? "Transmitted by" : "Received from",
835 cec_la2s(from), to == 0xf ? "all" : cec_la2s(to), from, to);
836 cec_log_msg(&msg);
837 if (options[OptShowRaw])
838 log_raw_msg(&msg);
839 std::string status;
840 if ((msg.tx_status & ~CEC_TX_STATUS_OK) ||
841 (msg.rx_status & ~CEC_RX_STATUS_OK)) {
842 status = std::string(" ") + cec_status2s(msg);
843 if (verbose)
844 printf("\tTimestamp: %s\n", ts2s(current_ts()).c_str());
845 }
846 if (verbose && transmitted)
847 printf("\tSequence: %u Tx Timestamp: %s%s\n",
848 msg.sequence, ts2s(msg.tx_ts).c_str(),
849 status.c_str());
850 else if (verbose && !transmitted)
851 printf("\tSequence: %u Rx Timestamp: %s%s\n",
852 msg.sequence, ts2s(msg.rx_ts).c_str(),
853 status.c_str());
854 }
855
856 static void wait_for_msgs(const struct node &node, __u32 monitor_time)
857 {
858 fd_set rd_fds;
859 fd_set ex_fds;
860 int fd = node.fd;
861 time_t t;
862
863 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
864 t = time(nullptr) + monitor_time;
865
866 while (!monitor_time || time(nullptr) < t) {
867 struct timeval tv = { 1, 0 };
868 int res;
869
870 fflush(stdout);
871 FD_ZERO(&rd_fds);
872 FD_ZERO(&ex_fds);
873 FD_SET(fd, &rd_fds);
874 FD_SET(fd, &ex_fds);
875 res = select(fd + 1, &rd_fds, nullptr, &ex_fds, &tv);
876 if (res < 0)
877 break;
878 if (FD_ISSET(fd, &ex_fds)) {
879 struct cec_event ev;
880
881 if (doioctl(&node, CEC_DQEVENT, &ev))
882 continue;
883 log_event(ev, true);
884 }
885 if (FD_ISSET(fd, &rd_fds)) {
886 struct cec_msg msg = { };
887
888 res = doioctl(&node, CEC_RECEIVE, &msg);
889 if (res == ENODEV) {
890 fprintf(stderr, "Device was disconnected.\n");
891 break;
892 }
893 if (!res)
894 show_msg(msg);
895 }
896 }
897 }
898
899 #define MONITOR_STATE_CHANGE 0x10
900 #define MONITOR_FL_DROPPED_EVENTS (1 << 16)
901
902 static void monitor(const struct node &node, __u32 monitor_time, const char *store_pin)
903 {
904 __u32 monitor = CEC_MODE_MONITOR;
905 fd_set rd_fds;
906 fd_set ex_fds;
907 int fd = node.fd;
908 FILE *fstore = nullptr;
909 time_t t, start_minute;
910
911 if (options[OptMonitorAll])
912 monitor = CEC_MODE_MONITOR_ALL;
913 else if (options[OptMonitorPin])
914 monitor = CEC_MODE_MONITOR_PIN;
915
916 if (!(node.caps & CEC_CAP_MONITOR_ALL) && monitor == CEC_MODE_MONITOR_ALL) {
917 fprintf(stderr, "Monitor All mode is not supported, falling back to regular monitoring\n");
918 monitor = CEC_MODE_MONITOR;
919 }
920 if (!(node.caps & CEC_CAP_MONITOR_PIN) && monitor == CEC_MODE_MONITOR_PIN) {
921 fprintf(stderr, "Monitor Pin mode is not supported\n");
922 usage();
923 std::exit(EXIT_FAILURE);
924 }
925
926 if (doioctl(&node, CEC_S_MODE, &monitor)) {
927 fprintf(stderr, "Selecting monitor mode failed, you may have to run this as root.\n");
928 return;
929 }
930
931 if (monitor == CEC_MODE_MONITOR_PIN) {
932 struct cec_log_addrs laddrs = { };
933
934 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
935 if (laddrs.log_addr_mask && !options[OptSkipInfo]) {
936 fprintf(stderr, "note: this CEC adapter is configured. This may cause inaccurate event\n");
937 fprintf(stderr, " timestamps. It is recommended to unconfigure the adapter (cec-ctl -C)\n");
938 }
939 }
940
941 if (store_pin) {
942 if (!strcmp(store_pin, "-"))
943 fstore = stdout;
944 else
945 fstore = fopen(store_pin, "w+");
946 if (fstore == nullptr) {
947 fprintf(stderr, "Failed to open %s: %s\n", store_pin,
948 strerror(errno));
949 std::exit(EXIT_FAILURE);
950 }
951 fprintf(fstore, "# cec-ctl --store-pin\n");
952 fprintf(fstore, "# version %d\n", CEC_CTL_VERSION);
953 fprintf(fstore, "# start_monotonic %llu.%09llu\n",
954 (__u64)start_monotonic.tv_sec, (__u64)start_monotonic.tv_nsec);
955 fprintf(fstore, "# start_timeofday %llu.%06llu\n",
956 (__u64)start_timeofday.tv_sec, (__u64)start_timeofday.tv_usec);
957 fprintf(fstore, "# log_addr_mask 0x%04x\n", node.log_addr_mask);
958 fprintf(fstore, "# phys_addr %x.%x.%x.%x\n",
959 cec_phys_addr_exp(node.phys_addr));
960 }
961
962 if (fstore != stdout)
963 printf("\n");
964
965 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
966 start_minute = time(nullptr);
967 t = start_minute + monitor_time;
968
969 while (1) {
970 time_t now = time(nullptr);
971 struct timeval tv = { 1, 0 };
972 bool pin_event = false;
973 int res;
974
975 fflush(stdout);
976 if (monitor_time && now >= t)
977 break;
978 FD_ZERO(&rd_fds);
979 FD_ZERO(&ex_fds);
980 FD_SET(fd, &rd_fds);
981 FD_SET(fd, &ex_fds);
982 res = select(fd + 1, &rd_fds, nullptr, &ex_fds, &tv);
983 if (res < 0)
984 break;
985 if (store_pin && now - start_minute > 60 &&
986 (FD_ISSET(fd, &rd_fds) || FD_ISSET(fd, &ex_fds))) {
987 /*
988 * The drift between the monotonic and wallclock
989 * time can be quite high (1 ms per minute), so
990 * report this once a minute to ensure a sane
991 * wallclock time when analyzing this later.
992 */
993 clock_gettime(CLOCK_MONOTONIC, &start_monotonic);
994 gettimeofday(&start_timeofday, nullptr);
995 fprintf(fstore, "# start_monotonic %llu.%09llu\n",
996 (__u64)start_monotonic.tv_sec, (__u64)start_monotonic.tv_nsec);
997 fprintf(fstore, "# start_timeofday %llu.%06llu\n",
998 (__u64)start_timeofday.tv_sec, (__u64)start_timeofday.tv_usec);
999 fflush(fstore);
1000 start_minute = now;
1001 }
1002 if (FD_ISSET(fd, &rd_fds)) {
1003 struct cec_msg msg = { };
1004
1005 res = doioctl(&node, CEC_RECEIVE, &msg);
1006 if (res == ENODEV) {
1007 fprintf(stderr, "Device was disconnected.\n");
1008 break;
1009 }
1010 if (!res && fstore != stdout)
1011 show_msg(msg);
1012 }
1013 if (FD_ISSET(fd, &ex_fds)) {
1014 struct cec_event ev;
1015
1016 if (doioctl(&node, CEC_DQEVENT, &ev))
1017 continue;
1018 if (ev.event == CEC_EVENT_PIN_CEC_LOW ||
1019 ev.event == CEC_EVENT_PIN_CEC_HIGH ||
1020 ev.event == CEC_EVENT_PIN_HPD_LOW ||
1021 ev.event == CEC_EVENT_PIN_HPD_HIGH ||
1022 ev.event == CEC_EVENT_PIN_5V_LOW ||
1023 ev.event == CEC_EVENT_PIN_5V_HIGH)
1024 pin_event = true;
1025 if (ev.event == CEC_EVENT_PIN_CEC_LOW ||
1026 ev.event == CEC_EVENT_PIN_CEC_HIGH)
1027 generate_eob_event(ev.ts, fstore);
1028 if (fstore && ev.event == CEC_EVENT_STATE_CHANGE) {
1029 unsigned int v = MONITOR_STATE_CHANGE;
1030
1031 if (ev.flags & CEC_EVENT_FL_DROPPED_EVENTS)
1032 v |= MONITOR_FL_DROPPED_EVENTS;
1033
1034 fprintf(fstore, "%llu.%09llu 0x%x 0x%04x 0x%04x\n",
1035 ev.ts / 1000000000, ev.ts % 1000000000, v,
1036 ev.state_change.phys_addr, ev.state_change.log_addr_mask);
1037 fflush(fstore);
1038 } else if (fstore && pin_event) {
1039 unsigned int v = ev.event - CEC_EVENT_PIN_CEC_LOW;
1040
1041 if (ev.flags & CEC_EVENT_FL_DROPPED_EVENTS)
1042 v |= MONITOR_FL_DROPPED_EVENTS;
1043 fprintf(fstore, "%llu.%09llu 0x%x\n",
1044 ev.ts / 1000000000, ev.ts % 1000000000, v);
1045 fflush(fstore);
1046 }
1047 if (!pin_event || options[OptMonitorPin])
1048 log_event(ev, fstore != stdout, true);
1049 }
1050 if (!res && eob_ts) {
1051 struct timespec ts;
1052 __u64 ts64;
1053
1054 clock_gettime(CLOCK_MONOTONIC, &ts);
1055 ts64 = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
1056 generate_eob_event(ts64, fstore);
1057 }
1058 }
1059 if (fstore && fstore != stdout)
1060 fclose(fstore);
1061 }
1062
1063 static unsigned read_val(char **p)
1064 {
1065 unsigned v = 0;
1066
1067 while (**p == ' ')
1068 (*p)++;
1069
1070 if ((*p)[0] == '0' && (*p)[1] == 'x') {
1071 (*p) += 2;
1072 while (isxdigit(**p)) {
1073 if (isdigit(**p))
1074 v = v * 16 + **p - '0';
1075 else
1076 v = v * 16 + tolower(**p) - 'a' + 10;
1077 (*p)++;
1078 }
1079 } else {
1080 while (isdigit(**p)) {
1081 v = v * 10 + **p - '0';
1082 (*p)++;
1083 }
1084 }
1085 return v;
1086 }
1087
1088 static void analyze(const char *analyze_pin)
1089 {
1090 FILE *fanalyze;
1091 struct cec_event ev = { };
1092 unsigned long tv_sec, tv_nsec, tv_usec;
1093 unsigned version;
1094 unsigned log_addr_mask;
1095 unsigned pa1, pa2, pa3, pa4;
1096 unsigned line = 1;
1097 char s[100];
1098
1099 if (!strcmp(analyze_pin, "-"))
1100 fanalyze = stdin;
1101 else
1102 fanalyze = fopen(analyze_pin, "r");
1103 if (fanalyze == nullptr) {
1104 fprintf(stderr, "Failed to open %s: %s\n", analyze_pin,
1105 strerror(errno));
1106 std::exit(EXIT_FAILURE);
1107 }
1108 if (!fgets(s, sizeof(s), fanalyze) ||
1109 strcmp(s, "# cec-ctl --store-pin\n"))
1110 goto err;
1111 line++;
1112 if (!fgets(s, sizeof(s), fanalyze) ||
1113 sscanf(s, "# version %u\n", &version) != 1)
1114 goto err;
1115 if (version > CEC_CTL_VERSION) {
1116 fprintf(stderr, "Pin store file has version %d, but we only support up to version %d\n",
1117 version, CEC_CTL_VERSION);
1118 std::exit(EXIT_FAILURE);
1119 }
1120 line++;
1121 if (!fgets(s, sizeof(s), fanalyze) ||
1122 sscanf(s, "# start_monotonic %lu.%09lu\n", &tv_sec, &tv_nsec) != 2 ||
1123 tv_nsec >= 1000000000)
1124 goto err;
1125 start_monotonic.tv_sec = tv_sec;
1126 start_monotonic.tv_nsec = tv_nsec;
1127 line++;
1128 if (!fgets(s, sizeof(s), fanalyze) ||
1129 sscanf(s, "# start_timeofday %lu.%06lu\n", &tv_sec, &tv_usec) != 2 ||
1130 tv_usec >= 1000000)
1131 goto err;
1132 start_timeofday.tv_sec = tv_sec;
1133 start_timeofday.tv_usec = tv_usec;
1134 line++;
1135 if (!fgets(s, sizeof(s), fanalyze) ||
1136 sscanf(s, "# log_addr_mask 0x%04x\n", &log_addr_mask) != 1)
1137 goto err;
1138 line++;
1139 if (!fgets(s, sizeof(s), fanalyze) ||
1140 sscanf(s, "# phys_addr %x.%x.%x.%x\n", &pa1, &pa2, &pa3, &pa4) != 4)
1141 goto err;
1142 line++;
1143
1144 printf("Physical Address: %x.%x.%x.%x\n", pa1, pa2, pa3, pa4);
1145 printf("Logical Address Mask: 0x%04x\n\n", log_addr_mask);
1146
1147 while (fgets(s, sizeof(s), fanalyze)) {
1148 unsigned event;
1149 char *p = s;
1150
1151 if (s[0] == '#') {
1152 if (sscanf(s, "# start_monotonic %lu.%09lu\n", &tv_sec, &tv_nsec) == 2 &&
1153 tv_nsec < 1000000000) {
1154 start_monotonic.tv_sec = tv_sec;
1155 start_monotonic.tv_nsec = tv_nsec;
1156 } else if (sscanf(s, "# start_timeofday %lu.%06lu\n", &tv_sec, &tv_usec) == 2 &&
1157 tv_usec < 1000000) {
1158 start_timeofday.tv_sec = tv_sec;
1159 start_timeofday.tv_usec = tv_usec;
1160 valid_until_t = 0;
1161 }
1162 line++;
1163 continue;
1164 } else if (s[0] == '\n') {
1165 line++;
1166 continue;
1167 }
1168 tv_sec = tv_nsec = event = 0;
1169 while (isdigit(*p))
1170 tv_sec = tv_sec * 10 + *p++ - '0';
1171 if (*p == '.')
1172 p++;
1173 while (isdigit(*p))
1174 tv_nsec = tv_nsec * 10 + *p++ - '0';
1175 event = read_val(&p);
1176
1177 bool dropped_events = event & MONITOR_FL_DROPPED_EVENTS;
1178 event &= ~MONITOR_FL_DROPPED_EVENTS;
1179
1180 __u16 pa = 0;
1181 __u16 la_mask = 0;
1182
1183 if (event == MONITOR_STATE_CHANGE) {
1184 pa = read_val(&p);
1185 la_mask = read_val(&p);
1186 }
1187 if (*p != '\n') {
1188 fprintf(stderr, "malformed data at line %d\n", line);
1189 break;
1190 }
1191 if (event != MONITOR_STATE_CHANGE && event > 5) {
1192 fprintf(stderr, "unknown event at line %d\n", line);
1193 break;
1194 }
1195 ev.ts = tv_sec * 1000000000ULL + tv_nsec;
1196 ev.flags = 0;
1197 if (dropped_events)
1198 ev.flags = CEC_EVENT_FL_DROPPED_EVENTS;
1199 if (event == MONITOR_STATE_CHANGE) {
1200 ev.event = CEC_EVENT_STATE_CHANGE;
1201 ev.state_change.phys_addr = pa;
1202 ev.state_change.log_addr_mask = la_mask;
1203 } else {
1204 ev.event = event + CEC_EVENT_PIN_CEC_LOW;
1205 }
1206 log_event(ev, true, true);
1207 line++;
1208 }
1209
1210 if (eob_ts) {
1211 ev.event = CEC_EVENT_PIN_CEC_HIGH;
1212 ev.ts = eob_ts;
1213 log_event(ev, true, true);
1214 }
1215
1216 if (fanalyze != stdin)
1217 fclose(fanalyze);
1218 return;
1219
1220 err:
1221 fprintf(stderr, "Not a pin store file: malformed data at line %d\n", line);
1222 std::exit(EXIT_FAILURE);
1223 }
1224
1225 static bool wait_for_pwr_state(const struct node &node, unsigned from,
1226 unsigned &hpd_is_low_cnt, bool on)
1227 {
1228 struct cec_msg msg;
1229 __u8 pwr;
1230 int ret;
1231
1232 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1233 cec_msg_give_device_power_status(&msg, true);
1234 ret = doioctl(&node, CEC_TRANSMIT, &msg);
1235 if (ret == ENONET) {
1236 printf("X");
1237 fflush(stdout);
1238 hpd_is_low_cnt++;
1239 return hpd_is_low_cnt <= 2 ? false : !on;
1240 }
1241 hpd_is_low_cnt = 0;
1242 if (ret) {
1243 fprintf(stderr, "Give Device Power Status Transmit failed: %s\n",
1244 strerror(ret));
1245 std::exit(EXIT_FAILURE);
1246 }
1247 if ((msg.rx_status & CEC_RX_STATUS_OK) &&
1248 (msg.rx_status & CEC_RX_STATUS_FEATURE_ABORT)) {
1249 printf("A");
1250 fflush(stdout);
1251 return false;
1252 }
1253 if (!(msg.rx_status & CEC_RX_STATUS_OK)) {
1254 if (msg.tx_status & CEC_TX_STATUS_OK)
1255 printf("T");
1256 else
1257 printf("N");
1258 fflush(stdout);
1259 return false;
1260 }
1261
1262 cec_ops_report_power_status(&msg, &pwr);
1263 switch (pwr) {
1264 case CEC_OP_POWER_STATUS_ON:
1265 printf("+");
1266 break;
1267 case CEC_OP_POWER_STATUS_STANDBY:
1268 printf("-");
1269 break;
1270 case CEC_OP_POWER_STATUS_TO_ON:
1271 printf("%c", on ? '/' : '|');
1272 break;
1273 case CEC_OP_POWER_STATUS_TO_STANDBY:
1274 printf("%c", on ? '|' : '\\');
1275 break;
1276 default:
1277 printf(" %d ", pwr);
1278 break;
1279 }
1280 fflush(stdout);
1281 return pwr == (on ? CEC_OP_POWER_STATUS_ON : CEC_OP_POWER_STATUS_STANDBY);
1282 }
1283
1284 static bool wait_for_power_on(const struct node &node, unsigned from)
1285 {
1286 unsigned hpd_is_low_cnt = 0;
1287 return wait_for_pwr_state(node, from, hpd_is_low_cnt, true);
1288 }
1289
1290 static bool wait_for_power_off(const struct node &node, unsigned from, unsigned &hpd_is_low_cnt)
1291 {
1292 return wait_for_pwr_state(node, from, hpd_is_low_cnt, false);
1293 }
1294
1295 static int transmit_msg_retry(const struct node &node, struct cec_msg &msg)
1296 {
1297 bool from_unreg = cec_msg_initiator(&msg) == CEC_LOG_ADDR_UNREGISTERED;
1298 unsigned cnt = 0;
1299 bool repeat;
1300 int ret;
1301
1302 // Can happen if wakeup_la == 15 and CEC just started configuring
1303 do {
1304 ret = doioctl(&node, CEC_TRANSMIT, &msg);
1305 repeat = ret == ENONET || (ret == EINVAL && from_unreg);
1306 if (repeat)
1307 usleep(100000);
1308 } while (repeat && cnt++ < 10);
1309 return ret;
1310 }
1311
1312 static void test_reliability(const struct node &node, unsigned int to, unsigned int secs)
1313 {
1314 struct cec_log_addrs laddrs = { };
1315 struct cec_msg msg;
1316 unsigned from, iter = 0;
1317 __u8 prim_dev, cur_prim_dev;
1318 __u16 pa, cur_pa;
1319
1320 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1321 if (laddrs.log_addr[0] == CEC_LOG_ADDR_INVALID) {
1322 printf("FAIL: invalid logical address\n");
1323 std::exit(EXIT_FAILURE);
1324 }
1325 from = laddrs.log_addr[0];
1326 cec_msg_init(&msg, from, to);
1327 cec_msg_give_physical_addr(&msg, true);
1328 doioctl(&node, CEC_TRANSMIT, &msg);
1329 if (!cec_msg_status_is_ok(&msg)) {
1330 printf("Iteration 0: FAIL: %s\n", cec_status2s(msg).c_str());
1331 std::exit(EXIT_FAILURE);
1332 }
1333 pa = (msg.msg[2] << 8) | msg.msg[3];
1334 prim_dev = msg.msg[4];
1335
1336 printf("Iteration 0: Physical Address: %x.%x.%x.%x Primary Device Type: %s\n",
1337 cec_phys_addr_exp(pa), cec_prim_type2s(prim_dev));
1338
1339 time_t start = time(NULL);
1340
1341 while (1) {
1342 iter++;
1343 cec_msg_init(&msg, from, to);
1344 cec_msg_give_physical_addr(&msg, true);
1345 doioctl(&node, CEC_TRANSMIT, &msg);
1346 if (!cec_msg_status_is_ok(&msg)) {
1347 printf("Iteration %u: FAIL: %s\n", iter, cec_status2s(msg).c_str());
1348 std::exit(EXIT_FAILURE);
1349 }
1350 cur_pa = (msg.msg[2] << 8) | msg.msg[3];
1351 cur_prim_dev = msg.msg[4];
1352 bool pass = pa == cur_pa && prim_dev == cur_prim_dev;
1353
1354 printf("Iteration %u: %s: Physical Address: %x.%x.%x.%x Primary Device Type: %s\n",
1355 iter, pass ? "PASS" : "FAIL",
1356 cec_phys_addr_exp(cur_pa), cec_prim_type2s(cur_prim_dev));
1357 fflush(stdout);
1358 if (!pass)
1359 std::exit(EXIT_FAILURE);
1360 time_t cur = time(NULL);
1361 if (secs && cur - start > (time_t)secs)
1362 break;
1363 }
1364 printf("%u iterations over %u seconds: PASS\n", iter, secs);
1365 }
1366
1367 static void show_legend()
1368 {
1369 printf("Legend:\n\n"
1370 "X No LA claimed (HPD is likely pulled low)\n"
1371 "N Give Device Power Status was Nacked\n"
1372 "T Time out waiting for Report Power Status reply\n"
1373 "A Feature Abort of Give Device Power Status\n"
1374 "C Active Source was Nacked\n"
1375 "S Standby was Nacked\n"
1376 "I Image View On was Nacked\n"
1377 "+ Reported On\n"
1378 "- Reported In Standby\n"
1379 "/ Reported Transitioning to On\n"
1380 "\\ Reported Transitioning to Standby\n"
1381 "| Reported Transitioning to On when 'to Standby' was expected or vice versa\n\n");
1382 }
1383
1384 static int init_standby_wakeup_cycle_test(const struct node &node,
1385 unsigned repeats, unsigned max_tries)
1386 {
1387 struct cec_msg msg;
1388 unsigned from;
1389 unsigned tries;
1390 __u16 pa;
1391 int ret;
1392 struct cec_log_addrs laddrs = { };
1393
1394 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1395 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID) {
1396 from = laddrs.log_addr[0];
1397 } else {
1398 switch (laddrs.log_addr_type[0]) {
1399 case CEC_LOG_ADDR_TYPE_TV:
1400 fprintf(stderr, "A TV can't run the standby-wakeup cycle test.\n");
1401 std::exit(EXIT_FAILURE);
1402 case CEC_LOG_ADDR_TYPE_RECORD:
1403 from = CEC_LOG_ADDR_RECORD_1;
1404 break;
1405 case CEC_LOG_ADDR_TYPE_TUNER:
1406 from = CEC_LOG_ADDR_TUNER_1;
1407 break;
1408 case CEC_LOG_ADDR_TYPE_PLAYBACK:
1409 from = CEC_LOG_ADDR_PLAYBACK_1;
1410 break;
1411 case CEC_LOG_ADDR_TYPE_AUDIOSYSTEM:
1412 from = CEC_LOG_ADDR_AUDIOSYSTEM;
1413 break;
1414 case CEC_LOG_ADDR_TYPE_SPECIFIC:
1415 from = CEC_LOG_ADDR_SPECIFIC;
1416 break;
1417 case CEC_LOG_ADDR_TYPE_UNREGISTERED:
1418 default:
1419 from = CEC_LOG_ADDR_UNREGISTERED;
1420 break;
1421 }
1422 }
1423
1424 if (laddrs.log_addr[0] == CEC_LOG_ADDR_INVALID) {
1425 printf("No Logical Addresses claimed, assume TV is already in Standby\n\n");
1426 } else {
1427 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1428 for (unsigned repeat = 0; repeat <= repeats; repeat++) {
1429 /*
1430 * Some displays only accept Standby from the Active Source.
1431 * So make us the Active Source before sending Standby.
1432 */
1433 printf("%s: ", ts2s(current_ts()).c_str());
1434 printf("Transmit Active Source to TV: ");
1435 fflush(stdout);
1436 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1437 cec_msg_active_source(&msg, pa);
1438 ret = transmit_msg_retry(node, msg);
1439 if (ret) {
1440 printf("FAIL: %s\n", strerror(ret));
1441 std::exit(EXIT_FAILURE);
1442 }
1443 printf("OK\n");
1444 printf("%s: ", ts2s(current_ts()).c_str());
1445 printf("Transmit Standby to TV: ");
1446 fflush(stdout);
1447 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1448 cec_msg_standby(&msg);
1449
1450 tries = 0;
1451 unsigned hpd_is_low_cnt = 0;
1452 for (;;) {
1453 ret = transmit_msg_retry(node, msg);
1454 // The first standby transmit must always succeed,
1455 // later standbys may fail with ENONET
1456 if (ret && (ret != ENONET || !tries)) {
1457 printf("FAIL: %s\n", strerror(ret));
1458 std::exit(EXIT_FAILURE);
1459 }
1460
1461 if (wait_for_power_off(node, from, hpd_is_low_cnt))
1462 break;
1463 if (++tries > max_tries) {
1464 if (repeat == repeats) {
1465 printf(" FAIL: never went into standby\n");
1466 std::exit(EXIT_FAILURE);
1467 }
1468 break;
1469 }
1470 sleep(1);
1471 }
1472 if (tries <= max_tries)
1473 break;
1474
1475 printf(" WARN: never went into standby during attempt %u\n", repeat + 1);
1476 }
1477 printf(" OK\n");
1478 printf("%s: ", ts2s(current_ts()).c_str());
1479 printf("TV is in Standby\n");
1480 sleep(5);
1481 }
1482 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1483 printf("%s: ", ts2s(current_ts()).c_str());
1484 printf("Physical Address: %x.%x.%x.%x\n\n",
1485 cec_phys_addr_exp(pa));
1486
1487 if (pa != CEC_PHYS_ADDR_INVALID)
1488 return from;
1489
1490 sleep(2);
1491
1492 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1493 if (pa != CEC_PHYS_ADDR_INVALID) {
1494 printf("FAIL: Five seconds after being put in the Standby state the HPD was low.\n");
1495 printf(" Two seconds later the HPD was high again. HPD toggles while in Standby\n");
1496 printf(" are not allowed.\n");
1497 std::exit(EXIT_FAILURE);
1498 }
1499
1500 struct cec_caps caps = { };
1501 doioctl(&node, CEC_ADAP_G_CAPS, &caps);
1502 unsigned major = caps.version >> 16;
1503 unsigned minor = (caps.version >> 8) & 0xff;
1504 if (!strcmp(caps.driver, "pulse8-cec") &&
1505 !((major == 4 && minor == 19) || major > 5 ||
1506 (major == 5 && minor >= 4))) {
1507 // The cec framework had a bug that prevented it from reliably
1508 // working with displays that pull down the HPD. This was fixed
1509 // in commit ac479b51f3f4 for kernel 5.5 and backported to kernels
1510 // 4.19.94 and 5.4.9. We only fail when the pulse8-cec driver is used,
1511 // for other CEC devices you hopefully know what you are doing...
1512 printf("FAIL: This display appears to pull down the HPD when in Standby. For such\n");
1513 printf(" displays kernel 4.19 or kernel 5.4 or higher is required.\n");
1514 std::exit(EXIT_FAILURE);
1515 }
1516
1517 return from;
1518 }
1519
1520 static void test_standby_wakeup_cycle(const struct node &node, unsigned int max_tries,
1521 unsigned int retry_sleep, bool hpd_may_be_low)
1522 {
1523 struct cec_log_addrs laddrs = { };
1524 struct cec_msg msg;
1525 unsigned failures = 0;
1526 unsigned from;
1527 unsigned tries;
1528 unsigned secs;
1529 __u16 pa, prev_pa;
1530 __u16 display_pa = CEC_PHYS_ADDR_INVALID;
1531 __u8 wakeup_la;
1532 int ret;
1533
1534 show_legend();
1535 from = init_standby_wakeup_cycle_test(node, 2, max_tries);
1536
1537 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1538 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
1539 wakeup_la = from = laddrs.log_addr[0];
1540 else
1541 wakeup_la = CEC_LOG_ADDR_UNREGISTERED;
1542
1543 bool hpd_is_low = (wakeup_la == CEC_LOG_ADDR_UNREGISTERED) || hpd_may_be_low;
1544
1545 printf("The Hotplug Detect pin %s when in Standby\n\n",
1546 hpd_may_be_low ? "may be pulled low" :
1547 (hpd_is_low ? "is pulled low" : "remains high"));
1548
1549 for (unsigned iter = 0; iter <= 2 * 12; iter++) {
1550 unsigned i = iter / 2;
1551
1552 /*
1553 * For sleep values 0-5 run the test twice,
1554 * after that run it only once.
1555 */
1556 if (i > 5 && (iter & 1))
1557 continue;
1558
1559 printf("%s: ", ts2s(current_ts()).c_str());
1560 printf("Wake up TV using Image View On from LA %s: ", cec_la2s(wakeup_la));
1561 fflush(stdout);
1562 cec_msg_init(&msg, wakeup_la, CEC_LOG_ADDR_TV);
1563 cec_msg_image_view_on(&msg);
1564 ret = transmit_msg_retry(node, msg);
1565 if (ret) {
1566 printf("FAIL: %s\n", strerror(ret));
1567 std::exit(EXIT_FAILURE);
1568 }
1569 tries = 0;
1570 for (;;) {
1571 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1572 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
1573 wakeup_la = from = laddrs.log_addr[0];
1574 if (wait_for_power_on(node, from))
1575 break;
1576 if (++tries > max_tries)
1577 break;
1578 sleep(1);
1579 }
1580
1581 if (tries > max_tries) {
1582 wakeup_la = from;
1583 printf("\nFAIL: never woke up, sleep %u secs, then retry\n",
1584 retry_sleep);
1585 failures++;
1586 fflush(stdout);
1587 sleep(retry_sleep);
1588 printf("%s: ", ts2s(current_ts()).c_str());
1589 printf("Wake up TV using Image View On from LA %s: ", cec_la2s(wakeup_la));
1590 fflush(stdout);
1591 cec_msg_init(&msg, wakeup_la, CEC_LOG_ADDR_TV);
1592 cec_msg_image_view_on(&msg);
1593 ret = doioctl(&node, CEC_TRANSMIT, &msg);
1594 if (ret == ENONET) {
1595 printf("(ENONET) ");
1596 } else if (ret == EINVAL && wakeup_la == CEC_LOG_ADDR_UNREGISTERED) {
1597 printf("(EINVAL) ");
1598 } else if (ret) {
1599 printf("FAIL: %s\n", strerror(ret));
1600 std::exit(EXIT_FAILURE);
1601 }
1602 tries = 0;
1603 for (;;) {
1604 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1605 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
1606 wakeup_la = from = laddrs.log_addr[0];
1607 if (wait_for_power_on(node, from))
1608 break;
1609 if (++tries > max_tries) {
1610 printf("\nFAIL: never woke up\n");
1611 failures++;
1612 break;
1613 }
1614 sleep(1);
1615 }
1616 }
1617 printf(" %d second%s\n", tries, tries == 1 ? "" : "s");
1618
1619 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1620 if (laddrs.log_addr[0] == CEC_LOG_ADDR_INVALID) {
1621 printf("FAIL: invalid logical address\n");
1622 std::exit(EXIT_FAILURE);
1623 }
1624 from = laddrs.log_addr[0];
1625 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1626 printf("%s: ", ts2s(current_ts()).c_str());
1627 printf("Physical Address: %x.%x.%x.%x LA: %s\n",
1628 cec_phys_addr_exp(pa), cec_la2s(from));
1629 if (pa == CEC_PHYS_ADDR_INVALID || !pa) {
1630 printf("FAIL: invalid physical address\n");
1631 std::exit(EXIT_FAILURE);
1632 }
1633 prev_pa = pa;
1634 if (display_pa == CEC_PHYS_ADDR_INVALID)
1635 display_pa = pa;
1636 if (pa != display_pa) {
1637 printf("FAIL: physical address changed from %x.%x.%x.%x to %x.%x.%x.%x\n",
1638 cec_phys_addr_exp(display_pa), cec_phys_addr_exp(pa));
1639 std::exit(EXIT_FAILURE);
1640 }
1641 secs = i <= 10 ? i : 10 + 10 * (i - 10);
1642 printf("%s: ", ts2s(current_ts()).c_str());
1643 printf("Sleep %u second%s\n", secs, secs == 1 ? "" : "s");
1644 sleep(secs);
1645 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1646 if (pa != prev_pa) {
1647 printf("\tFAIL: PA is now %x.%x.%x.%x\n\n",
1648 cec_phys_addr_exp(pa));
1649 std::exit(EXIT_FAILURE);
1650 }
1651
1652 printf("\n%s: ", ts2s(current_ts()).c_str());
1653 printf("Put TV in standby from LA %s: ", cec_la2s(from));
1654 fflush(stdout);
1655 /*
1656 * Some displays only accept Standby from the Active Source.
1657 * So make us the Active Source before sending Standby.
1658 */
1659 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1660 cec_msg_active_source(&msg, pa);
1661 ret = transmit_msg_retry(node, msg);
1662 if (ret) {
1663 printf("FAIL: Active Source Transmit failed: %s\n", strerror(ret));
1664 std::exit(EXIT_FAILURE);
1665 }
1666 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1667 cec_msg_standby(&msg);
1668 ret = transmit_msg_retry(node, msg);
1669 if (ret) {
1670 printf("FAIL: %s\n", strerror(ret));
1671 std::exit(EXIT_FAILURE);
1672 }
1673
1674 tries = 0;
1675 bool first_standby = true;
1676 unsigned hpd_is_low_cnt = 0;
1677 for (;;) {
1678 if (!hpd_is_low)
1679 hpd_is_low_cnt = 0;
1680 if (wait_for_power_off(node, from, hpd_is_low_cnt))
1681 break;
1682 if (++tries > max_tries) {
1683 if (first_standby) {
1684 printf("\nFAIL: never went into standby, sleep %u secs, then retry\n",
1685 retry_sleep);
1686 failures++;
1687 fflush(stdout);
1688 sleep(retry_sleep);
1689 printf("%s: ", ts2s(current_ts()).c_str());
1690 printf("Put TV in standby from LA %s: ", cec_la2s(from));
1691 fflush(stdout);
1692 first_standby = false;
1693 tries = 0;
1694 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1695 cec_msg_standby(&msg);
1696 ret = doioctl(&node, CEC_TRANSMIT, &msg);
1697 if (!ret)
1698 continue;
1699 printf("FAIL: %s\n", strerror(ret));
1700 std::exit(EXIT_FAILURE);
1701 }
1702 printf("\nFAIL: never went into standby\n");
1703 failures++;
1704 break;
1705 }
1706 sleep(1);
1707 }
1708 printf(" %d second%s\n", tries, tries == 1 ? "" : "s");
1709 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1710 printf("%s: ", ts2s(current_ts()).c_str());
1711 printf("Physical Address: %x.%x.%x.%x\n",
1712 cec_phys_addr_exp(pa));
1713 prev_pa = pa;
1714 printf("%s: ", ts2s(current_ts()).c_str());
1715 printf("Sleep %d second%s\n", secs, secs == 1 ? "" : "s");
1716 sleep(secs);
1717 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1718 if (pa != prev_pa) {
1719 printf("%s: ", ts2s(current_ts()).c_str());
1720 printf("Physical Address: %x.%x.%x.%x\n",
1721 cec_phys_addr_exp(pa));
1722 }
1723 if (pa != CEC_PHYS_ADDR_INVALID && pa != display_pa) {
1724 printf("FAIL: physical address changed from %x.%x.%x.%x to %x.%x.%x.%x\n",
1725 cec_phys_addr_exp(display_pa), cec_phys_addr_exp(pa));
1726 std::exit(EXIT_FAILURE);
1727 }
1728 printf("\n");
1729 }
1730 if (failures)
1731 printf("Test had %u failure%s\n", failures, failures == 1 ? "" : "s");
1732 else
1733 printf("PASS\n");
1734 }
1735
1736 static void stress_test_standby_wakeup_cycle(const struct node &node, unsigned cnt,
1737 double min_sleep, double max_sleep, unsigned max_tries,
1738 bool has_seed, unsigned seed, unsigned repeats,
1739 double sleep_before_on, double sleep_before_off,
1740 bool hpd_may_be_low)
1741 {
1742 struct cec_log_addrs laddrs = { };
1743 struct cec_msg msg;
1744 unsigned tries = 0;
1745 unsigned iter = 0;
1746 unsigned min_usleep = 1000000.0 * (max_sleep ? min_sleep : 0);
1747 unsigned mod_usleep = 0;
1748 unsigned wakeup_la;
1749 __u16 pa, prev_pa;
1750 __u16 display_pa = CEC_PHYS_ADDR_INVALID;
1751 int ret;
1752
1753 if (max_sleep)
1754 mod_usleep = 1000000.0 * (max_sleep - min_sleep) + 1;
1755
1756 if (!has_seed)
1757 seed = time(nullptr);
1758
1759 if (mod_usleep)
1760 printf("Randomizer seed: %u\n\n", seed);
1761
1762 show_legend();
1763
1764 unsigned from = init_standby_wakeup_cycle_test(node, repeats, max_tries);
1765
1766 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1767 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
1768 wakeup_la = from = laddrs.log_addr[0];
1769 else
1770 wakeup_la = CEC_LOG_ADDR_UNREGISTERED;
1771
1772 bool hpd_is_low = (wakeup_la == CEC_LOG_ADDR_UNREGISTERED) || hpd_may_be_low;
1773
1774 printf("The Hotplug Detect pin %s when in Standby\n\n",
1775 hpd_may_be_low ? "may be pulled low" :
1776 (hpd_is_low ? "is pulled low" : "remains high"));
1777
1778 srandom(seed);
1779
1780 for (;;) {
1781 unsigned usecs1 = mod_usleep ? random() % mod_usleep : static_cast<unsigned>(sleep_before_on * 1000000);
1782 unsigned usecs2 = mod_usleep ? random() % mod_usleep : static_cast<unsigned>(sleep_before_off * 1000000);
1783
1784 usecs1 += min_usleep;
1785 usecs2 += min_usleep;
1786
1787 iter++;
1788
1789 if (usecs1)
1790 printf("%s: Sleep %.2fs before Image View On\n", ts2s(current_ts()).c_str(),
1791 usecs1 / 1000000.0);
1792 fflush(stdout);
1793 usleep(usecs1);
1794 for (unsigned repeat = 0; repeat <= repeats; repeat++) {
1795 printf("%s: ", ts2s(current_ts()).c_str());
1796 printf("Transmit Image View On from LA %s (iteration %u): ", cec_la2s(wakeup_la), iter);
1797
1798 cec_msg_init(&msg, wakeup_la, CEC_LOG_ADDR_TV);
1799 tries = 0;
1800 bool image_view_on_ok = false;
1801
1802 for (;;) {
1803 if (!image_view_on_ok) {
1804 cec_msg_image_view_on(&msg);
1805 ret = transmit_msg_retry(node, msg);
1806 if (ret == EINVAL && wakeup_la == CEC_LOG_ADDR_UNREGISTERED) {
1807 // Can happen if wakeup_la == 15 and CEC just started configuring
1808 printf("(EINVAL) ");
1809 } else if (ret) {
1810 printf("FAIL: %s\n", strerror(ret));
1811 std::exit(EXIT_FAILURE);
1812 }
1813 // Depending on the CEC hardware, a successfully
1814 // transmitted message may in some cases be marked
1815 // as aborted if the HPD goes low before the transmit
1816 // was marked as 'Done'. For now assume that an
1817 // aborted message was really Nacked so it is retried.
1818 if (msg.tx_status & CEC_TX_STATUS_ABORTED)
1819 msg.tx_status = CEC_TX_STATUS_NACK;
1820 if (!(msg.tx_status & (CEC_TX_STATUS_OK | CEC_TX_STATUS_NACK))) {
1821 printf("FAIL: Image View On failed: %s\n",
1822 cec_status2s(msg).c_str());
1823 std::exit(EXIT_FAILURE);
1824 }
1825 if (msg.tx_status & CEC_TX_STATUS_OK) {
1826 image_view_on_ok = true;
1827 } else {
1828 printf("I");
1829 fflush(stdout);
1830 sleep(1);
1831 continue;
1832 }
1833 }
1834 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1835 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
1836 wakeup_la = from = laddrs.log_addr[0];
1837 if (wait_for_power_on(node, from))
1838 break;
1839 if (++tries > max_tries) {
1840 if (repeat == repeats) {
1841 printf("\nFAIL: never woke up\n");
1842 std::exit(EXIT_FAILURE);
1843 }
1844 break;
1845 }
1846 sleep(1);
1847 }
1848 if (tries <= max_tries)
1849 break;
1850 printf("\nWARN: never woke up during attempt %u\n", repeat + 1);
1851 }
1852 printf(" %d second%s\n", tries, tries == 1 ? "" : "s");
1853 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
1854 if (laddrs.log_addr[0] == CEC_LOG_ADDR_INVALID) {
1855 printf("FAIL: invalid logical address\n");
1856 std::exit(EXIT_FAILURE);
1857 }
1858 from = laddrs.log_addr[0];
1859 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1860 prev_pa = pa;
1861 printf("%s: ", ts2s(current_ts()).c_str());
1862 printf("Physical Address: %x.%x.%x.%x LA: %s\n",
1863 cec_phys_addr_exp(pa), cec_la2s(from));
1864 if (pa == CEC_PHYS_ADDR_INVALID || !pa) {
1865 printf("FAIL: invalid physical address\n");
1866 std::exit(EXIT_FAILURE);
1867 }
1868 if (display_pa == CEC_PHYS_ADDR_INVALID)
1869 display_pa = pa;
1870 if (pa != display_pa) {
1871 printf("FAIL: physical address changed from %x.%x.%x.%x to %x.%x.%x.%x\n",
1872 cec_phys_addr_exp(display_pa), cec_phys_addr_exp(pa));
1873 std::exit(EXIT_FAILURE);
1874 }
1875
1876 if (cnt && iter == cnt)
1877 break;
1878
1879 if (usecs2)
1880 printf("%s: Sleep %.2fs before Standby\n", ts2s(current_ts()).c_str(),
1881 usecs2 / 1000000.0);
1882 fflush(stdout);
1883 usleep(usecs2);
1884 for (unsigned repeat = 0; repeat <= repeats; repeat++) {
1885 printf("%s: ", ts2s(current_ts()).c_str());
1886 printf("Transmit Standby (iteration %u): ", iter);
1887 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
1888 if (pa != prev_pa) {
1889 printf("\tFAIL: PA is now %x.%x.%x.%x\n\n",
1890 cec_phys_addr_exp(pa));
1891 std::exit(EXIT_FAILURE);
1892 }
1893 if (pa != CEC_PHYS_ADDR_INVALID && pa != display_pa) {
1894 printf("FAIL: physical address changed from %x.%x.%x.%x to %x.%x.%x.%x\n",
1895 cec_phys_addr_exp(display_pa), cec_phys_addr_exp(pa));
1896 std::exit(EXIT_FAILURE);
1897 }
1898
1899 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1900
1901 tries = 0;
1902 unsigned hpd_is_low_cnt = 0;
1903 bool active_source_ok = false;
1904 bool standby_ok = false;
1905 for (;;) {
1906 if (!active_source_ok) {
1907 /*
1908 * Some displays only accept Standby from the Active Source.
1909 * So make us the Active Source before sending Standby.
1910 */
1911 cec_msg_active_source(&msg, pa);
1912 ret = transmit_msg_retry(node, msg);
1913 if (ret) {
1914 printf("FAIL: Active Source Transmit failed: %s\n",
1915 strerror(ret));
1916 std::exit(EXIT_FAILURE);
1917 }
1918 if (!(msg.tx_status & (CEC_TX_STATUS_OK | CEC_TX_STATUS_NACK))) {
1919 printf("FAIL: Active Source Transmit failed: %s\n",
1920 cec_status2s(msg).c_str());
1921 std::exit(EXIT_FAILURE);
1922 }
1923 if (msg.tx_status & CEC_TX_STATUS_OK) {
1924 active_source_ok = true;
1925 } else {
1926 printf("C");
1927 fflush(stdout);
1928 sleep(1);
1929 continue;
1930 }
1931 }
1932 if (!standby_ok) {
1933 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
1934 cec_msg_standby(&msg);
1935 ret = transmit_msg_retry(node, msg);
1936 if (ret) {
1937 printf("FAIL: %s\n", strerror(ret));
1938 std::exit(EXIT_FAILURE);
1939 }
1940 if (!(msg.tx_status & (CEC_TX_STATUS_OK | CEC_TX_STATUS_NACK))) {
1941 printf("FAIL: Standby Transmit failed: %s\n",
1942 cec_status2s(msg).c_str());
1943 std::exit(EXIT_FAILURE);
1944 }
1945 if (msg.tx_status & CEC_TX_STATUS_OK) {
1946 standby_ok = true;
1947 } else {
1948 printf("S");
1949 fflush(stdout);
1950 sleep(1);
1951 continue;
1952 }
1953 }
1954 if (!hpd_is_low)
1955 hpd_is_low_cnt = 0;
1956 if (wait_for_power_off(node, from, hpd_is_low_cnt))
1957 break;
1958 if (++tries > max_tries) {
1959 if (repeat == repeats) {
1960 printf("\nFAIL: never went into standby\n");
1961 std::exit(EXIT_FAILURE);
1962 }
1963 break;
1964 }
1965 sleep(1);
1966 }
1967 if (tries <= max_tries)
1968 break;
1969 printf("\nWARN: never went into standby during attempt %u\n", repeat + 1);
1970 }
1971 printf(" %d second%s\n", tries, tries == 1 ? "" : "s");
1972 }
1973 printf("%u iterations: PASS\n", cnt);
1974 }
1975
1976 static void stress_test_random_standby_wakeup_cycle(const struct node &node, unsigned cnt,
1977 double min_sleep, double max_sleep,
1978 bool has_seed, unsigned seed,
1979 bool hpd_may_be_low)
1980 {
1981 struct cec_log_addrs laddrs = { };
1982 struct cec_msg msg;
1983 unsigned iter = 0;
1984 unsigned min_usleep = 1000000.0 * (max_sleep ? min_sleep : 0);
1985 unsigned mod_usleep = 0;
1986 unsigned from, wakeup_la;
1987 __u16 pa;
1988 int ret;
1989
1990 if (max_sleep)
1991 mod_usleep = 1000000.0 * (max_sleep - min_sleep) + 1;
1992
1993 if (!has_seed)
1994 seed = time(nullptr);
1995
1996 if (mod_usleep)
1997 printf("Randomizer seed: %u\n\n", seed);
1998
1999 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
2000 if (pa == CEC_PHYS_ADDR_INVALID || !pa) {
2001 cec_msg_init(&msg, 0xf, CEC_LOG_ADDR_TV);
2002 cec_msg_image_view_on(&msg);
2003 if (transmit_msg_retry(node, msg)) {
2004 printf("FAIL: Image View On failed\n");
2005 std::exit(EXIT_FAILURE);
2006 }
2007 sleep(15);
2008 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &pa);
2009 if (pa == CEC_PHYS_ADDR_INVALID || !pa) {
2010 printf("FAIL: invalid physical address\n");
2011 std::exit(EXIT_FAILURE);
2012 }
2013 printf("Physical Address: %x.%x.%x.%x\n",
2014 cec_phys_addr_exp(pa));
2015 }
2016
2017 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
2018 if (laddrs.log_addr[0] == CEC_LOG_ADDR_INVALID) {
2019 printf("FAIL: invalid logical address\n");
2020 std::exit(EXIT_FAILURE);
2021 }
2022 from = laddrs.log_addr[0];
2023
2024 init_standby_wakeup_cycle_test(node, 2, 30);
2025
2026 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
2027 if (laddrs.log_addr[0] != CEC_LOG_ADDR_INVALID)
2028 wakeup_la = laddrs.log_addr[0];
2029 else
2030 wakeup_la = CEC_LOG_ADDR_UNREGISTERED;
2031
2032 bool hpd_is_low = (wakeup_la == CEC_LOG_ADDR_UNREGISTERED) || hpd_may_be_low;
2033
2034 printf("The Hotplug Detect pin %s when in Standby\n\n",
2035 hpd_may_be_low ? "may be pulled low" :
2036 (hpd_is_low ? "is pulled low" : "remains high"));
2037
2038 srandom(seed);
2039
2040 for (;;) {
2041 unsigned usecs1 = mod_usleep ? random() % mod_usleep : 0;
2042 unsigned usecs2 = mod_usleep ? random() % mod_usleep : 0;
2043
2044 usecs1 += min_usleep;
2045 usecs2 += min_usleep;
2046
2047 iter++;
2048
2049 bool verify_result = iter % 10 == 0;
2050
2051 if (verify_result)
2052 usecs1 = 30 * 1000000;
2053
2054 if (usecs1)
2055 printf("%s: Sleep %.2fs before Image View On\n", ts2s(current_ts()).c_str(),
2056 usecs1 / 1000000.0);
2057 fflush(stdout);
2058 usleep(usecs1);
2059 printf("%s: ", ts2s(current_ts()).c_str());
2060 printf("Transmit Image View On from LA %s (iteration %u): ", cec_la2s(wakeup_la), iter);
2061
2062 cec_msg_init(&msg, wakeup_la, CEC_LOG_ADDR_TV);
2063 cec_msg_image_view_on(&msg);
2064 for (int i = 0; i < 10; i++) {
2065 ret = transmit_msg_retry(node, msg);
2066 if (!ret)
2067 break;
2068 usleep(200000);
2069 }
2070 if (ret != ENONET)
2071 printf("%s\n", strerror(ret));
2072 else
2073 printf("OK\n");
2074
2075 if (verify_result) {
2076 printf("%s: Sleep %.2fs before verifying power state\n", ts2s(current_ts()).c_str(),
2077 usecs1 / 1000000.0);
2078 fflush(stdout);
2079 usleep(usecs1);
2080 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
2081 cec_msg_give_device_power_status(&msg, true);
2082 printf("%s: ", ts2s(current_ts()).c_str());
2083 printf("Transmit Give Device Power Status from LA %s: ", cec_la2s(from));
2084 ret = transmit_msg_retry(node, msg);
2085 if (!ret) {
2086 if (cec_msg_status_is_ok(&msg)) {
2087 __u8 pwr;
2088
2089 cec_ops_report_power_status(&msg, &pwr);
2090 printf("%s\n", power_status2s(pwr));
2091 if (pwr == CEC_OP_POWER_STATUS_ON)
2092 goto done;
2093 } else {
2094 printf("%s\n", cec_status2s(msg).c_str());
2095 }
2096 } else {
2097 printf("%s\n", strerror(ret));
2098 }
2099 printf("%s: ", ts2s(current_ts()).c_str());
2100 printf("Retry transmit Image View On from LA %s: ", cec_la2s(wakeup_la));
2101
2102 cec_msg_init(&msg, wakeup_la, CEC_LOG_ADDR_TV);
2103 cec_msg_image_view_on(&msg);
2104 ret = transmit_msg_retry(node, msg);
2105 if (ret) {
2106 printf("%s\n", strerror(ret));
2107 printf("FAIL: never woke up\n");
2108 std::exit(EXIT_FAILURE);
2109 }
2110 printf("OK\n");
2111 printf("%s: Sleep %.2fs before verifying power state\n", ts2s(current_ts()).c_str(),
2112 usecs1 / 1000000.0);
2113 fflush(stdout);
2114 usleep(usecs1);
2115 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
2116 cec_msg_give_device_power_status(&msg, true);
2117 printf("%s: ", ts2s(current_ts()).c_str());
2118 printf("Retry transmit Give Device Power Status from LA %s: ", cec_la2s(from));
2119 ret = transmit_msg_retry(node, msg);
2120 if (ret) {
2121 printf("%s\n", strerror(ret));
2122 } else if (!cec_msg_status_is_ok(&msg)) {
2123 printf("%s\n", cec_status2s(msg).c_str());
2124 } else {
2125 __u8 pwr;
2126
2127 cec_ops_report_power_status(&msg, &pwr);
2128 printf("%s\n", power_status2s(pwr));
2129 if (pwr == CEC_OP_POWER_STATUS_ON)
2130 goto done;
2131 }
2132 printf("FAIL: never woke up\n");
2133 std::exit(EXIT_FAILURE);
2134 }
2135 done:
2136
2137 if (cnt && iter == cnt)
2138 break;
2139
2140 if (usecs2)
2141 printf("%s: Sleep %.2fs before Standby\n", ts2s(current_ts()).c_str(),
2142 usecs2 / 1000000.0);
2143 fflush(stdout);
2144 usleep(usecs2);
2145 printf("%s: ", ts2s(current_ts()).c_str());
2146 printf("Transmit Standby from LA %s (iteration %u): ", cec_la2s(from), iter);
2147
2148 /*
2149 * Some displays only accept Standby from the Active Source.
2150 * So make us the Active Source before sending Standby.
2151 */
2152 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
2153 cec_msg_active_source(&msg, pa);
2154 transmit_msg_retry(node, msg);
2155 cec_msg_init(&msg, from, CEC_LOG_ADDR_TV);
2156 cec_msg_standby(&msg);
2157 for (int i = 0; i < 10; i++) {
2158 ret = transmit_msg_retry(node, msg);
2159 if (!ret)
2160 break;
2161 usleep(200000);
2162 }
2163 if (ret != ENONET)
2164 printf("%s\n", strerror(ret));
2165 else
2166 printf("OK\n");
2167 }
2168 printf("%u iterations: PASS\n", cnt);
2169 }
2170
2171
2172 static int calc_node_val(const char *s)
2173 {
2174 s = std::strrchr(s, '/') + 1;
2175
2176 if (!memcmp(s, "cec", 3))
2177 return atol(s + 3);
2178 return 0;
2179 }
2180
2181 static bool sort_on_device_name(const std::string &s1, const std::string &s2)
2182 {
2183 int n1 = calc_node_val(s1.c_str());
2184 int n2 = calc_node_val(s2.c_str());
2185
2186 return n1 < n2;
2187 }
2188
2189 static unsigned int cec_get_edid_spa_location(const __u8 *edid,
2190 unsigned int size)
2191 {
2192 unsigned int blocks = size / 128;
2193 unsigned int block;
2194 __u8 d;
2195
2196 /* Sanity check: at least 2 blocks and a multiple of the block size */
2197 if (blocks < 2 || size % 128)
2198 return 0;
2199
2200 /*
2201 * If there are fewer extension blocks than the size, then update
2202 * 'blocks'. It is allowed to have more extension blocks than the size,
2203 * since some hardware can only read e.g. 256 bytes of the EDID, even
2204 * though more blocks are present. The first CEA-861 extension block
2205 * should normally be in block 1 anyway.
2206 */
2207 if (edid[0x7e] + 1U < blocks)
2208 blocks = edid[0x7e] + 1;
2209
2210 for (block = 1; block < blocks; block++) {
2211 unsigned int offset = block * 128;
2212
2213 /* Skip any non-CEA-861 extension blocks */
2214 if (edid[offset] != 0x02 || edid[offset + 1] != 0x03)
2215 continue;
2216
2217 /* search Vendor Specific Data Block (tag 3) */
2218 d = edid[offset + 2] & 0x7f;
2219 /* Check if there are Data Blocks */
2220 if (d <= 4)
2221 continue;
2222 if (d > 4) {
2223 unsigned int i = offset + 4;
2224 unsigned int end = offset + d;
2225
2226 /* Note: 'end' is always < 'size' */
2227 do {
2228 __u8 tag = edid[i] >> 5;
2229 __u8 len = edid[i] & 0x1f;
2230
2231 if (tag == 3 && len >= 5 && i + len <= end &&
2232 edid[i + 1] == 0x03 &&
2233 edid[i + 2] == 0x0c &&
2234 edid[i + 3] == 0x00)
2235 return i + 4;
2236 i += len + 1;
2237 } while (i < end);
2238 }
2239 }
2240 return 0;
2241 }
2242
2243 static __u16 parse_phys_addr_from_edid(const char *edid_path)
2244 {
2245 FILE *f = fopen(edid_path, "r");
2246 __u16 pa = CEC_PHYS_ADDR_INVALID;
2247 __u8 edid[256];
2248
2249 if (f == nullptr)
2250 return pa;
2251 if (fread(edid, sizeof(edid), 1, f) == 1) {
2252 unsigned int loc = cec_get_edid_spa_location(edid, sizeof(edid));
2253
2254 if (loc)
2255 pa = (edid[loc] << 8) | edid[loc + 1];
2256 }
2257 fclose(f);
2258 return pa;
2259 }
2260
2261 static void *thread_edid_poll(void *arg)
2262 {
2263 auto node = static_cast<struct node *>(arg);
2264 __u16 phys_addr;
2265 bool has_edid;
2266 char dummy;
2267 int fd;
2268
2269 fd = open(edid_path, O_RDONLY);
2270 if (fd < 0)
2271 std::exit(EXIT_FAILURE);
2272
2273 doioctl(node, CEC_ADAP_G_PHYS_ADDR, &phys_addr);
2274 has_edid = phys_addr != CEC_PHYS_ADDR_INVALID;
2275
2276 for (;;) {
2277 bool edid;
2278
2279 /* Poll every 100 ms */
2280 usleep(100000);
2281 lseek(fd, 0, SEEK_SET);
2282 edid = read(fd, &dummy, 1) > 0;
2283 if (has_edid != edid) {
2284 has_edid = edid;
2285 if (!edid)
2286 phys_addr = CEC_PHYS_ADDR_INVALID;
2287 else
2288 phys_addr = parse_phys_addr_from_edid(edid_path);
2289 doioctl(node, CEC_ADAP_S_PHYS_ADDR, &phys_addr);
2290 if (is_paused)
2291 printf("Physical Address: %x.%x.%x.%x\n",
2292 cec_phys_addr_exp(phys_addr));
2293 }
2294 }
2295 return nullptr;
2296 }
2297
2298 using dev_vec = std::vector<std::string>;
2299 using dev_map = std::map<std::string, std::string>;
2300
2301 static void list_devices()
2302 {
2303 DIR *dp;
2304 struct dirent *ep;
2305 dev_vec files;
2306 dev_map links;
2307 dev_map cards;
2308 struct cec_caps caps;
2309
2310 dp = opendir("/dev");
2311 if (dp == nullptr) {
2312 perror("Couldn't open the directory");
2313 return;
2314 }
2315 while ((ep = readdir(dp)))
2316 if (!memcmp(ep->d_name, "cec", 3) && isdigit(ep->d_name[3]))
2317 files.push_back(std::string("/dev/") + ep->d_name);
2318 closedir(dp);
2319
2320 /* Find device nodes which are links to other device nodes */
2321 for (auto iter = files.begin();
2322 iter != files.end(); ) {
2323 char link[64+1];
2324 int link_len;
2325 std::string target;
2326
2327 link_len = readlink(iter->c_str(), link, 64);
2328 if (link_len < 0) { /* Not a link or error */
2329 iter++;
2330 continue;
2331 }
2332 link[link_len] = '\0';
2333
2334 /* Only remove from files list if target itself is in list */
2335 if (link[0] != '/') /* Relative link */
2336 target = std::string("/dev/");
2337 target += link;
2338 if (find(files.begin(), files.end(), target) == files.end()) {
2339 iter++;
2340 continue;
2341 }
2342
2343 /* Move the device node from files to links */
2344 if (links[target].empty())
2345 links[target] = *iter;
2346 else
2347 links[target] += ", " + *iter;
2348 iter = files.erase(iter);
2349 }
2350
2351 std::sort(files.begin(), files.end(), sort_on_device_name);
2352
2353 for (const auto &file : files) {
2354 int fd = open(file.c_str(), O_RDWR);
2355 std::string cec_info;
2356
2357 if (fd < 0)
2358 continue;
2359 int err = ioctl(fd, CEC_ADAP_G_CAPS, &caps);
2360 close(fd);
2361 if (err)
2362 continue;
2363 cec_info = std::string(caps.driver) + " (" + caps.name + ")";
2364 if (cards[cec_info].empty())
2365 cards[cec_info] += cec_info + ":\n";
2366 cards[cec_info] += "\t" + file;
2367 if (!(links[file].empty()))
2368 cards[cec_info] += " <- " + links[file];
2369 cards[cec_info] += "\n";
2370 }
2371 for (const auto &card : cards) {
2372 printf("%s\n", card.second.c_str());
2373 }
2374 }
2375
2376 int main(int argc, char **argv)
2377 {
2378 std::string device;
2379 const char *driver = nullptr;
2380 const char *adapter = nullptr;
2381 const struct cec_msg_args *opt;
2382 msg_vec msgs;
2383 char short_options[26 * 2 * 3 + 1];
2384 __u32 timeout = 1000;
2385 __u32 monitor_time = 0;
2386 __u32 vendor_id = 0x000c03; /* HDMI LLC vendor ID */
2387 unsigned int stress_test_standby_wakeup_cycle_cnt = 0;
2388 double stress_test_standby_wakeup_cycle_min_sleep = 0;
2389 double stress_test_standby_wakeup_cycle_max_sleep = 0;
2390 unsigned int stress_test_standby_wakeup_cycle_polls = 30;
2391 bool stress_test_standby_wakeup_cycle_has_seed = false;
2392 unsigned int stress_test_standby_wakeup_cycle_seed = 0;
2393 unsigned int stress_test_standby_wakeup_cycle_repeats = 0;
2394 double stress_test_standby_wakeup_cycle_sleep_before_on = 0;
2395 double stress_test_standby_wakeup_cycle_sleep_before_off = 0;
2396 bool stress_test_standby_wakeup_cycle_hpd_may_be_low = false;
2397 unsigned int test_reliability_duration = 0;
2398 unsigned int test_standby_wakeup_cycle_polls = 15;
2399 unsigned int test_standby_wakeup_cycle_sleep = 10;
2400 bool test_standby_wakeup_cycle_hpd_may_be_low = false;
2401 unsigned int stress_test_random_standby_wakeup_cnt = 0;
2402 double stress_test_random_standby_wakeup_min_sleep = 0;
2403 double stress_test_random_standby_wakeup_max_sleep = 10;
2404 bool stress_test_random_standby_wakeup_has_seed = false;
2405 unsigned int stress_test_random_standby_wakeup_seed = 0;
2406 bool stress_test_random_standby_wakeup_hpd_may_be_low = false;
2407 bool warn_if_unconfigured = false;
2408 __u16 phys_addr;
2409 __u8 from = 0, to = 0, first_to = 0xff;
2410 __u8 dev_features = 0;
2411 __u8 rc_tv = 0;
2412 __u8 rc_src = 0;
2413 const char *osd_name = "";
2414 const char *store_pin = nullptr;
2415 const char *analyze_pin = nullptr;
2416 bool reply = true;
2417 int idx = 0;
2418 int fd = -1;
2419 int ch;
2420 int i;
2421
2422 memset(phys_addrs, 0xff, sizeof(phys_addrs));
2423
2424 for (i = 0; long_options[i].name; i++) {
2425 if (!isalpha(long_options[i].val))
2426 continue;
2427 short_options[idx++] = long_options[i].val;
2428 if (long_options[i].has_arg == required_argument) {
2429 short_options[idx++] = ':';
2430 } else if (long_options[i].has_arg == optional_argument) {
2431 short_options[idx++] = ':';
2432 short_options[idx++] = ':';
2433 }
2434 }
2435 while (true) {
2436 int option_index = 0;
2437 struct cec_msg msg;
2438
2439 short_options[idx] = 0;
2440 ch = getopt_long(argc, argv, short_options,
2441 long_options, &option_index);
2442 if (ch == -1)
2443 break;
2444
2445 cec_msg_init(&msg, 0, 0);
2446 msg.msg[0] = options[OptTo] ? to : 0xf0;
2447 options[ch] = 1;
2448
2449 if (!option_index) {
2450 for (i = 0; long_options[i].val; i++) {
2451 if (long_options[i].val == ch) {
2452 option_index = i;
2453 break;
2454 }
2455 }
2456 }
2457 if (long_options[option_index].has_arg == optional_argument &&
2458 !optarg && argv[optind] && argv[optind][0] != '-')
2459 optarg = argv[optind++];
2460
2461 switch (ch) {
2462 case OptHelp:
2463 usage();
2464 return 0;
2465 case OptSetDevice:
2466 device = optarg;
2467 if (device[0] >= '0' && device[0] <= '9' && device.length() <= 3) {
2468 static char newdev[20];
2469
2470 sprintf(newdev, "/dev/cec%s", optarg);
2471 device = newdev;
2472 }
2473 break;
2474 case OptSetDriver:
2475 driver = optarg;
2476 break;
2477 case OptSetAdapter:
2478 adapter = optarg;
2479 break;
2480 case OptVerbose:
2481 verbose = true;
2482 break;
2483 case OptFrom:
2484 from = strtoul(optarg, nullptr, 0) & 0xf;
2485 break;
2486 case OptTo:
2487 to = strtoul(optarg, nullptr, 0) & 0xf;
2488 if (first_to == 0xff)
2489 first_to = to;
2490 break;
2491 case OptTimeout:
2492 timeout = strtoul(optarg, nullptr, 0);
2493 break;
2494 case OptMonitorTime:
2495 monitor_time = strtoul(optarg, nullptr, 0);
2496 break;
2497 case OptIgnore: {
2498 bool all_la = !strncmp(optarg, "all", 3);
2499 bool all_opcodes = true;
2500 const char *sep = std::strchr(optarg, ',');
2501 unsigned la_mask = 0xffff, opcode, la = 0;
2502
2503 if (sep)
2504 all_opcodes = !strncmp(sep + 1, "all", 3);
2505 if (!all_la) {
2506 la = strtoul(optarg, nullptr, 0);
2507
2508 if (la > 15) {
2509 fprintf(stderr, "invalid logical address (> 15)\n");
2510 usage();
2511 return 1;
2512 }
2513 la_mask = 1 << la;
2514 }
2515 if (!all_opcodes) {
2516 if (!strncmp(sep + 1, "poll", 4)) {
2517 opcode = POLL_FAKE_OPCODE;
2518 } else {
2519 opcode = strtoul(sep + 1, nullptr, 0);
2520 if (opcode > 255) {
2521 fprintf(stderr, "invalid opcode (> 255)\n");
2522 usage();
2523 return 1;
2524 }
2525 }
2526 ignore_opcode[opcode] |= la_mask;
2527 break;
2528 }
2529 if (all_la && all_opcodes) {
2530 fprintf(stderr, "all,all is invalid\n");
2531 usage();
2532 return 1;
2533 }
2534 ignore_la[la] = true;
2535 break;
2536 }
2537 case OptStorePin:
2538 store_pin = optarg;
2539 break;
2540 case OptAnalyzePin:
2541 analyze_pin = optarg;
2542 break;
2543 case OptToggleNoReply:
2544 reply = !reply;
2545 break;
2546 case OptPhysAddr:
2547 phys_addr = cec_parse_phys_addr(optarg);
2548 break;
2549 case OptPhysAddrFromEDIDPoll:
2550 edid_path = optarg;
2551 fallthrough;
2552 case OptPhysAddrFromEDID:
2553 phys_addr = parse_phys_addr_from_edid(optarg);
2554 break;
2555 case OptOsdName:
2556 osd_name = optarg;
2557 break;
2558 case OptVendorID:
2559 vendor_id = strtoul(optarg, nullptr, 0) & 0x00ffffff;
2560 break;
2561 case OptRcTVProfile1:
2562 rc_tv = CEC_OP_FEAT_RC_TV_PROFILE_1;
2563 break;
2564 case OptRcTVProfile2:
2565 rc_tv = CEC_OP_FEAT_RC_TV_PROFILE_2;
2566 break;
2567 case OptRcTVProfile3:
2568 rc_tv = CEC_OP_FEAT_RC_TV_PROFILE_3;
2569 break;
2570 case OptRcTVProfile4:
2571 rc_tv = CEC_OP_FEAT_RC_TV_PROFILE_4;
2572 break;
2573 case OptRcSrcDevRoot:
2574 rc_src |= CEC_OP_FEAT_RC_SRC_HAS_DEV_ROOT_MENU;
2575 break;
2576 case OptRcSrcDevSetup:
2577 rc_src |= CEC_OP_FEAT_RC_SRC_HAS_DEV_SETUP_MENU;
2578 break;
2579 case OptRcSrcContents:
2580 rc_src |= CEC_OP_FEAT_RC_SRC_HAS_CONTENTS_MENU;
2581 break;
2582 case OptRcSrcMediaTop:
2583 rc_src |= CEC_OP_FEAT_RC_SRC_HAS_MEDIA_TOP_MENU;
2584 break;
2585 case OptRcSrcMediaContext:
2586 rc_src |= CEC_OP_FEAT_RC_SRC_HAS_MEDIA_CONTEXT_MENU;
2587 break;
2588 case OptFeatRecordTVScreen:
2589 dev_features |= CEC_OP_FEAT_DEV_HAS_RECORD_TV_SCREEN;
2590 break;
2591 case OptFeatSetOSDString:
2592 dev_features |= CEC_OP_FEAT_DEV_HAS_SET_OSD_STRING;
2593 break;
2594 case OptFeatDeckControl:
2595 dev_features |= CEC_OP_FEAT_DEV_HAS_DECK_CONTROL;
2596 break;
2597 case OptFeatSetAudioRate:
2598 dev_features |= CEC_OP_FEAT_DEV_HAS_SET_AUDIO_RATE;
2599 break;
2600 case OptFeatSinkHasARCTx:
2601 dev_features |= CEC_OP_FEAT_DEV_SINK_HAS_ARC_TX;
2602 break;
2603 case OptFeatSourceHasARCRx:
2604 dev_features |= CEC_OP_FEAT_DEV_SOURCE_HAS_ARC_RX;
2605 break;
2606 case OptPlayback:
2607 case OptRecord:
2608 if (options[OptPlayback] && options[OptRecord]) {
2609 fprintf(stderr, "--playback and --record cannot be combined.\n\n");
2610 usage();
2611 return 1;
2612 }
2613 break;
2614 case OptSwitch:
2615 case OptCDCOnly:
2616 case OptUnregistered:
2617 if (options[OptCDCOnly] + options[OptUnregistered] + options[OptSwitch] > 1) {
2618 fprintf(stderr, "--switch, --cdc-only and --unregistered cannot be combined.\n\n");
2619 usage();
2620 return 1;
2621 }
2622 break;
2623 case ':':
2624 fprintf(stderr, "Option '%s' requires a value\n\n",
2625 argv[optind]);
2626 usage();
2627 return 1;
2628 case '?':
2629 if (argv[optind])
2630 fprintf(stderr, "Unknown argument '%s'\n\n", argv[optind]);
2631 usage();
2632 return 1;
2633 case OptVendorCommand: {
2634 static constexpr const char *arg_names[] = {
2635 "payload",
2636 nullptr
2637 };
2638 char *value, *endptr, *subs = optarg;
2639 __u8 size = 0;
2640 __u8 bytes[14];
2641
2642 while (*subs != '\0') {
2643 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2644 case 0:
2645 while (size < sizeof(bytes)) {
2646 bytes[size++] = strtoul(value, &endptr, 0L);
2647 if (endptr == value) {
2648 size--;
2649 break;
2650 }
2651 value = std::strchr(value, ':');
2652 if (value == nullptr)
2653 break;
2654 value++;
2655 }
2656 break;
2657 default:
2658 std::exit(EXIT_FAILURE);
2659 }
2660 }
2661 if (size) {
2662 cec_msg_vendor_command(&msg, size, bytes);
2663 msgs.push_back(msg);
2664 }
2665 break;
2666 }
2667 case OptCustomCommand: {
2668 static constexpr const char *arg_names[] = {
2669 "cmd",
2670 "payload",
2671 nullptr
2672 };
2673 char *value, *endptr, *subs = optarg;
2674 bool have_cmd = false;
2675 __u8 cmd = 0;
2676 __u8 size = 0;
2677 __u8 bytes[14];
2678
2679 while (*subs != '\0') {
2680 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2681 case 0:
2682 cmd = strtoul(value, &endptr, 0L);
2683 have_cmd = true;
2684 break;
2685 case 1:
2686 while (size < sizeof(bytes)) {
2687 bytes[size++] = strtoul(value, &endptr, 0L);
2688 if (endptr == value) {
2689 size--;
2690 break;
2691 }
2692 value = std::strchr(value, ':');
2693 if (value == nullptr)
2694 break;
2695 value++;
2696 }
2697 break;
2698 default:
2699 std::exit(EXIT_FAILURE);
2700 }
2701 }
2702 if (have_cmd) {
2703 msg.len = 2 + size;
2704 msg.msg[1] = cmd;
2705 memcpy(msg.msg + 2, bytes, size);
2706 msgs.push_back(msg);
2707 }
2708 break;
2709 }
2710 case OptVendorCommandWithID: {
2711 static constexpr const char *arg_names[] = {
2712 "vendor-id",
2713 "reply",
2714 "cmd",
2715 nullptr
2716 };
2717 char *value, *endptr, *subs = optarg;
2718 __u32 vendor_id = 0;
2719 __u8 size = 0;
2720 __u8 bytes[11];
2721
2722 while (*subs != '\0') {
2723 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2724 case 0:
2725 vendor_id = strtoul(value, nullptr, 0);
2726 break;
2727 case 1:
2728 msg.reply = strtoul(value, &endptr, 0L);
2729 msg.flags = CEC_MSG_FL_REPLY_VENDOR_ID;
2730 break;
2731 case 2:
2732 while (size < sizeof(bytes)) {
2733 bytes[size++] = strtoul(value, &endptr, 0L);
2734 if (endptr == value) {
2735 size--;
2736 break;
2737 }
2738 value = std::strchr(value, ':');
2739 if (value == nullptr)
2740 break;
2741 value++;
2742 }
2743 break;
2744 default:
2745 std::exit(EXIT_FAILURE);
2746 }
2747 }
2748 if (size) {
2749 cec_msg_vendor_command_with_id(&msg, vendor_id, size, bytes);
2750 msgs.push_back(msg);
2751 }
2752 break;
2753 }
2754 case OptVendorRemoteButtonDown: {
2755 static constexpr const char *arg_names[] = {
2756 "rc-code",
2757 nullptr
2758 };
2759 char *value, *endptr, *subs = optarg;
2760 __u8 size = 0;
2761 __u8 bytes[14];
2762
2763 while (*subs != '\0') {
2764 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2765 case 0:
2766 while (size < sizeof(bytes)) {
2767 bytes[size++] = strtoul(value, &endptr, 0L);
2768 if (endptr == value) {
2769 size--;
2770 break;
2771 }
2772 value = std::strchr(value, ':');
2773 if (value == nullptr)
2774 break;
2775 value++;
2776 }
2777 break;
2778 default:
2779 std::exit(EXIT_FAILURE);
2780 }
2781 }
2782 if (size) {
2783 cec_msg_vendor_remote_button_down(&msg, size, bytes);
2784 msgs.push_back(msg);
2785 }
2786 break;
2787 }
2788 case OptPoll:
2789 msgs.push_back(msg);
2790 break;
2791
2792 case OptListDevices:
2793 if (driver || adapter) {
2794 device = cec_device_find(driver, adapter);
2795 if (!device.empty())
2796 printf("%s\n", device.c_str());
2797 return 0;
2798 }
2799 list_devices();
2800 return 0;
2801
2802 case OptTestReliability:
2803 test_reliability_duration = strtoul(optarg, nullptr, 0);
2804 break;
2805
2806 case OptTestStandbyWakeupCycle: {
2807 static constexpr const char *arg_names[] = {
2808 "polls",
2809 "sleep",
2810 "hpd-may-be-low",
2811 nullptr
2812 };
2813 char *value, *subs = optarg;
2814
2815 warn_if_unconfigured = true;
2816 if (!optarg)
2817 break;
2818
2819 while (*subs != '\0') {
2820 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2821 case 0:
2822 test_standby_wakeup_cycle_polls = strtoul(value, nullptr, 0);
2823 break;
2824 case 1:
2825 test_standby_wakeup_cycle_sleep = strtoul(value, nullptr, 0);
2826 break;
2827 case 2:
2828 test_standby_wakeup_cycle_hpd_may_be_low = !!strtoul(value, nullptr, 0);
2829 break;
2830 default:
2831 std::exit(EXIT_FAILURE);
2832 }
2833 }
2834 break;
2835 }
2836
2837 case OptStressTestStandbyWakeupCycle: {
2838 static constexpr const char *arg_names[] = {
2839 "cnt",
2840 "min-sleep",
2841 "max-sleep",
2842 "seed",
2843 "repeats",
2844 "sleep-before-on",
2845 "sleep-before-off",
2846 "polls",
2847 "hpd-may-be-low",
2848 nullptr
2849 };
2850 char *value, *subs = optarg;
2851
2852 while (*subs != '\0') {
2853 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2854 case 0:
2855 stress_test_standby_wakeup_cycle_cnt = strtoul(value, nullptr, 0);
2856 break;
2857 case 1:
2858 stress_test_standby_wakeup_cycle_min_sleep = strtod(value, nullptr);
2859 break;
2860 case 2:
2861 stress_test_standby_wakeup_cycle_max_sleep = strtod(value, nullptr);
2862 break;
2863 case 3:
2864 stress_test_standby_wakeup_cycle_has_seed = true;
2865 stress_test_standby_wakeup_cycle_seed = strtoul(value, nullptr, 0);
2866 break;
2867 case 4:
2868 stress_test_standby_wakeup_cycle_repeats = strtoul(value, nullptr, 0);
2869 break;
2870 case 5:
2871 stress_test_standby_wakeup_cycle_sleep_before_on = strtod(value, nullptr);
2872 break;
2873 case 6:
2874 stress_test_standby_wakeup_cycle_sleep_before_off = strtod(value, nullptr);
2875 break;
2876 case 7:
2877 stress_test_standby_wakeup_cycle_polls = strtoul(value, nullptr, 0);
2878 break;
2879 case 8:
2880 stress_test_standby_wakeup_cycle_hpd_may_be_low = !!strtoul(value, nullptr, 0);
2881 break;
2882 default:
2883 std::exit(EXIT_FAILURE);
2884 }
2885 }
2886 if (stress_test_standby_wakeup_cycle_min_sleep > stress_test_standby_wakeup_cycle_max_sleep) {
2887 fprintf(stderr, "min-sleep > max-sleep\n");
2888 std::exit(EXIT_FAILURE);
2889 }
2890 warn_if_unconfigured = true;
2891 break;
2892 }
2893
2894 case OptStressTestRandomStandbyWakeupCycle: {
2895 static constexpr const char *arg_names[] = {
2896 "cnt",
2897 "min-sleep",
2898 "max-sleep",
2899 "seed",
2900 "hpd-may-be-low",
2901 nullptr
2902 };
2903 char *value, *subs = optarg;
2904
2905 while (*subs != '\0') {
2906 switch (cec_parse_subopt(&subs, arg_names, &value)) {
2907 case 0:
2908 stress_test_random_standby_wakeup_cnt = strtoul(value, nullptr, 0);
2909 break;
2910 case 1:
2911 stress_test_random_standby_wakeup_min_sleep = strtod(value, nullptr);
2912 break;
2913 case 2:
2914 stress_test_random_standby_wakeup_max_sleep = strtod(value, nullptr);
2915 break;
2916 case 3:
2917 stress_test_random_standby_wakeup_has_seed = true;
2918 stress_test_random_standby_wakeup_seed = strtoul(value, nullptr, 0);
2919 break;
2920 case 4:
2921 stress_test_random_standby_wakeup_hpd_may_be_low = !!strtoul(value, nullptr, 0);
2922 break;
2923 default:
2924 std::exit(EXIT_FAILURE);
2925 }
2926 }
2927 if (stress_test_random_standby_wakeup_min_sleep > stress_test_random_standby_wakeup_max_sleep) {
2928 fprintf(stderr, "min-sleep > max-sleep\n");
2929 std::exit(EXIT_FAILURE);
2930 }
2931 warn_if_unconfigured = true;
2932 break;
2933 }
2934
2935 case OptVersion:
2936 print_version();
2937 std::exit(EXIT_SUCCESS);
2938
2939 default:
2940 if (ch >= OptHelpAll) {
2941 cec_parse_usage_options(options);
2942 std::exit(EXIT_SUCCESS);
2943 }
2944 if (ch <= OptMessages)
2945 break;
2946 opt = cec_log_msg_args(ch - OptMessages - 1);
2947 cec_parse_msg_args(msg, reply, opt, ch);
2948 msgs.push_back(msg);
2949 break;
2950 }
2951 }
2952 if (optind < argc) {
2953 fprintf(stderr, "unknown arguments: ");
2954 while (optind < argc)
2955 fprintf(stderr, "%s ", argv[optind++]);
2956 fprintf(stderr, "\n");
2957 usage();
2958 return 1;
2959 }
2960
2961 if (!msgs.empty())
2962 warn_if_unconfigured = true;
2963
2964 if (store_pin && analyze_pin) {
2965 fprintf(stderr, "--store-pin and --analyze-pin options cannot be combined.\n\n");
2966 usage();
2967 return 1;
2968 }
2969
2970 if (analyze_pin && options[OptSetDevice]) {
2971 fprintf(stderr, "--device and --analyze-pin options cannot be combined.\n\n");
2972 usage();
2973 return 1;
2974 }
2975
2976 if (analyze_pin) {
2977 analyze(analyze_pin);
2978 return 0;
2979 }
2980
2981 if (options[OptWallClock] && !options[OptMonitorPin])
2982 verbose = true;
2983
2984 if (store_pin && !strcmp(store_pin, "-"))
2985 options[OptSkipInfo] = 1;
2986
2987 if (rc_tv && rc_src) {
2988 fprintf(stderr, "--rc-tv- and --rc-src- options cannot be combined.\n\n");
2989 usage();
2990 return 1;
2991 }
2992
2993 if (rc_tv && !options[OptTV]) {
2994 fprintf(stderr, "--rc-tv- can only be used in combination with --tv.\n\n");
2995 usage();
2996 return 1;
2997 }
2998
2999 if (rc_src && options[OptTV]) {
3000 fprintf(stderr, "--rc-src- can't be used in combination with --tv.\n\n");
3001 usage();
3002 return 1;
3003 }
3004
3005 if ((dev_features & (CEC_OP_FEAT_DEV_SOURCE_HAS_ARC_RX |
3006 CEC_OP_FEAT_DEV_HAS_DECK_CONTROL |
3007 CEC_OP_FEAT_DEV_HAS_SET_AUDIO_RATE)) && options[OptTV]) {
3008 fprintf(stderr, "--feat-deck-control, --feat-set-audio-rate and --feat-source-has-arc-rx cannot be used in combination with --tv.\n\n");
3009 usage();
3010 return 1;
3011 }
3012
3013 if ((dev_features & (CEC_OP_FEAT_DEV_HAS_RECORD_TV_SCREEN |
3014 CEC_OP_FEAT_DEV_HAS_SET_OSD_STRING)) && !options[OptTV]) {
3015 fprintf(stderr, "--feat-set-osd-string and --feat-record-tv-screen can only be used in combination with --tv.\n\n");
3016 usage();
3017 return 1;
3018 }
3019
3020 if (device.empty() && (driver || adapter)) {
3021 device = cec_device_find(driver, adapter);
3022 if (device.empty()) {
3023 fprintf(stderr,
3024 "Could not find a CEC device for the given driver/adapter combination\n");
3025 std::exit(EXIT_FAILURE);
3026 }
3027 }
3028 if (device.empty())
3029 device = "/dev/cec0";
3030
3031 clock_gettime(CLOCK_MONOTONIC, &start_monotonic);
3032 gettimeofday(&start_timeofday, nullptr);
3033
3034 if ((fd = open(device.c_str(), O_RDWR)) < 0) {
3035 fprintf(stderr, "Failed to open %s: %s\n", device.c_str(),
3036 strerror(errno));
3037 std::exit(EXIT_FAILURE);
3038 }
3039
3040 struct node node;
3041 struct cec_caps caps = { };
3042
3043 node.fd = fd;
3044 node.device = device.c_str();
3045 doioctl(&node, CEC_ADAP_G_CAPS, &caps);
3046 node.caps = caps.capabilities;
3047 node.available_log_addrs = caps.available_log_addrs;
3048
3049 bool set_phys_addr = options[OptPhysAddr] || options[OptPhysAddrFromEDID] ||
3050 options[OptPhysAddrFromEDIDPoll];
3051
3052 if (set_phys_addr && !(node.caps & CEC_CAP_PHYS_ADDR))
3053 fprintf(stderr, "The CEC adapter doesn't allow setting the physical address manually, ignore this option.\n\n");
3054
3055 unsigned flags = 0;
3056
3057 if (options[OptOsdName])
3058 ;
3059 else if (options[OptTV])
3060 osd_name = "TV";
3061 else if (options[OptRecord])
3062 osd_name = "Record";
3063 else if (options[OptPlayback])
3064 osd_name = "Playback";
3065 else if (options[OptTuner])
3066 osd_name = "Tuner";
3067 else if (options[OptAudio])
3068 osd_name = "Audio System";
3069 else if (options[OptProcessor])
3070 osd_name = "Processor";
3071 else if (options[OptSwitch] || options[OptCDCOnly] || options[OptUnregistered])
3072 osd_name = "";
3073 else
3074 osd_name = "TV";
3075
3076 if (options[OptTV])
3077 flags |= 1 << CEC_OP_PRIM_DEVTYPE_TV;
3078 if (options[OptRecord])
3079 flags |= 1 << CEC_OP_PRIM_DEVTYPE_RECORD;
3080 if (options[OptTuner])
3081 flags |= 1 << CEC_OP_PRIM_DEVTYPE_TUNER;
3082 if (options[OptPlayback])
3083 flags |= 1 << CEC_OP_PRIM_DEVTYPE_PLAYBACK;
3084 if (options[OptAudio])
3085 flags |= 1 << CEC_OP_PRIM_DEVTYPE_AUDIOSYSTEM;
3086 if (options[OptProcessor])
3087 flags |= 1 << CEC_OP_PRIM_DEVTYPE_PROCESSOR;
3088 if (options[OptSwitch] || options[OptCDCOnly] || options[OptUnregistered])
3089 flags |= 1 << CEC_OP_PRIM_DEVTYPE_SWITCH;
3090
3091 if (flags == 0 && (rc_tv || rc_src || dev_features)) {
3092 fprintf(stderr, "The --feat- and --rc- options can only be used in combination with selecting the device type.\n\n");
3093 usage();
3094 return 1;
3095 }
3096
3097 bool set_log_addrs = (node.caps & CEC_CAP_LOG_ADDRS) && flags;
3098 bool clear_log_addrs = (node.caps & CEC_CAP_LOG_ADDRS) && options[OptClear];
3099
3100 // When setting both PA and LA it is best to clear the LAs first.
3101 if (clear_log_addrs || (set_phys_addr && set_log_addrs)) {
3102 struct cec_log_addrs laddrs = { };
3103
3104 doioctl(&node, CEC_ADAP_S_LOG_ADDRS, &laddrs);
3105 }
3106
3107 if (set_phys_addr)
3108 doioctl(&node, CEC_ADAP_S_PHYS_ADDR, &phys_addr);
3109
3110 doioctl(&node, CEC_ADAP_G_PHYS_ADDR, &phys_addr);
3111
3112 if (set_log_addrs) {
3113 struct cec_log_addrs laddrs = {};
3114 __u8 all_dev_types = 0;
3115 __u8 prim_type = 0xff;
3116
3117 doioctl(&node, CEC_ADAP_S_LOG_ADDRS, &laddrs);
3118 memset(&laddrs, 0, sizeof(laddrs));
3119
3120 laddrs.cec_version = options[OptCECVersion1_4] ?
3121 CEC_OP_CEC_VERSION_1_4 : CEC_OP_CEC_VERSION_2_0;
3122 strncpy(laddrs.osd_name, osd_name, sizeof(laddrs.osd_name));
3123 laddrs.osd_name[sizeof(laddrs.osd_name) - 1] = 0;
3124 laddrs.vendor_id = vendor_id;
3125 if (options[OptAllowUnregFallback])
3126 laddrs.flags |= CEC_LOG_ADDRS_FL_ALLOW_UNREG_FALLBACK;
3127 if (!options[OptNoRC] && flags != (1 << CEC_OP_PRIM_DEVTYPE_SWITCH))
3128 laddrs.flags |= CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU;
3129 if (options[OptCDCOnly])
3130 laddrs.flags |= CEC_LOG_ADDRS_FL_CDC_ONLY;
3131
3132 for (unsigned i = 0; i < 8; i++) {
3133 unsigned la_type;
3134
3135 if (!(flags & (1 << i)))
3136 continue;
3137 if (prim_type == 0xff)
3138 prim_type = i;
3139 if (laddrs.num_log_addrs == node.available_log_addrs) {
3140 fprintf(stderr, "Attempt to define too many logical addresses\n");
3141 std::exit(EXIT_FAILURE);
3142 }
3143 switch (i) {
3144 case CEC_OP_PRIM_DEVTYPE_TV:
3145 la_type = CEC_LOG_ADDR_TYPE_TV;
3146 all_dev_types |= CEC_OP_ALL_DEVTYPE_TV;
3147 prim_type = i;
3148 break;
3149 case CEC_OP_PRIM_DEVTYPE_RECORD:
3150 la_type = CEC_LOG_ADDR_TYPE_RECORD;
3151 all_dev_types |= CEC_OP_ALL_DEVTYPE_RECORD;
3152 break;
3153 case CEC_OP_PRIM_DEVTYPE_TUNER:
3154 la_type = CEC_LOG_ADDR_TYPE_TUNER;
3155 all_dev_types |= CEC_OP_ALL_DEVTYPE_TUNER;
3156 break;
3157 case CEC_OP_PRIM_DEVTYPE_PLAYBACK:
3158 la_type = CEC_LOG_ADDR_TYPE_PLAYBACK;
3159 all_dev_types |= CEC_OP_ALL_DEVTYPE_PLAYBACK;
3160 break;
3161 case CEC_OP_PRIM_DEVTYPE_AUDIOSYSTEM:
3162 la_type = CEC_LOG_ADDR_TYPE_AUDIOSYSTEM;
3163 all_dev_types |= CEC_OP_ALL_DEVTYPE_AUDIOSYSTEM;
3164 if (prim_type != CEC_OP_PRIM_DEVTYPE_TV)
3165 prim_type = i;
3166 break;
3167 case CEC_OP_PRIM_DEVTYPE_PROCESSOR:
3168 la_type = CEC_LOG_ADDR_TYPE_SPECIFIC;
3169 all_dev_types |= CEC_OP_ALL_DEVTYPE_SWITCH;
3170 break;
3171 case CEC_OP_PRIM_DEVTYPE_SWITCH:
3172 default:
3173 la_type = CEC_LOG_ADDR_TYPE_UNREGISTERED;
3174 all_dev_types |= CEC_OP_ALL_DEVTYPE_SWITCH;
3175 break;
3176 }
3177 laddrs.log_addr_type[laddrs.num_log_addrs++] = la_type;
3178 }
3179 for (unsigned i = 0; i < laddrs.num_log_addrs; i++) {
3180 laddrs.primary_device_type[i] = prim_type;
3181 laddrs.all_device_types[i] = all_dev_types;
3182 laddrs.features[i][0] = rc_tv | rc_src;
3183 laddrs.features[i][1] = dev_features;
3184 }
3185
3186 doioctl(&node, CEC_ADAP_S_LOG_ADDRS, &laddrs);
3187 }
3188
3189 struct cec_log_addrs laddrs = { };
3190 doioctl(&node, CEC_ADAP_G_LOG_ADDRS, &laddrs);
3191 node.num_log_addrs = laddrs.num_log_addrs;
3192 node.log_addr_mask = laddrs.log_addr_mask;
3193 node.phys_addr = phys_addr;
3194
3195 for (i = 0; i < laddrs.num_log_addrs; i++) {
3196 __u8 la = laddrs.log_addr[i];
3197
3198 if (la != CEC_LOG_ADDR_INVALID)
3199 phys_addrs[la] = (phys_addr << 8) | la;
3200 }
3201
3202 if (options[OptTestReliability] ||
3203 options[OptTestStandbyWakeupCycle] ||
3204 options[OptStressTestStandbyWakeupCycle] ||
3205 options[OptStressTestRandomStandbyWakeupCycle]) {
3206 print_version();
3207 printf("\n");
3208 }
3209
3210 if (!options[OptSkipInfo]) {
3211 struct cec_connector_info conn_info = {};
3212
3213 doioctl(&node, CEC_ADAP_G_CONNECTOR_INFO, &conn_info);
3214
3215 cec_driver_info(caps, laddrs, phys_addr, conn_info);
3216 }
3217
3218 if (options[OptPhysAddrFromEDIDPoll]) {
3219 pthread_t t;
3220 int ret = pthread_create(&t, nullptr, thread_edid_poll, &node);
3221 if (ret) {
3222 fprintf(stderr, "Failed to start EDID poll thread: %s\n",
3223 strerror(errno));
3224 std::exit(EXIT_FAILURE);
3225 }
3226 }
3227
3228 if (options[OptShowPhysAddr])
3229 printf("%x.%x.%x.%x\n", cec_phys_addr_exp(phys_addr));
3230
3231 if (node.num_log_addrs == 0) {
3232 if (options[OptMonitor] || options[OptMonitorAll] ||
3233 options[OptMonitorPin])
3234 goto skip_la;
3235 if (warn_if_unconfigured)
3236 fprintf(stderr, "\nAdapter is unconfigured, please configure it first.\n");
3237 return 0;
3238 }
3239 if (!options[OptSkipInfo])
3240 printf("\n");
3241
3242 if (!options[OptFrom])
3243 from = laddrs.log_addr[0] & 0xf;
3244
3245 if (options[OptShowTopology])
3246 showTopology(&node);
3247
3248 if (options[OptShowLogicalAddress])
3249 printf("%d\n", laddrs.log_addr[0] & 0xf);
3250 if (options[OptShowLogicalAddresses]) {
3251 for (i = 0; i < laddrs.num_log_addrs; i++)
3252 printf("%d ", laddrs.log_addr[i] & 0xf);
3253 printf("\n");
3254 }
3255
3256 if (options[OptWaitForMsgs]) {
3257 __u32 monitor = CEC_MODE_INITIATOR | CEC_MODE_FOLLOWER;
3258
3259 if (doioctl(&node, CEC_S_MODE, &monitor)) {
3260 fprintf(stderr, "Selecting follower mode failed.\n");
3261 return 1;
3262 }
3263 }
3264 if (options[OptNonBlocking])
3265 fcntl(node.fd, F_SETFL, fcntl(node.fd, F_GETFL) | O_NONBLOCK);
3266
3267 for (auto &msg : msgs) {
3268 fflush(stdout);
3269 if (!cec_msg_is_broadcast(&msg) && !options[OptTo]) {
3270 fprintf(stderr, "attempting to send message without --to\n");
3271 std::exit(EXIT_FAILURE);
3272 }
3273 if (msg.msg[0] == 0xf0)
3274 msg.msg[0] = first_to;
3275 msg.msg[0] &= 0x0f;
3276 msg.msg[0] |= from << 4;
3277 to = msg.msg[0] & 0xf;
3278 printf("\nTransmit from %s to %s (%d to %d):\n",
3279 cec_la2s(from), to == 0xf ? "all" : cec_la2s(to), from, to);
3280 msg.flags |= options[OptReplyToFollowers] ? CEC_MSG_FL_REPLY_TO_FOLLOWERS : 0;
3281 msg.flags |= options[OptRawMsg] ? CEC_MSG_FL_RAW : 0;
3282 msg.timeout = (msg.flags & CEC_MSG_FL_REPLY_VENDOR_ID) || msg.reply ? timeout : 0;
3283 cec_log_msg(&msg);
3284 if (options[OptShowRaw])
3285 log_raw_msg(&msg);
3286 if (doioctl(&node, CEC_TRANSMIT, &msg))
3287 continue;
3288 if (msg.rx_status & (CEC_RX_STATUS_OK | CEC_RX_STATUS_FEATURE_ABORT)) {
3289 printf(" Received from %s (%d):\n ", cec_la2s(cec_msg_initiator(&msg)),
3290 cec_msg_initiator(&msg));
3291 cec_log_msg(&msg);
3292 if (options[OptShowRaw])
3293 log_raw_msg(&msg);
3294 }
3295 printf("\tSequence: %u Tx Timestamp: %s",
3296 msg.sequence, ts2s(msg.tx_ts).c_str());
3297 if (msg.rx_ts)
3298 printf(" Rx Timestamp: %s\n\tApproximate response time: %u ms",
3299 ts2s(msg.rx_ts).c_str(),
3300 response_time_ms(msg));
3301 printf("\n");
3302 if (!cec_msg_status_is_ok(&msg) || verbose)
3303 printf("\t%s\n", cec_status2s(msg).c_str());
3304 }
3305 fflush(stdout);
3306
3307 if (options[OptNonBlocking])
3308 fcntl(node.fd, F_SETFL, fcntl(node.fd, F_GETFL) & ~O_NONBLOCK);
3309
3310 if (options[OptTestReliability])
3311 test_reliability(node, to, test_reliability_duration);
3312 if (options[OptTestStandbyWakeupCycle])
3313 test_standby_wakeup_cycle(node,
3314 test_standby_wakeup_cycle_polls,
3315 test_standby_wakeup_cycle_sleep,
3316 test_standby_wakeup_cycle_hpd_may_be_low);
3317 if (options[OptStressTestStandbyWakeupCycle])
3318 stress_test_standby_wakeup_cycle(node,
3319 stress_test_standby_wakeup_cycle_cnt,
3320 stress_test_standby_wakeup_cycle_min_sleep,
3321 stress_test_standby_wakeup_cycle_max_sleep,
3322 stress_test_standby_wakeup_cycle_polls,
3323 stress_test_standby_wakeup_cycle_has_seed,
3324 stress_test_standby_wakeup_cycle_seed,
3325 stress_test_standby_wakeup_cycle_repeats,
3326 stress_test_standby_wakeup_cycle_sleep_before_on,
3327 stress_test_standby_wakeup_cycle_sleep_before_off,
3328 stress_test_standby_wakeup_cycle_hpd_may_be_low);
3329 if (options[OptStressTestRandomStandbyWakeupCycle])
3330 stress_test_random_standby_wakeup_cycle(node,
3331 stress_test_random_standby_wakeup_cnt,
3332 stress_test_random_standby_wakeup_min_sleep,
3333 stress_test_random_standby_wakeup_max_sleep,
3334 stress_test_random_standby_wakeup_has_seed,
3335 stress_test_random_standby_wakeup_seed,
3336 stress_test_random_standby_wakeup_hpd_may_be_low);
3337
3338 skip_la:
3339 if (options[OptMonitor] || options[OptMonitorAll] ||
3340 options[OptMonitorPin]) {
3341 monitor(node, monitor_time, store_pin);
3342 } else if (options[OptWaitForMsgs]) {
3343 wait_for_msgs(node, monitor_time);
3344 } else if (options[OptPhysAddrFromEDIDPoll]) {
3345 printf("Press Ctrl-C to stop EDID polling.\n");
3346 is_paused = true;
3347 pause();
3348 }
3349 fflush(stdout);
3350 close(fd);
3351 return 0;
3352 }