libcec-sys 9.0.3

FFI bindings to libcec
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
/*
 * This file is part of the libCEC(R) library.
 *
 * libCEC(R) is Copyright (C) 2011-2015 Pulse-Eight Limited.  All rights reserved.
 * libCEC(R) is an original work, containing original code.
 *
 * libCEC(R) is a trademark of Pulse-Eight Limited.
 *
 * This program is dual-licensed; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 *
 *
 * Alternatively, you can license this library under a commercial license,
 * please contact Pulse-Eight Licensing for more information.
 *
 * For more information contact:
 * Pulse-Eight Licensing       <license@pulse-eight.com>
 *     http://www.pulse-eight.com/
 *     http://www.pulse-eight.net/
 */

#include "env.h"
#include "LibCEC.h"

#include "adapter/AdapterFactory.h"
#include "adapter/AdapterCommunication.h"
#include "CECProcessor.h"
#include "devices/CECAudioSystem.h"
#include "devices/CECBusDevice.h"
#include "devices/CECPlaybackDevice.h"
#include "devices/CECTV.h"
#include "p8-platform/util/timeutils.h"
#include "p8-platform/util/util.h"
#include <stdio.h>
#include <stdlib.h>

#include "CECClient.h"

using namespace CEC;
using namespace P8PLATFORM;

CLibCEC::CLibCEC(void) :
    m_iStartTime(GetTimeMs()),
    m_client(nullptr)
{
  m_cec = new CCECProcessor(this);
}

CLibCEC::~CLibCEC(void)
{
  // unregister all clients
  if (m_cec && m_cec->IsRunning())
    m_cec->UnregisterClients();

  m_clients.clear();

  // delete the adapter connection
  SAFE_DELETE(m_cec);

  // delete active client
  m_client.reset();
}

bool CLibCEC::Open(const char *strPort, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */)
{
  if (!m_cec || !strPort)
    return false;

  // open a new connection
  if (!m_cec->Start(strPort, CEC_SERIAL_DEFAULT_BAUDRATE, iTimeoutMs))
  {
    AddLog(CEC_LOG_ERROR, "could not start CEC communications");
    return false;
  }

  // register all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
  {
    if (!m_cec->RegisterClient(*it))
    {
      AddLog(CEC_LOG_ERROR, "failed to register a CEC client");
      return false;
    }
  }

  return true;
}

void CLibCEC::Close(void)
{
  if (!m_cec)
    return;

  // unregister all clients
  m_cec->UnregisterClients();

  // close the connection
  m_cec->Close();
}

int8_t CLibCEC::FindAdapters(cec_adapter *deviceList, uint8_t iBufSize, const char *strDevicePath /* = nullptr */)
{
  return CAdapterFactory(this).FindAdapters(deviceList, iBufSize, strDevicePath);
}

bool CLibCEC::StartBootloader(void)
{
  return m_cec ? m_cec->StartBootloader() : false;
}

bool CLibCEC::PingAdapter(void)
{
  return m_client ? m_client->PingAdapter() : false;
}

#if CEC_LIB_VERSION_MAJOR >= 5
bool CLibCEC::SetCallbacks(ICECCallbacks *callbacks, void *cbParam)
{
  return !!m_client ? m_client->EnableCallbacks(cbParam, callbacks) : false;
}

bool CLibCEC::DisableCallbacks(void)
{
  return !!m_client ? m_client->EnableCallbacks(nullptr, nullptr) : false;
}

bool CLibCEC::EnableCallbacks(void *cbParam, ICECCallbacks *callbacks)
{
  return SetCallbacks(callbacks, cbParam);
}
#else
bool CLibCEC::EnableCallbacks(void *cbParam, ICECCallbacks *callbacks)
{
  return !!m_client ? m_client->EnableCallbacks(cbParam, callbacks) : false;
}
#endif

bool CLibCEC::GetCurrentConfiguration(libcec_configuration *configuration)
{
  return m_client ? m_client->GetCurrentConfiguration(*configuration) : false;
}

