forked from glywood/cec-fix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
624 lines (550 loc) · 15.6 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#include <bcm_host.h>
#include <iostream>
#include <stdexcept>
#include <unistd.h>
#include <stdlib.h>
#include "spdlog/spdlog.h"
#include <string.h>
#include <signal.h>
#include <unordered_map>
#include "lan.hpp"
#include "fifo.hpp"
using namespace std;
bool want_run = true;
// Mapping of logical to physical addresses
unordered_map<CEC_AllDevices_T, uint8_t*> addressMap { 0 };
const char OSD_NAME[] { "JVC NX7" };
/**
* Return string representation of a message payload.
*
* @param unit8_t * payload The message payload as an array of bytes.
* @param size_t length The length of the message.
*
* @return string
*/
string getOpcodeString(uint8_t* payload, size_t length) {
string content = "";
if (!length) {
return content;
}
for (size_t i = 0; i < length; i++) {
content += fmt::format("{:X} ", payload[i]);
}
content.pop_back(); // Remove trailing space
return content;
}
/**
* Request the physical address of a logical address.
*
* @param CEC_AllDevices follower Logical address of the device.
*/
void getPhysicalAddress(CEC_AllDevices follower) {
spdlog::info("Get physical address for {}", follower);
uint8_t bytes[1];
bytes[0] = CEC_Opcode_GivePhysicalAddress;
if (vc_cec_send_message(follower,
bytes, 1, VC_FALSE) != 0) {
spdlog::error( "Failed to request physical address.");
}
}
/**
* Set the stream path to a physical address.
*
* @param uint8_t * physicalAddress Array of bytes representing a device's physical address.
*/
void setStreamPath(uint8_t * physicalAddress) {
string path = getOpcodeString(physicalAddress, 2);
spdlog::info("Set stream path to: {}", path);
uint8_t bytes[3];
bytes[0] = CEC_Opcode_SetStreamPath;
bytes[1] = physicalAddress[0];
bytes[2] = physicalAddress[1];
if (vc_cec_send_message(CEC_BROADCAST_ADDR,
bytes, 3, VC_FALSE) != 0) {
spdlog::error( "Failed to set stream path.");
}
}
// Marker to remember if we are waiting on a physical address to set the stream path.
bool want_set_stream_path = false;
/**
* Set the stream path to Playback1 device.
*/
void setStreamPathToPlayback1() {
uint8_t * address;
try {
address = addressMap.at(CEC_AllDevices_eDVD1);
} catch(const out_of_range &e) {
want_set_stream_path = true;
getPhysicalAddress(CEC_AllDevices_eDVD1);
return;
}
if (address) {
setStreamPath(address);
}
}
/**
* Whether a CEC message is a device reporting physical address.
*
* @return bool
*/
bool isReportPhysicalAddress(VC_CEC_MESSAGE_T &message) {
return (
message.length > 1 &&
message.payload[0] == CEC_Opcode_ReportPhysicalAddress
);
}
/**
* Handler for a CEC message that reports a device's physical address.
*
* @param VC_CEC_MESSAGE_T message The message to parse.
*/
void handleReportPhysicalAddress(VC_CEC_MESSAGE_T &message) {
string content = getOpcodeString(message.payload, message.length);
spdlog::debug("handleReportPhysicalAddress: {}:{}", message.initiator, content);
// If an existing address exists, free the underlying int array.
try {
uint8_t * existingAddressPtr = addressMap.at(message.initiator);
addressMap.erase(message.initiator);
delete existingAddressPtr;
} catch(const out_of_range &e) { }
// Set (or replace) the address of the initiator
uint8_t * addressPtr = new uint8_t[2];
// Byte 0 of the payload is the command. Bytes 1-2 are the physical address.
addressPtr[0] = message.payload[1];
addressPtr[1] = message.payload[2];
addressMap[message.initiator] = addressPtr;
content = getOpcodeString(addressPtr, 2);
spdlog::debug("Set physical address to `{}` for logical address `{}`", content, message.initiator);
if (want_set_stream_path) {
setStreamPath(addressPtr);
want_set_stream_path = false;
}
}
/**
* Turn off the TV.
*
* @return void
*/
void turnOffTV() {
try {
if (isOff()) {
spdlog::info("TV is already off!");
return;
}
} catch(const runtime_error& e) {
spdlog::warn("Exception caught in turnOffTV: {}", e.what());
// Assume TV is on
}
spdlog::info("Turning off the TV");
if(sendOff() == 0) {
spdlog::info("TV turned off");
}
}
/**
* Turn on the TV.
*
* @return void
*/
void turnOnTV() {
try {
if (isOn()) {
spdlog::info("TV is already on!");
return;
}
} catch(const runtime_error& e) {
spdlog::warn("Exception caught in turnOnTV: {}", e.what());
// Assume TV is off
}
spdlog::info("Turning on the TV");
if(sendOn() == 0) {
spdlog::info("TV turned on");
}
}
/**
* Check whether a CEC message means that a device requested ImageViewOn.
*
* @param C_CEC_MESSAGE_T message The parsed CEC message.
*
* @return bool
*/
bool isImageViewOn(VC_CEC_MESSAGE_T &message) {
return (
message.length == 1 && (
message.payload[0] == CEC_Opcode_ImageViewOn ||
message.payload[0] == CEC_Opcode_TextViewOn
)
);
}
/**
* Whether a CEC message indicates that the TV should switch to standby.
*
* @param C_CEC_MESSAGE_T message The parsed CEC message.
*
* @return bool
*/
bool isTVOffCmd(VC_CEC_MESSAGE_T &message) {
return (
(message.follower == CEC_AllDevices_eTV || message.follower == CEC_BROADCAST_ADDR) &&
message.initiator != CEC_AllDevices_eTV &&
message.length == 1 &&
message.payload[0] == CEC_Opcode_Standby
);
}
/**
* Broadcast a CEC message to all followers to enter standby mode.
*
* @return void
*/
void broadcastStandby() {
spdlog::info("Broadcasting standby");
if (vc_cec_send_Standby(CEC_BROADCAST_ADDR, false) != 0) {
spdlog::error( "Failed to broadcast standby command.");
}
}
/**
* Whether a CEC message is a request for this device's vendor ID.
*
* @param C_CEC_MESSAGE_T message The parsed CEC message.
*
* @return bool
*/
bool isRequestForVendorId(VC_CEC_MESSAGE_T &message) {
return (
message.follower == CEC_AllDevices_eTV &&
message.length == 1 &&
message.payload[0] == CEC_Opcode_GiveDeviceVendorID
);
}
/**
* Broadcast the vendor ID of this device.
* Raspberry Pi uses Broadcom chipset. Vendor ID is 0x18C086L.
*
* @return void
*/
void broadcastVendorId() {
spdlog::info("Broadcasting Vendor ID {}", CEC_VENDOR_ID_BROADCOM);
if(vc_cec_set_vendor_id(CEC_VENDOR_ID_BROADCOM) != 0) {
spdlog::error("Failed to reply with vendor ID.");
}
}
/**
* Whether a CEC message is a request for this device's power status.
*
* @param C_CEC_MESSAGE_T message The parsed CEC message.
*
* @return bool
*/
bool isRequestForPowerStatus(VC_CEC_MESSAGE_T &message) {
return (
message.follower == CEC_AllDevices_eTV &&
message.length == 1 &&
message.payload[0] == CEC_Opcode_GiveDevicePowerStatus
);
}
/**
* Reply to a power status request.
*
* @param int requestor The CEC logical address of the device requesting power status.
*
* @return void
*/
void replyWithPowerStatus(int requestor) {
bool tv_is_on;
try {
tv_is_on = isOn();
} catch(const runtime_error& e) {
spdlog::warn("Exception caught in replyWithPowerStatus: {}", e.what());
return;
}
spdlog::info("Replying with power status: {}", tv_is_on);
uint8_t bytes[2];
bytes[0] = CEC_Opcode_ReportPowerStatus;
bytes[1] = tv_is_on ? CEC_POWER_STATUS_ON : CEC_POWER_STATUS_STANDBY;
if (vc_cec_send_message(requestor,
bytes, 2, VC_TRUE) != 0) {
spdlog::error("Failed to reply with TV power status.");
}
}
/**
* Set the entire system to standby.
*/
int systemStandby() {
spdlog::debug("systemStandby called");
turnOffTV();
broadcastStandby();
return 1;
}
/**
* Turns on the entire system and set active source to Playback 1.
*/
int systemActive() {
spdlog::debug("systemActive called");
turnOnTV();
setStreamPathToPlayback1();
return 1;
}
/**
* Parse a CEC callback into a VC_CEC_MESSAGE_T struct.
*
* @return bool true if parsing was successful, false otherwise.
*/
bool parseCECMessage(VC_CEC_MESSAGE_T &message, uint32_t reason, uint32_t param1, uint32_t param2, uint32_t param3, uint32_t param4) {
int retval = vc_cec_param2message(reason, param1, param2, param3, param4, &message);
bool success = 0 == retval;
string content = getOpcodeString(message.payload, message.length);
if(success) {
spdlog::debug(
"Translated to message: initiator={initiator:X} follower={follower:X} length={length:d} content={content}",
fmt::arg("initiator", message.initiator),
fmt::arg("follower", message.follower),
fmt::arg("length", message.length),
fmt::arg("content", content)
);
} else {
spdlog::warn("Not a valid message!");
}
return success;
}
/**
* Whether a CEC message is request for the OSD name.
*
* @param VC_CEC_MESSAGE_T &message The CEC message.
*
* @return bool
*/
bool isGiveOSDName(VC_CEC_MESSAGE_T &message) {
return (
message.length == 1 &&
message.payload[0] == CEC_Opcode_GiveOSDName
);
}
/**
* Reply to a GiveOSDName request.
*/
void setOSDName() {
spdlog::info("Replying with OSD name: {}", OSD_NAME);
vc_cec_set_osd_name(OSD_NAME);
}
/**
* Callback function for host side notification.
* This is the SAME as the callback function type defined in vc_cec.h
* Host applications register a single callback for all CEC related notifications.
* See vc_cec.h for meanings of all parameters
*
* @param callback_data is the context passed in by user in <DFN>vc_cec_register_callback</DFN>
*
* @param reason bits 15-0 is VC_CEC_NOTIFY_T in vc_cec.h;
* bits 23-16 is the valid length of message in param1 to param4 (LSB of param1 is the byte0, MSB of param4 is byte15), little endian
* bits 31-24 is the return code (if any)
*
* @param param1 is the first parameter
*
* @param param2 is the second parameter
*
* @param param3 is the third parameter
*
* @param param4 is the fourth parameter
*
* @return void
*/
void handleCECCallback(void *callback_data, uint32_t reason, uint32_t param1, uint32_t param2, uint32_t param3, uint32_t param4) {
spdlog::debug(
"Got a callback: reason={reason:X} param1={p1:X} param2={p1:X} param3={p3:X} param4={p4:X}",
fmt::arg("reason", reason),
fmt::arg("p1", param1),
fmt::arg("p2", param2),
fmt::arg("p3", param3),
fmt::arg("p4", param4)
);
VC_CEC_MESSAGE_T message;
if (!parseCECMessage(message, reason, param1, param2, param3, param4)) {
return;
}
// Detect when the TV is being told to turn on. Check the power
// status of the receiver, because if it's not on we'll want to
// turn it on.
if (isImageViewOn(message)) {
spdlog::info("ImageViewOn message received.");
turnOnTV();
// This will result in the audio system sending us back a message
return;
}
// Detect when the TV is being told to go into standby.
if (isTVOffCmd(message)) {
spdlog::info("Standby message received.");
turnOffTV();
broadcastStandby();
return;
}
// Roku likes to ask for this.
if (isRequestForVendorId(message)) {
spdlog::info("Vendor ID request message received.");
broadcastVendorId();
return;
}
// Roku also likes to ask for this.
if (isRequestForPowerStatus(message)) {
spdlog::info("Power status request message received.");
replyWithPowerStatus(message.initiator);
return;
}
if(isReportPhysicalAddress(message)) {
spdlog::info("Report physical address message received.");
handleReportPhysicalAddress(message);
return;
}
if (isGiveOSDName(message)) {
spdlog::info("Give OSD name message received.");
setOSDName();
return;
}
}
/**
* Callback function for host side notification.
* Host applications register a single callback for all TV related notifications.
* See <DFN>VC_HDMI_NOTIFY_T</DFN> and <DFN>VC_SDTV_NOTIFY_T</DFN> in vc_hdmi.h and vc_sdtv.h
* respectively for list of reasons and respective param1 and param2
*
* @param callback_data is the context passed in during the call to vc_tv_register_callback
*
* @param reason is the notification reason
*
* @param param1 is the first optional parameter
*
* @param param2 is the second optional parameter
*
* @return void
*/
void handleTVCallback(void *callback_data, uint32_t reason, uint32_t p0, uint32_t p1) {
spdlog::debug(
"Got a TV callback: reason={reason:X} param0={p0:X} param1={p1:X}",
fmt::arg("reason", reason),
fmt::arg("p0", p0),
fmt::arg("p1", p1)
);
}
/**
* Set up CEC handlers.
*
* @return bool Whether CEC was configured successfully.
*/
bool initCEC() {
bcm_host_init();
vcos_init();
VCHI_INSTANCE_T vchi_instance;
if (vchi_initialise(&vchi_instance) != 0) {
spdlog::critical("Could not initialize VHCI");
return false;
}
if (vchi_connect(nullptr, 0, vchi_instance) != 0) {
spdlog::critical("Failed to connect to VHCI");
return false;
}
vc_vchi_cec_init(vchi_instance, nullptr, 0);
if (vc_cec_set_passive(VC_TRUE) != 0) {
spdlog::critical("Failed to enter passive mode");
return false;
}
vc_cec_register_callback(handleCECCallback, nullptr);
vc_tv_register_callback(handleTVCallback, nullptr);
if (vc_cec_register_all() != 0) {
spdlog::critical("Failed to register all opcodes");
return false;
}
// TODO: these probably aren't needed.
// vc_cec_register_command(CEC_Opcode_GivePhysicalAddress);
// vc_cec_register_command(CEC_Opcode_MenuRequest);
// vc_cec_register_command(CEC_Opcode_GetMenuLanguage);
// vc_cec_register_command(CEC_Opcode_GetCECVersion);
vc_cec_register_command(CEC_Opcode_GiveDeviceVendorID);
vc_cec_register_command(CEC_Opcode_GiveOSDName);
vc_cec_register_command(CEC_Opcode_GiveDevicePowerStatus);
if (vc_cec_set_logical_address(CEC_AllDevices_eTV, CEC_DeviceType_TV, CEC_VENDOR_ID_BROADCOM) != 0) {
spdlog::critical("Failed to set logical address");
return false;
}
// Cache the physical address of Playback 1
getPhysicalAddress(CEC_AllDevices_eDVD1);
spdlog::debug("CEC init successful");
return true;
}
/**
* Catch SIGINT and set running state of program to false.
*
* @param int s Not used
*
* @return void
*/
void handleSIGINT(int s) {
want_run = false;
}
/**
* Set the projector IP address from the command line args, if present.
*
* @param int argc argc from main.
* @param char argv argv from main.
*
* @return bool Whether LAN was configured successfully.
*/
bool initLAN(int argc, char *argv[]) {
if (argc == 2) {
// Host provided
setHost(argv[1]);
spdlog::info("Projector host is {}", argv[1]);
} else {
spdlog::critical("Invalid invocation. First arg must be the IP address of the projector.");
return false;
}
if(sendNull() < 0) {
spdlog::critical("Could not communicate with projector.");
return false;
}
spdlog::debug("LAN init successful");
return true;
}
/**
* Get an environment variable as a string.
*
* @param key The name of the environment variable.
* @param default_value The value to return if the requested key is not found in the environment.
*
* @return std::string The value of the requested key if present, otherwise an empty string.
*/
string getEnvVar(string const & key, string const default_value) {
char * val = getenv(key.c_str());
return val == NULL ? default_value : string(val);
}
/**
* Bootstrap all the things!
*
* @param int argc Passed to initLAN.
* @param char argv Passed to initLAN.
*
* @return int 0: process exited normally.
* 1: process exited due to critical CEC or LAN init error.
* -1: process failed to cleanup FIFO on exit.
*/
int main(int argc, char *argv[]) {
const string log_level = getEnvVar("LOG_LEVEL", "debug");
spdlog::set_level(spdlog::level::from_str(log_level)); // Set global log level to debug
if (!initLAN(argc, argv)) {
return 1;
}
if (!initCEC()) {
return 1;
}
if (initFIFO(systemStandby, systemActive) < 0) {
return 1;
}
// Handle SIGINT cleanly
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = handleSIGINT;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
spdlog::info("Running! Press CTRL-c to exit.");
while (want_run) {
pause();
}
return cleanupFIFO();;
}