bool CLibCEC::SetConfiguration(const libcec_configuration *configuration)
{
  return m_client ? m_client->SetConfiguration(*configuration) : false;
}

#if CEC_LIB_VERSION_MAJOR >= 5
bool CLibCEC::CanSaveConfiguration(void)
#else
bool CLibCEC::CanPersistConfiguration(void)
#endif
{
  return m_client ? m_client->CanSaveConfiguration() : false;
}

#if CEC_LIB_VERSION_MAJOR < 5
bool CLibCEC::PersistConfiguration(libcec_configuration *configuration)
{
  return SetConfiguration(configuration);
}
#endif

void CLibCEC::RescanActiveDevices(void)
{
  if (m_client)
    m_client->RescanActiveDevices();
}

bool CLibCEC::IsLibCECActiveSource(void)
{
  return m_client ? m_client->IsLibCECActiveSource() : false;
}

bool CLibCEC::Transmit(const cec_command &data)
{
  return m_client ? m_client->Transmit(data, false) : false;
}

bool CLibCEC::SetLogicalAddress(cec_logical_address iLogicalAddress)
{
  return m_client ? m_client->SetLogicalAddress(iLogicalAddress) : false;
}

bool CLibCEC::SetPhysicalAddress(uint16_t iPhysicalAddress /* = CEC_DEFAULT_PHYSICAL_ADDRESS */)
{
  return m_client ? m_client->SetPhysicalAddress(iPhysicalAddress) : false;
}

bool CLibCEC::SetHDMIPort(cec_logical_address iBaseDevice, uint8_t iPort /* = CEC_DEFAULT_HDMI_PORT */)
{
  return m_client ? m_client->SetHDMIPort(iBaseDevice, iPort) : false;
}

bool CLibCEC::PowerOnDevices(cec_logical_address address /* = CECDEVICE_TV */)
{
  return m_client ? m_client->SendPowerOnDevices(address) : false;
}

bool CLibCEC::StandbyDevices(cec_logical_address address /* = CECDEVICE_BROADCAST */)
{
  return m_client ? m_client->SendStandbyDevices(address) : false;
}

bool CLibCEC::SetActiveSource(cec_device_type type /* = CEC_DEVICE_TYPE_RESERVED */)
{
  return m_client ? m_client->SendSetActiveSource(type) : false;
}

bool CLibCEC::SetDeckControlMode(cec_deck_control_mode mode, bool bSendUpdate /* = true */)
{
  return m_client ? m_client->SendSetDeckControlMode(mode, bSendUpdate) : false;
}

bool CLibCEC::SetDeckInfo(cec_deck_info info, bool bSendUpdate /* = true */)
{
  return m_client ? m_client->SendSetDeckInfo(info, bSendUpdate) : false;
}

bool CLibCEC::SetInactiveView(void)
{
  return m_client ? m_client->SendSetInactiveView() : false;
}

bool CLibCEC::SetMenuState(cec_menu_state state, bool bSendUpdate /* = true */)
{
  return m_client ? m_client->SendSetMenuState(state, bSendUpdate) : false;
}

bool CLibCEC::SetOSDString(cec_logical_address iLogicalAddress, cec_display_control duration, const char *strMessage)
{
  return m_client ? m_client->SendSetOSDString(iLogicalAddress, duration, strMessage) : false;
}

bool CLibCEC::SwitchMonitoring(bool bEnable)
{
  return m_client ? m_client->SwitchMonitoring(bEnable) : false;
}

cec_version CLibCEC::GetDeviceCecVersion(cec_logical_address iAddress)
{
  return m_client ? m_client->GetDeviceCecVersion(iAddress) : CEC_VERSION_UNKNOWN;
}

std::string CLibCEC::GetDeviceMenuLanguage(cec_logical_address iAddress)
{
  return !!m_client ? m_client->GetDeviceMenuLanguage(iAddress) : "???";
}

uint32_t CLibCEC::GetDeviceVendorId(cec_logical_address iAddress)
{
  return m_client ? m_client->GetDeviceVendorId(iAddress) : (uint32_t)CEC_VENDOR_UNKNOWN;
}

uint16_t CLibCEC::GetDevicePhysicalAddress(cec_logical_address iAddress)
{
  return m_client ? m_client->GetDevicePhysicalAddress(iAddress) : CEC_INVALID_PHYSICAL_ADDRESS;
}

cec_power_status CLibCEC::GetDevicePowerStatus(cec_logical_address iAddress)
{
  return m_client ? m_client->GetDevicePowerStatus(iAddress) : CEC_POWER_STATUS_UNKNOWN;
}

bool CLibCEC::PollDevice(cec_logical_address iAddress)
{
  return m_client ? m_client->PollDevice(iAddress) : false;
}

cec_logical_addresses CLibCEC::GetActiveDevices(void)
{
  cec_logical_addresses addresses;
  addresses.Clear();
  if (m_client)
    addresses = m_client->GetActiveDevices();
  return addresses;
}

bool CLibCEC::IsActiveDevice(cec_logical_address iAddress)
{
  return m_client ? m_client->IsActiveDevice(iAddress) : false;
}

bool CLibCEC::IsActiveDeviceType(cec_device_type type)
{
  return m_client ? m_client->IsActiveDeviceType(type) : false;
}

uint8_t CLibCEC::VolumeUp(bool bSendRelease /* = true */)
{
  return m_client ? m_client->SendVolumeUp(bSendRelease) : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

uint8_t CLibCEC::VolumeDown(bool bSendRelease /* = true */)
{
  return m_client ? m_client->SendVolumeDown(bSendRelease) : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

#if CEC_LIB_VERSION_MAJOR >= 5
uint8_t CLibCEC::MuteAudio(void)
{
  return !!m_client ?
    m_client->SendMuteAudio() :
    (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}
#endif

bool CLibCEC::SendKeypress(cec_logical_address iDestination, cec_user_control_code key, bool bWait /* = true */)
{
  return m_client ? m_client->SendKeypress(iDestination, key, bWait) : false;
}

bool CLibCEC::SendKeyRelease(cec_logical_address iDestination, bool bWait /* = true */)
{
  return m_client ? m_client->SendKeyRelease(iDestination, bWait) : false;
}

std::string CLibCEC::GetDeviceOSDName(cec_logical_address iAddress)
{
  return !!m_client ?
      m_client->GetDeviceOSDName(iAddress) :
      "";
}

cec_logical_address CLibCEC::GetActiveSource(void)
{
  return m_client ? m_client->GetActiveSource() : CECDEVICE_UNKNOWN;
}

bool CLibCEC::IsActiveSource(cec_logical_address iAddress)
{
  return m_client ? m_client->IsActiveSource(iAddress) : false;
}
bool CLibCEC::SetStreamPath(cec_logical_address iAddress)
{
  return m_client ? m_client->SetStreamPath(iAddress) : false;
}

bool CLibCEC::SetStreamPath(uint16_t iPhysicalAddress)
{
  return m_client ? m_client->SetStreamPath(iPhysicalAddress) : false;
}

cec_logical_addresses CLibCEC::GetLogicalAddresses(void)
{
  cec_logical_addresses addresses;
  addresses.Clear();
  if (m_client)
    addresses = m_client->GetLogicalAddresses();
  return addresses;
}

cec_device_type CLibCEC::GetType(cec_logical_address address)
{
  return CCECTypeUtils::GetType(address);
}

uint16_t CLibCEC::GetMaskForType(cec_logical_address address)
{
  return CCECTypeUtils::GetMaskForType(address);
}

uint16_t CLibCEC::GetMaskForType(cec_device_type type)
{
  return CCECTypeUtils::GetMaskForType(type);
}

bool CLibCEC::IsValidPhysicalAddress(uint16_t iPhysicalAddress)
{
  return iPhysicalAddress >= CEC_MIN_PHYSICAL_ADDRESS &&
         iPhysicalAddress <= CEC_MAX_PHYSICAL_ADDRESS;
}

uint16_t CLibCEC::CheckKeypressTimeout(void)
{
  uint16_t timeout = CEC_PROCESSOR_SIGNAL_WAIT_TIME;
  // check all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
  {
    uint16_t t = (*it)->CheckKeypressTimeout();
    if (t < timeout)
      timeout = t;
  }
  return timeout;
}

void CLibCEC::AddLog(const cec_log_level level, const char *strFormat, ...)
{
  // format the message
  va_list argList;
  cec_log_message_cpp message;
  message.level = level;
  message.time = GetTimeMs() - m_iStartTime;
  va_start(argList, strFormat);
  message.message = StringUtils::FormatV(strFormat, argList);
  va_end(argList);

  // send the message to all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
    (*it)->AddLog(message);
}

void CLibCEC::AddCommand(const cec_command &command)
{
  // send the command to all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
    (*it)->QueueAddCommand(command);
}

bool CLibCEC::CommandHandlerCB(const cec_command &command)
{
  // send the command to all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
    if ((*it)->QueueCommandHandler(command))
      return true;
  return false;
}

void CLibCEC::Alert(const libcec_alert type, const libcec_parameter &param)
{
  // send the alert to all clients
  for (std::vector<CECClientPtr>::iterator it = m_clients.begin(); it != m_clients.end(); it++)
    (*it)->Alert(type, param);
}

CECClientPtr CLibCEC::RegisterClient(libcec_configuration &configuration)
{
  if (!m_cec)
    return CECClientPtr();
  if (configuration.clientVersion < LIBCEC_VERSION_TO_UINT(4, 0, 0))
  {
    AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: client version %s is no longer supported", CCECTypeUtils::VersionToString(configuration.clientVersion).c_str());
    return CECClientPtr();
  }

  // create a new client instance
  CECClientPtr newClient = CECClientPtr(new CCECClient(m_cec, configuration));
  if (!newClient)
    return newClient;
  m_clients.push_back(newClient);

  // if the default client isn't set, set it
  if (!m_client)
    m_client = newClient;

  // register the new client
  if (m_cec->CECInitialised())
  {
    if (!m_cec->RegisterClient(newClient))
      newClient = CECClientPtr();
    else
    {
      // update the current configuration
      newClient->GetCurrentConfiguration(configuration);
    }
  }

  return newClient;
}

ICECAdapter* CECInitialise(libcec_configuration *configuration)
{
  if (!configuration)
    return nullptr;

  // create a new libCEC instance
  CLibCEC *lib = new CLibCEC;

  // register a new client
  CECClientPtr client;
  return (!!lib && !!lib->RegisterClient(*configuration)) ?
    static_cast<ICECAdapter*> (lib) :
    nullptr;
}

bool CECStartBootloader(void)
{
  bool bReturn(false);
  cec_adapter deviceList[1];
  if (CAdapterFactory(nullptr).FindAdapters(deviceList, 1, 0) > 0)
  {
    CAdapterFactory factory(nullptr);
    IAdapterCommunication *comm = factory.GetInstance(deviceList[0].comm);
    if (comm)
    {
      CTimeout timeout(CEC_DEFAULT_CONNECT_TIMEOUT);
      while (timeout.TimeLeft() > 0 &&
          (bReturn = comm->Open(timeout.TimeLeft() / CEC_CONNECT_TRIES, true)) == false)
      {
        comm->Close();
        CEvent::Sleep(500);
      }
      if (comm->IsOpen())
        bReturn = comm->StartBootloader();

      delete comm;
    }
  }

  return bReturn;
}

void CECDestroy(CEC::ICECAdapter *instance)
{
  SAFE_DELETE(instance);
}

bool CLibCEC::GetDeviceInformation(const char *strPort, libcec_configuration *config, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */)
{
  if (m_cec->IsRunning())
    return false;

  return m_cec->GetDeviceInformation(strPort, config, iTimeoutMs);
}

const char *CLibCEC::GetLibInfo(void)
{
#ifndef LIB_INFO
#ifdef _WIN32
#define FEATURES "'P8 USB' 'P8 USB detect'"
#if defined(_WIN64)
#define HOST_TYPE "Windows (x64)"
#elif defined(_M_ARM64)
#define HOST_TYPE "Windows (ARM64)"
#else
#define HOST_TYPE "Windows (x86)"
#endif
#else
#define HOST_TYPE "unknown"
#define FEATURES "unknown"
#endif

  return "host: " HOST_TYPE ", features: " FEATURES ", compiled: " __DATE__;
#else
  return LIB_INFO;
#endif
}

void CLibCEC::InitVideoStandalone(void)
{
  CAdapterFactory::InitVideoStandalone();
}
uint16_t CLibCEC::GetAdapterVendorId(void) const
{
  return m_cec && m_cec->IsRunning() ? m_cec->GetAdapterVendorId() : 0;
}

uint16_t CLibCEC::GetAdapterProductId(void) const
{
  return m_cec && m_cec->IsRunning() ? m_cec->GetAdapterProductId() : 0;
}

uint8_t CLibCEC::AudioToggleMute(void)
{
  return m_client ? m_client->AudioToggleMute() : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

uint8_t CLibCEC::AudioMute(void)
{
  return m_client ? m_client->AudioMute() : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

uint8_t CLibCEC::AudioUnmute(void)
{
  return m_client ? m_client->AudioUnmute() : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

uint8_t CLibCEC::AudioStatus(void)
{
  return m_client ? m_client->AudioStatus() : (uint8_t)CEC_AUDIO_VOLUME_STATUS_UNKNOWN;
}

uint8_t CLibCEC::SystemAudioModeStatus(void)
{
  return m_client ? m_client->SystemAudioModeStatus() : (uint8_t)CEC_SYSTEM_AUDIO_STATUS_UNKNOWN;
}

int8_t CLibCEC::DetectAdapters(cec_adapter_descriptor *deviceList, uint8_t iBufSize, const char *strDevicePath /* = nullptr */, bool bQuickScan /* = false */)
{
  int8_t iAdaptersFound = CAdapterFactory(this).DetectAdapters(deviceList, iBufSize, strDevicePath);
  if (!bQuickScan)
  {
    for (int8_t iPtr = 0; iPtr < iAdaptersFound; iPtr++)
    {
      libcec_configuration config;
      GetDeviceInformation(deviceList[iPtr].strComName, &config);
      deviceList[iPtr].iFirmwareVersion   = config.iFirmwareVersion;
      deviceList[iPtr].iPhysicalAddress   = config.iPhysicalAddress;
      deviceList[iPtr].iFirmwareBuildDate = config.iFirmwareBuildDate;
      deviceList[iPtr].adapterType        = config.adapterType;
    }
  }
  return iAdaptersFound;
}

inline bool HexStrToInt(const std::string& data, uint8_t& value)
{
  int iTmp(0);
  if (sscanf(data.c_str(), "%x", &iTmp) == 1)
  {
    if (iTmp > 256)
      value = 255;
    else if (iTmp < 0)
      value = 0;
    else
      value = (uint8_t) iTmp;

    return true;
  }

  return false;
}

cec_command CLibCEC::CommandFromString(const char* strCommand)
{
  std::vector<std::string> splitCommand = StringUtils::Split(strCommand, ":");
  cec_command retval;
  unsigned long tmpVal;

  for (std::vector<std::string>::const_iterator it = splitCommand.begin(); it != splitCommand.end(); ++it)
  {
    tmpVal = strtoul((*it).c_str(), nullptr, 16);
    if (tmpVal <= 0xFF)
      retval.PushBack((uint8_t)tmpVal);
  }

  return retval;
}

void CLibCEC::PrintVersion(uint32_t version, char* buf, size_t bufSize)
{
  std::string strVersion = CCECTypeUtils::VersionToString(version);
  snprintf(buf, bufSize, "%s", strVersion.c_str());
}

bool CLibCEC::AudioEnable(bool enable)
{
  return !!m_client ?
      m_client->AudioEnable(enable) :
      false;
}

#if CEC_LIB_VERSION_MAJOR >= 5
bool CLibCEC::GetStats(struct cec_adapter_stats* stats)
{
  return !!m_client ?
      m_client->GetStats(stats) :
      false;
}
#endif